@codexhost/cli-win32-x64 0.28.2 → 0.29.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 (100) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +1894 -575
  4. package/app/console-web.js +2814 -729
  5. package/app/desktop-controller.mjs +251 -36
  6. package/app/host-runtime.mjs +36528 -32793
  7. package/app/plugins/antigravity/assets/icon.svg +34 -1
  8. package/app/plugins/antigravity/plugin.mjs +1628 -657
  9. package/app/plugins/claude-code/assets/icon.svg +1 -1
  10. package/app/plugins/claude-code/manifest.json +1 -1
  11. package/app/plugins/claude-code/plugin.mjs +256 -31
  12. package/app/plugins/codebuddy/assets/icon.svg +1 -1
  13. package/app/plugins/codebuddy/plugin.mjs +230 -28
  14. package/app/plugins/codex-usage/plugin.mjs +230 -28
  15. package/app/plugins/copilot/assets/icon.svg +3 -0
  16. package/app/plugins/copilot/manifest.json +13 -1
  17. package/app/plugins/copilot/plugin.mjs +230 -28
  18. package/app/plugins/cursor-cli/assets/icon.svg +1 -1
  19. package/app/plugins/cursor-cli/plugin.mjs +304 -44
  20. package/app/plugins/deepseek-harness/assets/icon.svg +1 -1
  21. package/app/plugins/deepseek-harness/manifest.json +1 -1
  22. package/app/plugins/deepseek-harness/plugin.mjs +230 -28
  23. package/app/plugins/devin/assets/icon.svg +1 -1
  24. package/app/plugins/devin/manifest.json +20 -0
  25. package/app/plugins/devin/plugin.mjs +354 -67
  26. package/app/plugins/grok/assets/icon.svg +4 -0
  27. package/app/plugins/grok/manifest.json +16 -2
  28. package/app/plugins/grok/plugin.mjs +230 -28
  29. package/app/plugins/hermes/assets/icon.png +0 -0
  30. package/app/plugins/hermes/manifest.json +0 -5
  31. package/app/plugins/hermes/plugin.mjs +230 -28
  32. package/app/plugins/kimi-code/assets/icon.svg +1 -1
  33. package/app/plugins/kimi-code/manifest.json +20 -0
  34. package/app/plugins/kimi-code/plugin.mjs +230 -28
  35. package/app/plugins/kiro-cli/assets/kiro-agent.svg +1 -6
  36. package/app/plugins/kiro-cli/manifest.json +24 -0
  37. package/app/plugins/kiro-cli/plugin.mjs +230 -28
  38. package/app/plugins/omp/assets/icon.svg +1 -1
  39. package/app/plugins/omp/manifest.json +0 -3
  40. package/app/plugins/omp/plugin.mjs +231 -29
  41. package/app/plugins/opencode/assets/icon.svg +5 -0
  42. package/app/plugins/opencode/manifest.json +22 -1
  43. package/app/plugins/opencode/plugin.mjs +246 -40
  44. package/app/plugins/pi/assets/icon.svg +3 -3
  45. package/app/plugins/pi/plugin.mjs +272 -30
  46. package/app/plugins/qoder/assets/icon.svg +1 -1
  47. package/app/plugins/qoder/plugin.mjs +230 -28
  48. package/app/plugins/qoder-cn/assets/icon.svg +1 -1
  49. package/app/plugins/qoder-cn/plugin.mjs +230 -28
  50. package/app/plugins/qwen-code/assets/icon.svg +1 -1
  51. package/app/plugins/qwen-code/plugin.mjs +230 -28
  52. package/app/plugins/workbuddy/assets/icon.svg +7 -9
  53. package/app/plugins/workbuddy/plugin.mjs +230 -28
  54. package/app/plugins/zcode/assets/icon.svg +1 -1
  55. package/app/plugins/zcode/plugin.mjs +230 -28
  56. package/app/renderer-extension.js +4230 -783
  57. package/app/web/apple-touch-icon.png +0 -0
  58. package/app/web/assets/index-0TnaYwHS.js +205 -0
  59. package/app/web/assets/index-aSHN2MIG.css +1 -0
  60. package/app/web/codex-agent.png +0 -0
  61. package/app/web/codex.png +0 -0
  62. package/app/web/codexhost-settings.js +1225 -305
  63. package/app/web/favicon-dark.svg +37 -4
  64. package/app/web/favicon.svg +37 -3
  65. package/app/web/icon-192.png +0 -0
  66. package/app/web/icon-512.png +0 -0
  67. package/app/web/index.html +2 -2
  68. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +65 -65
  69. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
  70. package/app/web/plugins/deepseek-ai__dsh-api-workspace-controller/client.js +1 -1
  71. package/app/web/plugins/deepseek-ai__dsh-client-file-upload/client.js +1 -1
  72. package/app/web/plugins/deepseek-ai__dsh-client-ui-attachment/client.js +1 -1
  73. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +69 -69
  74. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +73 -73
  75. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +102 -98
  76. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  77. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +2 -2
  78. package/app/web/plugins/deepseek-ai__dsh-client-ui-session/client.js +1 -1
  79. package/app/web/plugins/deepseek-ai__dsh-client-ui-shortcuts/client.js +2 -2
  80. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +2 -2
  81. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-files/client.js +1 -1
  82. package/app/web/plugins/deepseek-ai__dsh-client-ui-subagent/client.js +1 -1
  83. package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
  84. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  85. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  86. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +75 -81
  87. package/app/web/plugins.json +1 -0
  88. package/app/web-modules/server.mjs +1718 -573
  89. package/bin/codexhost.exe +0 -0
  90. package/libexec/codexhost-node-repl.exe +0 -0
  91. package/libexec/codexhost-screenshot.exe +0 -0
  92. package/libexec/codexhost-shell.exe +0 -0
  93. package/libexec/codexhost-shim.exe +0 -0
  94. package/libexec/codexhost-updater.exe +0 -0
  95. package/package.json +1 -1
  96. package/app/plugins/copilot/assets/icon.png +0 -0
  97. package/app/plugins/grok/assets/icon.png +0 -0
  98. package/app/plugins/opencode/assets/icon.png +0 -0
  99. package/app/web/assets/index-BJq8mT6r.js +0 -204
  100. package/app/web/assets/index-CMDliP5b.css +0 -1
@@ -116,17 +116,17 @@ var require_visit = __commonJS({
116
116
  visit2.BREAK = BREAK;
117
117
  visit2.SKIP = SKIP2;
118
118
  visit2.REMOVE = REMOVE;
119
- function visit_(key, node2, visitor, path15) {
120
- const ctrl = callVisitor(key, node2, visitor, path15);
119
+ function visit_(key, node2, visitor, path16) {
120
+ const ctrl = callVisitor(key, node2, visitor, path16);
121
121
  if (identity2.isNode(ctrl) || identity2.isPair(ctrl)) {
122
- replaceNode(key, path15, ctrl);
123
- return visit_(key, ctrl, visitor, path15);
122
+ replaceNode(key, path16, ctrl);
123
+ return visit_(key, ctrl, visitor, path16);
124
124
  }
125
125
  if (typeof ctrl !== "symbol") {
126
126
  if (identity2.isCollection(node2)) {
127
- path15 = Object.freeze(path15.concat(node2));
127
+ path16 = Object.freeze(path16.concat(node2));
128
128
  for (let i = 0; i < node2.items.length; ++i) {
129
- const ci = visit_(i, node2.items[i], visitor, path15);
129
+ const ci = visit_(i, node2.items[i], visitor, path16);
130
130
  if (typeof ci === "number")
131
131
  i = ci - 1;
132
132
  else if (ci === BREAK)
@@ -137,13 +137,13 @@ var require_visit = __commonJS({
137
137
  }
138
138
  }
139
139
  } else if (identity2.isPair(node2)) {
140
- path15 = Object.freeze(path15.concat(node2));
141
- const ck = visit_("key", node2.key, visitor, path15);
140
+ path16 = Object.freeze(path16.concat(node2));
141
+ const ck = visit_("key", node2.key, visitor, path16);
142
142
  if (ck === BREAK)
143
143
  return BREAK;
144
144
  else if (ck === REMOVE)
145
145
  node2.key = null;
146
- const cv = visit_("value", node2.value, visitor, path15);
146
+ const cv = visit_("value", node2.value, visitor, path16);
147
147
  if (cv === BREAK)
148
148
  return BREAK;
149
149
  else if (cv === REMOVE)
@@ -164,17 +164,17 @@ var require_visit = __commonJS({
164
164
  visitAsync.BREAK = BREAK;
165
165
  visitAsync.SKIP = SKIP2;
166
166
  visitAsync.REMOVE = REMOVE;
167
- async function visitAsync_(key, node2, visitor, path15) {
168
- const ctrl = await callVisitor(key, node2, visitor, path15);
167
+ async function visitAsync_(key, node2, visitor, path16) {
168
+ const ctrl = await callVisitor(key, node2, visitor, path16);
169
169
  if (identity2.isNode(ctrl) || identity2.isPair(ctrl)) {
170
- replaceNode(key, path15, ctrl);
171
- return visitAsync_(key, ctrl, visitor, path15);
170
+ replaceNode(key, path16, ctrl);
171
+ return visitAsync_(key, ctrl, visitor, path16);
172
172
  }
173
173
  if (typeof ctrl !== "symbol") {
174
174
  if (identity2.isCollection(node2)) {
175
- path15 = Object.freeze(path15.concat(node2));
175
+ path16 = Object.freeze(path16.concat(node2));
176
176
  for (let i = 0; i < node2.items.length; ++i) {
177
- const ci = await visitAsync_(i, node2.items[i], visitor, path15);
177
+ const ci = await visitAsync_(i, node2.items[i], visitor, path16);
178
178
  if (typeof ci === "number")
179
179
  i = ci - 1;
180
180
  else if (ci === BREAK)
@@ -185,13 +185,13 @@ var require_visit = __commonJS({
185
185
  }
186
186
  }
187
187
  } else if (identity2.isPair(node2)) {
188
- path15 = Object.freeze(path15.concat(node2));
189
- const ck = await visitAsync_("key", node2.key, visitor, path15);
188
+ path16 = Object.freeze(path16.concat(node2));
189
+ const ck = await visitAsync_("key", node2.key, visitor, path16);
190
190
  if (ck === BREAK)
191
191
  return BREAK;
192
192
  else if (ck === REMOVE)
193
193
  node2.key = null;
194
- const cv = await visitAsync_("value", node2.value, visitor, path15);
194
+ const cv = await visitAsync_("value", node2.value, visitor, path16);
195
195
  if (cv === BREAK)
196
196
  return BREAK;
197
197
  else if (cv === REMOVE)
@@ -218,23 +218,23 @@ var require_visit = __commonJS({
218
218
  }
219
219
  return visitor;
220
220
  }
221
- function callVisitor(key, node2, visitor, path15) {
221
+ function callVisitor(key, node2, visitor, path16) {
222
222
  if (typeof visitor === "function")
223
- return visitor(key, node2, path15);
223
+ return visitor(key, node2, path16);
224
224
  if (identity2.isMap(node2))
225
- return visitor.Map?.(key, node2, path15);
225
+ return visitor.Map?.(key, node2, path16);
226
226
  if (identity2.isSeq(node2))
227
- return visitor.Seq?.(key, node2, path15);
227
+ return visitor.Seq?.(key, node2, path16);
228
228
  if (identity2.isPair(node2))
229
- return visitor.Pair?.(key, node2, path15);
229
+ return visitor.Pair?.(key, node2, path16);
230
230
  if (identity2.isScalar(node2))
231
- return visitor.Scalar?.(key, node2, path15);
231
+ return visitor.Scalar?.(key, node2, path16);
232
232
  if (identity2.isAlias(node2))
233
- return visitor.Alias?.(key, node2, path15);
233
+ return visitor.Alias?.(key, node2, path16);
234
234
  return void 0;
235
235
  }
236
- function replaceNode(key, path15, node2) {
237
- const parent = path15[path15.length - 1];
236
+ function replaceNode(key, path16, node2) {
237
+ const parent = path16[path16.length - 1];
238
238
  if (identity2.isCollection(parent)) {
239
239
  parent.items[key] = node2;
240
240
  } else if (identity2.isPair(parent)) {
@@ -846,10 +846,10 @@ var require_Collection = __commonJS({
846
846
  var createNode = require_createNode();
847
847
  var identity2 = require_identity();
848
848
  var Node = require_Node();
849
- function collectionFromPath(schema, path15, value) {
849
+ function collectionFromPath(schema, path16, value) {
850
850
  let v = value;
851
- for (let i = path15.length - 1; i >= 0; --i) {
852
- const k = path15[i];
851
+ for (let i = path16.length - 1; i >= 0; --i) {
852
+ const k = path16[i];
853
853
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
854
854
  const a = [];
855
855
  a[k] = v;
@@ -868,7 +868,7 @@ var require_Collection = __commonJS({
868
868
  sourceObjects: /* @__PURE__ */ new Map()
869
869
  });
870
870
  }
871
- var isEmptyPath = (path15) => path15 == null || typeof path15 === "object" && !!path15[Symbol.iterator]().next().done;
871
+ var isEmptyPath = (path16) => path16 == null || typeof path16 === "object" && !!path16[Symbol.iterator]().next().done;
872
872
  var Collection = class extends Node.NodeBase {
873
873
  constructor(type, schema) {
874
874
  super(type);
@@ -898,11 +898,11 @@ var require_Collection = __commonJS({
898
898
  * be a Pair instance or a `{ key, value }` object, which may not have a key
899
899
  * that already exists in the map.
900
900
  */
901
- addIn(path15, value) {
902
- if (isEmptyPath(path15))
901
+ addIn(path16, value) {
902
+ if (isEmptyPath(path16))
903
903
  this.add(value);
904
904
  else {
905
- const [key, ...rest] = path15;
905
+ const [key, ...rest] = path16;
906
906
  const node2 = this.get(key, true);
907
907
  if (identity2.isCollection(node2))
908
908
  node2.addIn(rest, value);
@@ -916,8 +916,8 @@ var require_Collection = __commonJS({
916
916
  * Removes a value from the collection.
917
917
  * @returns `true` if the item was found and removed.
918
918
  */
919
- deleteIn(path15) {
920
- const [key, ...rest] = path15;
919
+ deleteIn(path16) {
920
+ const [key, ...rest] = path16;
921
921
  if (rest.length === 0)
922
922
  return this.delete(key);
923
923
  const node2 = this.get(key, true);
@@ -931,8 +931,8 @@ var require_Collection = __commonJS({
931
931
  * scalar values from their surrounding node; to disable set `keepScalar` to
932
932
  * `true` (collections are always returned intact).
933
933
  */
934
- getIn(path15, keepScalar) {
935
- const [key, ...rest] = path15;
934
+ getIn(path16, keepScalar) {
935
+ const [key, ...rest] = path16;
936
936
  const node2 = this.get(key, true);
937
937
  if (rest.length === 0)
938
938
  return !keepScalar && identity2.isScalar(node2) ? node2.value : node2;
@@ -950,8 +950,8 @@ var require_Collection = __commonJS({
950
950
  /**
951
951
  * Checks if the collection includes a value with the key `key`.
952
952
  */
953
- hasIn(path15) {
954
- const [key, ...rest] = path15;
953
+ hasIn(path16) {
954
+ const [key, ...rest] = path16;
955
955
  if (rest.length === 0)
956
956
  return this.has(key);
957
957
  const node2 = this.get(key, true);
@@ -961,8 +961,8 @@ var require_Collection = __commonJS({
961
961
  * Sets a value in this collection. For `!!set`, `value` needs to be a
962
962
  * boolean to add/remove the item from the set.
963
963
  */
964
- setIn(path15, value) {
965
- const [key, ...rest] = path15;
964
+ setIn(path16, value) {
965
+ const [key, ...rest] = path16;
966
966
  if (rest.length === 0) {
967
967
  this.set(key, value);
968
968
  } else {
@@ -3477,9 +3477,9 @@ var require_Document = __commonJS({
3477
3477
  this.contents.add(value);
3478
3478
  }
3479
3479
  /** Adds a value to the document. */
3480
- addIn(path15, value) {
3480
+ addIn(path16, value) {
3481
3481
  if (assertCollection(this.contents))
3482
- this.contents.addIn(path15, value);
3482
+ this.contents.addIn(path16, value);
3483
3483
  }
3484
3484
  /**
3485
3485
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -3554,14 +3554,14 @@ var require_Document = __commonJS({
3554
3554
  * Removes a value from the document.
3555
3555
  * @returns `true` if the item was found and removed.
3556
3556
  */
3557
- deleteIn(path15) {
3558
- if (Collection.isEmptyPath(path15)) {
3557
+ deleteIn(path16) {
3558
+ if (Collection.isEmptyPath(path16)) {
3559
3559
  if (this.contents == null)
3560
3560
  return false;
3561
3561
  this.contents = null;
3562
3562
  return true;
3563
3563
  }
3564
- return assertCollection(this.contents) ? this.contents.deleteIn(path15) : false;
3564
+ return assertCollection(this.contents) ? this.contents.deleteIn(path16) : false;
3565
3565
  }
3566
3566
  /**
3567
3567
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -3576,10 +3576,10 @@ var require_Document = __commonJS({
3576
3576
  * scalar values from their surrounding node; to disable set `keepScalar` to
3577
3577
  * `true` (collections are always returned intact).
3578
3578
  */
3579
- getIn(path15, keepScalar) {
3580
- if (Collection.isEmptyPath(path15))
3579
+ getIn(path16, keepScalar) {
3580
+ if (Collection.isEmptyPath(path16))
3581
3581
  return !keepScalar && identity2.isScalar(this.contents) ? this.contents.value : this.contents;
3582
- return identity2.isCollection(this.contents) ? this.contents.getIn(path15, keepScalar) : void 0;
3582
+ return identity2.isCollection(this.contents) ? this.contents.getIn(path16, keepScalar) : void 0;
3583
3583
  }
3584
3584
  /**
3585
3585
  * Checks if the document includes a value with the key `key`.
@@ -3590,10 +3590,10 @@ var require_Document = __commonJS({
3590
3590
  /**
3591
3591
  * Checks if the document includes a value at `path`.
3592
3592
  */
3593
- hasIn(path15) {
3594
- if (Collection.isEmptyPath(path15))
3593
+ hasIn(path16) {
3594
+ if (Collection.isEmptyPath(path16))
3595
3595
  return this.contents !== void 0;
3596
- return identity2.isCollection(this.contents) ? this.contents.hasIn(path15) : false;
3596
+ return identity2.isCollection(this.contents) ? this.contents.hasIn(path16) : false;
3597
3597
  }
3598
3598
  /**
3599
3599
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -3610,13 +3610,13 @@ var require_Document = __commonJS({
3610
3610
  * Sets a value in this document. For `!!set`, `value` needs to be a
3611
3611
  * boolean to add/remove the item from the set.
3612
3612
  */
3613
- setIn(path15, value) {
3614
- if (Collection.isEmptyPath(path15)) {
3613
+ setIn(path16, value) {
3614
+ if (Collection.isEmptyPath(path16)) {
3615
3615
  this.contents = value;
3616
3616
  } else if (this.contents == null) {
3617
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path15), value);
3617
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path16), value);
3618
3618
  } else if (assertCollection(this.contents)) {
3619
- this.contents.setIn(path15, value);
3619
+ this.contents.setIn(path16, value);
3620
3620
  }
3621
3621
  }
3622
3622
  /**
@@ -5577,9 +5577,9 @@ var require_cst_visit = __commonJS({
5577
5577
  visit2.BREAK = BREAK;
5578
5578
  visit2.SKIP = SKIP2;
5579
5579
  visit2.REMOVE = REMOVE;
5580
- visit2.itemAtPath = (cst, path15) => {
5580
+ visit2.itemAtPath = (cst, path16) => {
5581
5581
  let item = cst;
5582
- for (const [field3, index] of path15) {
5582
+ for (const [field3, index] of path16) {
5583
5583
  const tok = item?.[field3];
5584
5584
  if (tok && "items" in tok) {
5585
5585
  item = tok.items[index];
@@ -5588,23 +5588,23 @@ var require_cst_visit = __commonJS({
5588
5588
  }
5589
5589
  return item;
5590
5590
  };
5591
- visit2.parentCollection = (cst, path15) => {
5592
- const parent = visit2.itemAtPath(cst, path15.slice(0, -1));
5593
- const field3 = path15[path15.length - 1][0];
5591
+ visit2.parentCollection = (cst, path16) => {
5592
+ const parent = visit2.itemAtPath(cst, path16.slice(0, -1));
5593
+ const field3 = path16[path16.length - 1][0];
5594
5594
  const coll = parent?.[field3];
5595
5595
  if (coll && "items" in coll)
5596
5596
  return coll;
5597
5597
  throw new Error("Parent collection not found");
5598
5598
  };
5599
- function _visit(path15, item, visitor) {
5600
- let ctrl = visitor(item, path15);
5599
+ function _visit(path16, item, visitor) {
5600
+ let ctrl = visitor(item, path16);
5601
5601
  if (typeof ctrl === "symbol")
5602
5602
  return ctrl;
5603
5603
  for (const field3 of ["key", "value"]) {
5604
5604
  const token = item[field3];
5605
5605
  if (token && "items" in token) {
5606
5606
  for (let i = 0; i < token.items.length; ++i) {
5607
- const ci = _visit(Object.freeze(path15.concat([[field3, i]])), token.items[i], visitor);
5607
+ const ci = _visit(Object.freeze(path16.concat([[field3, i]])), token.items[i], visitor);
5608
5608
  if (typeof ci === "number")
5609
5609
  i = ci - 1;
5610
5610
  else if (ci === BREAK)
@@ -5615,10 +5615,10 @@ var require_cst_visit = __commonJS({
5615
5615
  }
5616
5616
  }
5617
5617
  if (typeof ctrl === "function" && field3 === "key")
5618
- ctrl = ctrl(item, path15);
5618
+ ctrl = ctrl(item, path16);
5619
5619
  }
5620
5620
  }
5621
- return typeof ctrl === "function" ? ctrl(item, path15) : ctrl;
5621
+ return typeof ctrl === "function" ? ctrl(item, path16) : ctrl;
5622
5622
  }
5623
5623
  exports.visit = visit2;
5624
5624
  }
@@ -7777,8 +7777,8 @@ function createHarnessInstaller(environment, source) {
7777
7777
  // dist/antigravity-adapter.js
7778
7778
  import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
7779
7779
  import { randomUUID as randomUUID2 } from "node:crypto";
7780
- import { stat as stat3 } from "node:fs/promises";
7781
- import path14 from "node:path";
7780
+ import { stat as stat4 } from "node:fs/promises";
7781
+ import path15 from "node:path";
7782
7782
 
7783
7783
  // ../../../node_modules/zod/v4/classic/external.js
7784
7784
  var external_exports = {};
@@ -8597,10 +8597,10 @@ function mergeDefs(...defs) {
8597
8597
  function cloneDef(schema) {
8598
8598
  return mergeDefs(schema._zod.def);
8599
8599
  }
8600
- function getElementAtPath(obj, path15) {
8601
- if (!path15)
8600
+ function getElementAtPath(obj, path16) {
8601
+ if (!path16)
8602
8602
  return obj;
8603
- return path15.reduce((acc, key) => acc?.[key], obj);
8603
+ return path16.reduce((acc, key) => acc?.[key], obj);
8604
8604
  }
8605
8605
  function promiseAllObject(promisesObj) {
8606
8606
  const keys = Object.keys(promisesObj);
@@ -8940,11 +8940,11 @@ function explicitlyAborted(x, startIndex = 0) {
8940
8940
  }
8941
8941
  return false;
8942
8942
  }
8943
- function prefixIssues(path15, issues) {
8943
+ function prefixIssues(path16, issues) {
8944
8944
  return issues.map((iss) => {
8945
8945
  var _a3;
8946
8946
  (_a3 = iss).path ?? (_a3.path = []);
8947
- iss.path.unshift(path15);
8947
+ iss.path.unshift(path16);
8948
8948
  return iss;
8949
8949
  });
8950
8950
  }
@@ -9406,16 +9406,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
9406
9406
  }
9407
9407
  function formatError(error62, mapper = (issue2) => issue2.message) {
9408
9408
  const fieldErrors = { _errors: [] };
9409
- const processError = (error63, path15 = []) => {
9409
+ const processError = (error63, path16 = []) => {
9410
9410
  for (const issue2 of error63.issues) {
9411
9411
  if (issue2.code === "invalid_union" && issue2.errors.length) {
9412
- issue2.errors.map((issues) => processError({ issues }, [...path15, ...issue2.path]));
9412
+ issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
9413
9413
  } else if (issue2.code === "invalid_key") {
9414
- processError({ issues: issue2.issues }, [...path15, ...issue2.path]);
9414
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
9415
9415
  } else if (issue2.code === "invalid_element") {
9416
- processError({ issues: issue2.issues }, [...path15, ...issue2.path]);
9416
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
9417
9417
  } else {
9418
- const fullpath = [...path15, ...issue2.path];
9418
+ const fullpath = [...path16, ...issue2.path];
9419
9419
  if (fullpath.length === 0) {
9420
9420
  fieldErrors._errors.push(mapper(issue2));
9421
9421
  } else {
@@ -9454,17 +9454,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
9454
9454
  }
9455
9455
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
9456
9456
  const result = { errors: [] };
9457
- const processError = (error63, path15 = []) => {
9457
+ const processError = (error63, path16 = []) => {
9458
9458
  var _a3;
9459
9459
  for (const issue2 of error63.issues) {
9460
9460
  if (issue2.code === "invalid_union" && issue2.errors.length) {
9461
- issue2.errors.map((issues) => processError({ issues }, [...path15, ...issue2.path]));
9461
+ issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
9462
9462
  } else if (issue2.code === "invalid_key") {
9463
- processError({ issues: issue2.issues }, [...path15, ...issue2.path]);
9463
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
9464
9464
  } else if (issue2.code === "invalid_element") {
9465
- processError({ issues: issue2.issues }, [...path15, ...issue2.path]);
9465
+ processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
9466
9466
  } else {
9467
- const fullpath = [...path15, ...issue2.path];
9467
+ const fullpath = [...path16, ...issue2.path];
9468
9468
  if (fullpath.length === 0) {
9469
9469
  result.errors.push(mapper(issue2));
9470
9470
  continue;
@@ -9503,8 +9503,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
9503
9503
  }
9504
9504
  function toDotPath(_path) {
9505
9505
  const segs = [];
9506
- const path15 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9507
- for (const seg of path15) {
9506
+ const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
9507
+ for (const seg of path16) {
9508
9508
  if (typeof seg === "number")
9509
9509
  segs.push(`[${seg}]`);
9510
9510
  else if (typeof seg === "symbol")
@@ -26642,13 +26642,13 @@ function resolveRef(ref, ctx) {
26642
26642
  if (!ref.startsWith("#")) {
26643
26643
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
26644
26644
  }
26645
- const path15 = ref.slice(1).split("/").filter(Boolean);
26646
- if (path15.length === 0) {
26645
+ const path16 = ref.slice(1).split("/").filter(Boolean);
26646
+ if (path16.length === 0) {
26647
26647
  return ctx.rootSchema;
26648
26648
  }
26649
26649
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
26650
- if (path15[0] === defsKey) {
26651
- const key = path15[1] === void 0 ? void 0 : decodeJSONPointerSegment(path15[1]);
26650
+ if (path16[0] === defsKey) {
26651
+ const key = path16[1] === void 0 ? void 0 : decodeJSONPointerSegment(path16[1]);
26652
26652
  if (!key || !ctx.defs[key]) {
26653
26653
  throw new Error(`Reference not found: ${ref}`);
26654
26654
  }
@@ -28333,7 +28333,7 @@ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("ty
28333
28333
  default: external_exports.string().optional()
28334
28334
  })
28335
28335
  ]).superRefine((field3, ctx) => {
28336
- const issue2 = (path15, message3) => ctx.addIssue({ code: "custom", path: [path15], message: message3 });
28336
+ const issue2 = (path16, message3) => ctx.addIssue({ code: "custom", path: [path16], message: message3 });
28337
28337
  if (field3.type === "number" || field3.type === "range") {
28338
28338
  const { min = -Infinity, max = Infinity, default: value } = field3;
28339
28339
  if (min > max)
@@ -28439,16 +28439,16 @@ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id2) => !reservedNa
28439
28439
  var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
28440
28440
  var hostExtensionDigestSchema = desktopExtensionHashSchema;
28441
28441
  var hostExtensionActivationIdSchema = external_exports.uuid();
28442
- 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((path15) => path15.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
28442
+ 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((path16) => path16.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
28443
28443
  var legacy = desktopExtensionManifestSchema.shape;
28444
28444
  var localized = (max, min = 0) => external_exports.strictObject({
28445
28445
  en: external_exports.string().trim().min(min).max(max),
28446
28446
  "zh-CN": external_exports.string().trim().min(min).max(max)
28447
28447
  });
28448
- var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path15) => path15.endsWith(suffix), `Expected a ${suffix} file`);
28448
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path16) => path16.endsWith(suffix), `Expected a ${suffix} file`);
28449
28449
  var moduleEntry = resourceWithSuffix(".mjs");
28450
28450
  var style = resourceWithSuffix(".css").optional();
28451
- var hostExtensionCanonicalPath = (path15) => path15.normalize("NFC").toLowerCase();
28451
+ var hostExtensionCanonicalPath = (path16) => path16.normalize("NFC").toLowerCase();
28452
28452
  var hostExtensionManifestV2Schema = external_exports.strictObject({
28453
28453
  manifestVersion: external_exports.literal(2),
28454
28454
  id: hostExtensionIdSchema,
@@ -28458,8 +28458,8 @@ var hostExtensionManifestV2Schema = external_exports.strictObject({
28458
28458
  details: localized(16384).optional(),
28459
28459
  author: legacy.author,
28460
28460
  repository: legacy.repository,
28461
- icon: legacy.icon.refine((path15) => path15 === void 0 || hostExtensionResourcePathSchema.safeParse(path15).success),
28462
- screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path15) => hostExtensionResourcePathSchema.safeParse(path15).success)),
28461
+ icon: legacy.icon.refine((path16) => path16 === void 0 || hostExtensionResourcePathSchema.safeParse(path16).success),
28462
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path16) => hostExtensionResourcePathSchema.safeParse(path16).success)),
28463
28463
  categories: legacy.categories,
28464
28464
  settingsSchema: legacy.settingsSchema,
28465
28465
  slots: legacy.slots.removeDefault().optional(),
@@ -28490,6 +28490,35 @@ function targetsForCapabilities({ hasPage, hasWidget, hasDesktop, hasWeb, hasBac
28490
28490
  }
28491
28491
  var hostExtensionBackendMethodSchema = desktopExtensionBackendMethodSchema;
28492
28492
 
28493
+ // ../../shared-contracts/dist/thread-tree-watch.js
28494
+ var THREAD_TREE_MAX_NODES = 5e3;
28495
+ var threadTreeStatusSchema = external_exports.enum(["running", "waiting", "idle", "unknown"]);
28496
+ var threadTreeHandoffSchema = external_exports.strictObject({
28497
+ sourceThreadId: hostThreadIdSchema,
28498
+ createdAtMs: external_exports.number().int().nonnegative()
28499
+ });
28500
+ var threadTreeNodeSchema = external_exports.strictObject({
28501
+ harnessId: harnessIdSchema,
28502
+ title: external_exports.string().optional(),
28503
+ status: threadTreeStatusSchema,
28504
+ archived: external_exports.boolean(),
28505
+ updatedAtMs: external_exports.number().int().nonnegative().optional()
28506
+ });
28507
+ var threadTreeSnapshotSchema = external_exports.strictObject({
28508
+ revision: external_exports.int().nonnegative(),
28509
+ parents: external_exports.record(hostThreadIdSchema, hostThreadIdSchema),
28510
+ handoffs: external_exports.record(hostThreadIdSchema, threadTreeHandoffSchema).optional(),
28511
+ nodes: external_exports.record(hostThreadIdSchema, threadTreeNodeSchema),
28512
+ truncated: external_exports.boolean()
28513
+ }).refine((snapshot) => Object.keys(snapshot.nodes).length <= THREAD_TREE_MAX_NODES, "Too many Thread tree nodes").refine(({ parents, handoffs, nodes }) => Object.entries(parents).every(([child, parent]) => Object.hasOwn(nodes, child) && Object.hasOwn(nodes, parent)) && Object.entries(handoffs ?? {}).every(([target2, { sourceThreadId }]) => Object.hasOwn(nodes, target2) && Object.hasOwn(nodes, sourceThreadId)), "Missing Thread tree node");
28514
+ var subscriptionId = external_exports.string().min(1).max(128);
28515
+ var threadTreeWatchParamsSchema = external_exports.strictObject({});
28516
+ var threadTreeUnwatchParamsSchema = external_exports.strictObject({ subscriptionId });
28517
+ var threadTreeUnwatchResultSchema = external_exports.strictObject({});
28518
+ var threadTreeWatchResultSchema = threadTreeUnwatchParamsSchema.extend({
28519
+ snapshot: threadTreeSnapshotSchema
28520
+ });
28521
+
28493
28522
  // ../../shared-contracts/dist/host-extension-management.js
28494
28523
  var HOST_EXTENSION_ZIP_MAX_BYTES = DESKTOP_EXTENSION_ZIP_MAX_BYTES;
28495
28524
  var hostExtensionRevisionSchema = external_exports.int().nonnegative();
@@ -28497,6 +28526,16 @@ var hostExtensionConfigurationSchema = external_exports.strictObject({
28497
28526
  revision: hostExtensionRevisionSchema,
28498
28527
  enabled: external_exports.array(hostExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs")
28499
28528
  });
28529
+ var hostExtensionDefaultSeedsSchema = external_exports.strictObject({
28530
+ version: external_exports.literal(1),
28531
+ seeded: external_exports.array(hostExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs")
28532
+ });
28533
+ var hostExtensionChangelogEntrySchema = external_exports.object({
28534
+ version: external_exports.string().trim().min(1).max(128),
28535
+ publishedAt: external_exports.string().trim().min(1).max(64).optional(),
28536
+ notes: external_exports.string().trim().min(1).max(8192),
28537
+ url: desktopExtensionHttpUrlSchema.optional()
28538
+ });
28500
28539
  var { downloadUrl, ...catalogMetadata } = desktopExtensionCatalogEntrySchema.shape;
28501
28540
  var hostExtensionCatalogEntrySchema = external_exports.object({
28502
28541
  ...catalogMetadata,
@@ -28510,7 +28549,10 @@ var hostExtensionCatalogEntrySchema = external_exports.object({
28510
28549
  web: external_exports.int().positive().optional(),
28511
28550
  backend: external_exports.int().positive().optional()
28512
28551
  }),
28513
- downloadUrl: downloadUrl.refine((url2) => url2.startsWith("https://"), "Expected HTTPS")
28552
+ downloadUrl: downloadUrl.refine((url2) => url2.startsWith("https://"), "Expected HTTPS"),
28553
+ featured: external_exports.boolean().optional(),
28554
+ featuredOrder: external_exports.int().nonnegative().optional(),
28555
+ changelog: external_exports.array(hostExtensionChangelogEntrySchema).max(20).optional()
28514
28556
  }).refine(({ targets, apis }) => {
28515
28557
  const derived2 = targetsForCapabilities({
28516
28558
  hasPage: Boolean(apis.page),
@@ -28529,7 +28571,8 @@ var hostExtensionCatalogSchema = external_exports.object({
28529
28571
  var hostExtensionsCatalogResultSchema = hostExtensionCatalogSchema.extend({
28530
28572
  catalogUrl: desktopExtensionHttpUrlSchema,
28531
28573
  fetchedAt: external_exports.iso.datetime(),
28532
- cached: external_exports.boolean()
28574
+ cached: external_exports.boolean(),
28575
+ stale: external_exports.boolean().optional()
28533
28576
  });
28534
28577
  var id = { id: hostExtensionIdSchema };
28535
28578
  var active = {
@@ -28538,7 +28581,7 @@ var active = {
28538
28581
  digest: hostExtensionDigestSchema
28539
28582
  };
28540
28583
  var optionalActivation = { ...id, activationId: active.activationId.optional() };
28541
- var filePath = external_exports.string().min(1).max(4096).refine((path15) => /^(?:\/|[a-z]:[/\\])/iu.test(path15) && !path15.includes("\0") && !path15.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
28584
+ var filePath = external_exports.string().min(1).max(4096).refine((path16) => /^(?:\/|[a-z]:[/\\])/iu.test(path16) && !path16.includes("\0") && !path16.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
28542
28585
  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");
28543
28586
  function base643(maxBytes) {
28544
28587
  return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
@@ -28613,6 +28656,7 @@ var HOST_EXTENSIONS_RPC = {
28613
28656
  list: "codexhost/extensions/list",
28614
28657
  snapshot: "codexhost/extensions/snapshot",
28615
28658
  catalog: "codexhost/extensions/catalog",
28659
+ catalogIcon: "codexhost/extensions/catalogIcon",
28616
28660
  install: "codexhost/extensions/install",
28617
28661
  update: "codexhost/extensions/update",
28618
28662
  enable: "codexhost/extensions/enable",
@@ -28622,7 +28666,8 @@ var HOST_EXTENSIONS_RPC = {
28622
28666
  asset: "codexhost/extensions/asset",
28623
28667
  settingsGet: "codexhost/extensions/settings/get",
28624
28668
  settingsSet: "codexhost/extensions/settings/set",
28625
- backendInvoke: "codexhost/extensions/backend/invoke"
28669
+ backendInvoke: "codexhost/extensions/backend/invoke",
28670
+ threadTree: "codexhost/extensions/threadTree"
28626
28671
  };
28627
28672
  var HOST_EXTENSION_MANAGEMENT_METHODS = Object.freeze(Object.values(HOST_EXTENSIONS_RPC));
28628
28673
  var methods = new Set(HOST_EXTENSION_MANAGEMENT_METHODS);
@@ -28644,6 +28689,10 @@ var hostExtensionsAssetResultSchema = external_exports.strictObject({
28644
28689
  base64: base643(DESKTOP_EXTENSION_ASSET_MAX_BYTES),
28645
28690
  digest: active.digest
28646
28691
  });
28692
+ var hostExtensionsCatalogIconResultSchema = external_exports.strictObject({
28693
+ mimeType: external_exports.enum(["image/png", "image/jpeg", "image/webp"]),
28694
+ base64: base643(DESKTOP_EXTENSION_ICON_MAX_BYTES)
28695
+ });
28647
28696
  var hostExtensionSettingsSchema = external_exports.strictObject({
28648
28697
  settingsRevision: hostExtensionRevisionSchema,
28649
28698
  values: jsonObjectSchema
@@ -28652,9 +28701,16 @@ var hostExtensionsRpcSchemas = {
28652
28701
  [HOST_EXTENSIONS_RPC.list]: { params: noParams, result: hostExtensionsListResultSchema },
28653
28702
  [HOST_EXTENSIONS_RPC.snapshot]: { params: noParams, result: hostExtensionsSnapshotResultSchema },
28654
28703
  [HOST_EXTENSIONS_RPC.catalog]: {
28655
- params: external_exports.strictObject({ forceRefresh: external_exports.boolean().optional() }),
28704
+ params: external_exports.strictObject({
28705
+ forceRefresh: external_exports.boolean().optional(),
28706
+ staleWhileRevalidate: external_exports.boolean().optional()
28707
+ }),
28656
28708
  result: hostExtensionsCatalogResultSchema
28657
28709
  },
28710
+ [HOST_EXTENSIONS_RPC.catalogIcon]: {
28711
+ params: external_exports.strictObject({ ...id }),
28712
+ result: hostExtensionsCatalogIconResultSchema
28713
+ },
28658
28714
  [HOST_EXTENSIONS_RPC.install]: {
28659
28715
  params: external_exports.strictObject({ source: hostExtensionInstallSourceSchema }),
28660
28716
  result: installationResult
@@ -28705,6 +28761,10 @@ var hostExtensionsRpcSchemas = {
28705
28761
  params: jsonValueSchema.optional()
28706
28762
  }),
28707
28763
  result: external_exports.strictObject({ result: jsonValueSchema })
28764
+ },
28765
+ [HOST_EXTENSIONS_RPC.threadTree]: {
28766
+ params: noParams,
28767
+ result: threadTreeSnapshotSchema
28708
28768
  }
28709
28769
  };
28710
28770
 
@@ -28713,6 +28773,104 @@ var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
28713
28773
  var threadArchiveConfirmParamsSchema = external_exports.object({ threadId: hostThreadIdSchema }).strict();
28714
28774
  var threadArchiveConfirmResultSchema = external_exports.object({ confirmed: external_exports.boolean() }).strict();
28715
28775
 
28776
+ // ../../shared-contracts/dist/telemetry.js
28777
+ var PRODUCT_TELEMETRY_GET_METHOD = "codexhost/telemetry/get";
28778
+ var PRODUCT_TELEMETRY_SET_METHOD = "codexhost/telemetry/set";
28779
+ var PRODUCT_TELEMETRY_SIGNAL_METHOD = "codexhost/telemetry/signal";
28780
+ var TELEMETRY_SURFACES = [
28781
+ "codex-desktop",
28782
+ "web",
28783
+ "web-desktop-shell",
28784
+ "web-mobile",
28785
+ "ssh-remote",
28786
+ "cli"
28787
+ ];
28788
+ var TELEMETRY_OS_LIST = ["darwin", "win32", "linux"];
28789
+ var TELEMETRY_ARCH_LIST = ["arm64", "x64", "ia32", "arm"];
28790
+ var TELEMETRY_UI_LANGUAGES = [
28791
+ "zh",
28792
+ "en",
28793
+ "ja",
28794
+ "ko",
28795
+ "de",
28796
+ "fr",
28797
+ "es",
28798
+ "pt",
28799
+ "ru",
28800
+ "other"
28801
+ ];
28802
+ var TELEMETRY_OFFICIAL_HARNESSES = [
28803
+ "codex",
28804
+ "claude-code",
28805
+ "antigravity",
28806
+ "pi",
28807
+ "opencode",
28808
+ "cursor-cli",
28809
+ "deepseek-harness",
28810
+ "grok",
28811
+ "omp",
28812
+ "qwen-code",
28813
+ "kiro-cli",
28814
+ "codebuddy",
28815
+ "workbuddy",
28816
+ "devin",
28817
+ "hermes",
28818
+ "qoder",
28819
+ "qoder-cn",
28820
+ "kimi-code",
28821
+ "zcode",
28822
+ "copilot",
28823
+ "custom"
28824
+ ];
28825
+ var TELEMETRY_REMOTE_ACCESS_CHANNELS = [
28826
+ "official-relay",
28827
+ "self-hosted-relay",
28828
+ "tailscale-serve",
28829
+ "tailscale-funnel",
28830
+ "tailscale-ip",
28831
+ "lan",
28832
+ "custom-proxy",
28833
+ "remote-peer"
28834
+ ];
28835
+ var telemetryVersionSchema = external_exports.string().min(1).max(40).regex(/^[0-9A-Za-z._+-]+$/u);
28836
+ var telemetrySurfaceSchema = external_exports.enum(TELEMETRY_SURFACES);
28837
+ var telemetryUiLanguageSchema = external_exports.enum(TELEMETRY_UI_LANGUAGES);
28838
+ var telemetryHarnessSchema = external_exports.enum(TELEMETRY_OFFICIAL_HARNESSES);
28839
+ var telemetryRemoteAccessChannelSchema = external_exports.enum(TELEMETRY_REMOTE_ACCESS_CHANNELS);
28840
+ var officialHarnessSet = new Set(TELEMETRY_OFFICIAL_HARNESSES);
28841
+ var uiLanguageSet = new Set(TELEMETRY_UI_LANGUAGES);
28842
+ var productTelemetrySettingsSchema = external_exports.object({
28843
+ enabled: external_exports.boolean(),
28844
+ forcedOffByEnv: external_exports.boolean()
28845
+ }).strict();
28846
+ var productTelemetrySetParamsSchema = external_exports.object({
28847
+ enabled: external_exports.boolean()
28848
+ }).strict();
28849
+ var productTelemetrySignalParamsSchema = external_exports.object({
28850
+ surfaces: external_exports.array(telemetrySurfaceSchema).max(12).optional(),
28851
+ harnesses: external_exports.array(telemetryHarnessSchema).max(32).optional(),
28852
+ remoteAccess: external_exports.array(telemetryRemoteAccessChannelSchema).max(12).optional()
28853
+ }).strict();
28854
+ var productTelemetryHeartbeatSchema = external_exports.object({
28855
+ dailyActive: external_exports.literal(true).optional(),
28856
+ weeklyActive: external_exports.literal(true).optional(),
28857
+ monthlyActive: external_exports.literal(true).optional(),
28858
+ newInstall: external_exports.literal(true).optional(),
28859
+ retainedD1: external_exports.literal(true).optional(),
28860
+ retainedD7: external_exports.literal(true).optional(),
28861
+ remoteAny: external_exports.literal(true).optional(),
28862
+ appVersion: telemetryVersionSchema.optional(),
28863
+ codexDesktopVersion: telemetryVersionSchema.optional(),
28864
+ os: external_exports.enum(TELEMETRY_OS_LIST).optional(),
28865
+ arch: external_exports.enum(TELEMETRY_ARCH_LIST).optional(),
28866
+ uiLanguage: telemetryUiLanguageSchema.optional(),
28867
+ surfaces: external_exports.array(telemetrySurfaceSchema).min(1).max(12).optional(),
28868
+ harnesses: external_exports.array(telemetryHarnessSchema).min(1).max(32).optional(),
28869
+ remoteAccess: external_exports.array(telemetryRemoteAccessChannelSchema).min(1).max(12).optional()
28870
+ }).strict().refine((value) => Object.keys(value).length > 0, {
28871
+ message: "Telemetry heartbeat must contain at least one countable field"
28872
+ });
28873
+
28716
28874
  // ../../shared-contracts/dist/client-channel.js
28717
28875
  var CLIENT_CHANNEL_VERSION = 1;
28718
28876
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
@@ -28740,6 +28898,7 @@ var CLIENT_CHANNEL_METHODS = [
28740
28898
  "thread/archive",
28741
28899
  THREAD_ARCHIVE_CONFIRM_METHOD,
28742
28900
  "thread/unarchive",
28901
+ "thread/delete",
28743
28902
  "turn/start",
28744
28903
  "turn/interrupt",
28745
28904
  "turn/steer",
@@ -28798,8 +28957,14 @@ var CLIENT_CHANNEL_METHODS = [
28798
28957
  "codexhost/update/check",
28799
28958
  "codexhost/update/start",
28800
28959
  "codexhost/update/status",
28960
+ "codexhost/update/macos-signing/status",
28961
+ "codexhost/update/macos-signing/setup",
28962
+ "codexhost/update/macos-signing/remove",
28801
28963
  "codexhost/announcement/get",
28802
28964
  "codexhost/announcement/acknowledge",
28965
+ PRODUCT_TELEMETRY_GET_METHOD,
28966
+ PRODUCT_TELEMETRY_SET_METHOD,
28967
+ PRODUCT_TELEMETRY_SIGNAL_METHOD,
28803
28968
  "codexhost/sessions/loaded/list"
28804
28969
  ];
28805
28970
  var clientThreadSectionsSchema = external_exports.object({
@@ -28836,7 +29001,10 @@ var clientWorkspaceSnapshotSchema = external_exports.object({
28836
29001
  pinned: external_exports.array(external_exports.string()),
28837
29002
  /** Projects Desktop placed in each custom section, keyed by the official section ID, in
28838
29003
  * Desktop's section order. Omitted when no section holds a project. */
28839
- sectionProjects: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional()
29004
+ sectionProjects: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional(),
29005
+ /** Projects pinned in Codex Desktop (`pinned-project-ids`), in Desktop order.
29006
+ * Omitted when Desktop global state has no `pinned-project-ids` array. */
29007
+ pinnedProjects: external_exports.array(external_exports.string()).optional()
28840
29008
  });
28841
29009
  var record2 = external_exports.record(external_exports.string(), external_exports.unknown());
28842
29010
  var clientChannelCursorSchema = external_exports.object({
@@ -28984,6 +29152,8 @@ var clientThreadSnapshotSchema = external_exports.object({
28984
29152
  modelProvider: external_exports.string().min(1),
28985
29153
  createdAt: external_exports.number(),
28986
29154
  updatedAt: external_exports.number(),
29155
+ /** Last conversation activity in Unix seconds, distinct from metadata writes. */
29156
+ recencyAt: external_exports.number().nullable().optional(),
28987
29157
  status: external_exports.object({ type: external_exports.string() }).passthrough(),
28988
29158
  name: external_exports.string().nullable().optional(),
28989
29159
  preview: external_exports.string().optional(),
@@ -29062,27 +29232,33 @@ var threadCatalogReadResultSchema = external_exports.object({
29062
29232
  officialCursor: external_exports.object({ live: external_exports.string().nullable(), archived: external_exports.string().nullable().optional() }).strict().optional()
29063
29233
  }).strict();
29064
29234
 
29065
- // ../../shared-contracts/dist/thread-tree-watch.js
29066
- var THREAD_TREE_MAX_NODES = 5e3;
29067
- var threadTreeStatusSchema = external_exports.enum(["running", "waiting", "idle", "unknown"]);
29068
- var threadTreeNodeSchema = external_exports.strictObject({
29069
- harnessId: harnessIdSchema,
29070
- title: external_exports.string().optional(),
29071
- status: threadTreeStatusSchema,
29072
- archived: external_exports.boolean()
29073
- });
29074
- var threadTreeSnapshotSchema = external_exports.strictObject({
29235
+ // ../../shared-contracts/dist/extension-services.js
29236
+ var extensionHarnessPresentationSchema = harnessPluginDescriptorSchema.pick({
29237
+ id: true,
29238
+ name: true,
29239
+ icon: true,
29240
+ iconStyle: true
29241
+ });
29242
+ var extensionActivitySessionSchema = external_exports.strictObject({
29243
+ threadId: external_exports.string().max(1024),
29244
+ title: external_exports.string().max(240),
29245
+ project: external_exports.string().max(240),
29246
+ harness: external_exports.strictObject({ id: external_exports.string().min(1).max(128), name: external_exports.string().min(1).max(128) }).optional(),
29247
+ state: external_exports.enum(["idle", "running", "waiting", "completed", "failed"]),
29248
+ updatedAt: external_exports.number().nonnegative()
29249
+ });
29250
+ var extensionActivitySchema = external_exports.strictObject({
29251
+ epoch: external_exports.string().max(128),
29075
29252
  revision: external_exports.int().nonnegative(),
29076
- parents: external_exports.record(hostThreadIdSchema, hostThreadIdSchema),
29077
- nodes: external_exports.record(hostThreadIdSchema, threadTreeNodeSchema),
29078
- truncated: external_exports.boolean()
29079
- }).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");
29080
- var subscriptionId = external_exports.string().min(1).max(128);
29081
- var threadTreeWatchParamsSchema = external_exports.strictObject({});
29082
- var threadTreeUnwatchParamsSchema = external_exports.strictObject({ subscriptionId });
29083
- var threadTreeUnwatchResultSchema = external_exports.strictObject({});
29084
- var threadTreeWatchResultSchema = threadTreeUnwatchParamsSchema.extend({
29085
- snapshot: threadTreeSnapshotSchema
29253
+ running: external_exports.int().nonnegative(),
29254
+ waiting: external_exports.int().nonnegative(),
29255
+ sessions: external_exports.array(extensionActivitySessionSchema).max(32).default([]),
29256
+ notifications: external_exports.array(external_exports.strictObject({
29257
+ threadId: external_exports.string().max(1024),
29258
+ key: external_exports.string().max(4096),
29259
+ kind: external_exports.enum(["completed", "failed", "approval", "question"]),
29260
+ revision: external_exports.int().nonnegative()
29261
+ })).max(256)
29086
29262
  });
29087
29263
 
29088
29264
  // ../../shared-contracts/dist/voice.js
@@ -29289,6 +29465,7 @@ var remotePeerSummarySchema = external_exports.object({
29289
29465
  updatedAt: external_exports.string()
29290
29466
  });
29291
29467
  var remotePeerListResultSchema = external_exports.object({
29468
+ localPlatform: external_exports.string().max(64).optional(),
29292
29469
  peers: external_exports.array(remotePeerSummarySchema)
29293
29470
  });
29294
29471
  var remotePeerAddParamsSchema = external_exports.object({
@@ -30042,7 +30219,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
30042
30219
  "codexhost/usage/statistics/get",
30043
30220
  "codexhost/update/check",
30044
30221
  "codexhost/update/start",
30045
- "codexhost/update/status"
30222
+ "codexhost/update/status",
30223
+ "codexhost/update/macos-signing/status",
30224
+ "codexhost/update/macos-signing/setup",
30225
+ "codexhost/update/macos-signing/remove"
30046
30226
  ]);
30047
30227
 
30048
30228
  // ../../shared-contracts/dist/version.js
@@ -30480,7 +30660,15 @@ var updateStatusSchema = external_exports.strictObject({
30480
30660
  });
30481
30661
  var updateEmptyParamsSchema = external_exports.strictObject({});
30482
30662
  var githubReleaseNotesUrlSchema = external_exports.string().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u, "release notes URL must identify a codexhost GitHub Release");
30483
- var updateCheckResultSchema = external_exports.strictObject({
30663
+ var updateBackgroundPhaseSchema = external_exports.enum(["idle", "downloading", "ready", "failed"]);
30664
+ var updateBackgroundDownloadSchema = external_exports.strictObject({
30665
+ downloadedBytes: external_exports.number().int().nonnegative(),
30666
+ totalBytes: external_exports.number().int().positive()
30667
+ }).refine((progress) => progress.downloadedBytes <= progress.totalBytes, {
30668
+ path: ["downloadedBytes"],
30669
+ message: "downloadedBytes must not exceed totalBytes"
30670
+ });
30671
+ var updateCheckResultSchema = external_exports.object({
30484
30672
  currentVersion: updateSemanticVersionSchema,
30485
30673
  installation: updateInstallationSchema.nullable(),
30486
30674
  latestVersion: updateSemanticVersionSchema.nullable(),
@@ -30489,7 +30677,12 @@ var updateCheckResultSchema = external_exports.strictObject({
30489
30677
  releaseNotes: external_exports.string().min(1).max(2e4).nullable(),
30490
30678
  releaseNotesUrl: githubReleaseNotesUrlSchema.nullable(),
30491
30679
  status: updateStatusSchema.nullable(),
30492
- error: external_exports.string().min(1).max(UPDATE_ERROR_MAX_LENGTH).nullable()
30680
+ error: external_exports.string().min(1).max(UPDATE_ERROR_MAX_LENGTH).nullable(),
30681
+ stagedVersion: updateSemanticVersionSchema.nullable().optional(),
30682
+ backgroundPhase: updateBackgroundPhaseSchema.optional(),
30683
+ backgroundDownload: updateBackgroundDownloadSchema.nullable().optional(),
30684
+ backgroundError: external_exports.string().min(1).max(UPDATE_ERROR_MAX_LENGTH).nullable().optional(),
30685
+ runningTaskCount: external_exports.number().int().nonnegative().optional()
30493
30686
  });
30494
30687
  var updateStartResultSchema = external_exports.strictObject({
30495
30688
  status: updateStatusSchema
@@ -30497,6 +30690,15 @@ var updateStartResultSchema = external_exports.strictObject({
30497
30690
  var updateStatusResultSchema = external_exports.strictObject({
30498
30691
  status: updateStatusSchema.nullable()
30499
30692
  });
30693
+ var macosLocalSigningStatusSchema = external_exports.strictObject({
30694
+ supported: external_exports.boolean(),
30695
+ enabled: external_exports.boolean(),
30696
+ certificatePresent: external_exports.boolean(),
30697
+ appSignedWithLocalCert: external_exports.boolean(),
30698
+ appPath: external_exports.string().min(1).nullable(),
30699
+ certificateName: external_exports.string().min(1),
30700
+ certificateSha1: external_exports.string().regex(/^[0-9A-Fa-f]{40}$/u).nullable()
30701
+ });
30500
30702
 
30501
30703
  // ../../shared-contracts/dist/release-announcement.js
30502
30704
  var RELEASE_ANNOUNCEMENT_MAX_THEMES = 12;
@@ -35492,16 +35694,16 @@ var Diff = class {
35492
35694
  }
35493
35695
  }
35494
35696
  }
35495
- addToPath(path15, added, removed, oldPosInc, options) {
35496
- const last = path15.lastComponent;
35697
+ addToPath(path16, added, removed, oldPosInc, options) {
35698
+ const last = path16.lastComponent;
35497
35699
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
35498
35700
  return {
35499
- oldPos: path15.oldPos + oldPosInc,
35701
+ oldPos: path16.oldPos + oldPosInc,
35500
35702
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
35501
35703
  };
35502
35704
  } else {
35503
35705
  return {
35504
- oldPos: path15.oldPos + oldPosInc,
35706
+ oldPos: path16.oldPos + oldPosInc,
35505
35707
  lastComponent: { count: 1, added, removed, previousComponent: last }
35506
35708
  };
35507
35709
  }
@@ -36754,16 +36956,16 @@ var AntigravityToolTracker = class {
36754
36956
  const diff = record3(value);
36755
36957
  if (diff.type !== "diff")
36756
36958
  return [];
36757
- const path15 = displayPath(text2(diff.path), this.options.cwd)?.path;
36758
- if (!path15)
36959
+ const path16 = displayPath(text2(diff.path), this.options.cwd)?.path;
36960
+ if (!path16)
36759
36961
  return [];
36760
36962
  const oldText = text2(diff.oldText);
36761
36963
  const newText = text2(diff.newText);
36762
36964
  const kind = diff.oldText == null ? "add" : diff.newText == null ? "delete" : "update";
36763
- const patch = createTwoFilesPatch(kind === "add" ? "/dev/null" : path15, kind === "delete" ? "/dev/null" : path15, oldText, newText, void 0, void 0, { context: 3 });
36965
+ const patch = createTwoFilesPatch(kind === "add" ? "/dev/null" : path16, kind === "delete" ? "/dev/null" : path16, oldText, newText, void 0, void 0, { context: 3 });
36764
36966
  return [
36765
36967
  {
36766
- path: path15,
36968
+ path: path16,
36767
36969
  kind,
36768
36970
  unifiedDiff: patch.length > limit ? `${patch.slice(0, limit)}
36769
36971
  [diff truncated]
@@ -37455,9 +37657,65 @@ var AntigravityAcpTransport = class {
37455
37657
 
37456
37658
  // dist/acp-usage.js
37457
37659
  import { createReadStream } from "node:fs";
37458
- import path8 from "node:path";
37660
+ import path9 from "node:path";
37459
37661
  import { createInterface } from "node:readline";
37460
37662
 
37663
+ // dist/native-db-fingerprint.js
37664
+ import { open as open3, stat as stat2 } from "node:fs/promises";
37665
+ function isMissing(error62) {
37666
+ const code = error62?.code;
37667
+ return code === "ENOENT" || code === "ENOTDIR";
37668
+ }
37669
+ async function readHeadHex(filePath2, offset, length) {
37670
+ let handle;
37671
+ try {
37672
+ handle = await open3(filePath2, "r");
37673
+ const buffer = Buffer.allocUnsafe(length);
37674
+ const { bytesRead } = await handle.read(buffer, 0, length, offset);
37675
+ return buffer.subarray(0, bytesRead).toString("hex");
37676
+ } catch (error62) {
37677
+ if (isMissing(error62))
37678
+ return "missing";
37679
+ return null;
37680
+ } finally {
37681
+ await handle?.close().catch(() => void 0);
37682
+ }
37683
+ }
37684
+ async function readFileFingerprint(filePath2) {
37685
+ try {
37686
+ const info = await stat2(filePath2, { bigint: true });
37687
+ return `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
37688
+ } catch (error62) {
37689
+ if (isMissing(error62))
37690
+ return "missing";
37691
+ return null;
37692
+ }
37693
+ }
37694
+ async function readSqlitePart(filePath2, headerOffset, headerLength) {
37695
+ let info;
37696
+ try {
37697
+ info = await stat2(filePath2, { bigint: true });
37698
+ } catch (error62) {
37699
+ if (isMissing(error62))
37700
+ return "missing";
37701
+ return null;
37702
+ }
37703
+ const head = info.size > BigInt(headerOffset) ? await readHeadHex(filePath2, headerOffset, headerLength) : "";
37704
+ if (head === null)
37705
+ return null;
37706
+ return `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${head}`;
37707
+ }
37708
+ async function readNativeDbFingerprint(dbPath) {
37709
+ const [dbPart, walPart, shmHead] = await Promise.all([
37710
+ readSqlitePart(dbPath, 24, 4),
37711
+ readSqlitePart(`${dbPath}-wal`, 0, 32),
37712
+ readHeadHex(`${dbPath}-shm`, 0, 48)
37713
+ ]);
37714
+ if (dbPart === null || walPart === null || shmHead === null)
37715
+ return null;
37716
+ return `${dbPart}|${walPart}|${shmHead}`;
37717
+ }
37718
+
37461
37719
  // dist/native-request-timing.js
37462
37720
  import path7 from "node:path";
37463
37721
 
@@ -37666,6 +37924,98 @@ async function readAntigravityRequestMetadata(nativeSessionId, home, requests, n
37666
37924
  }
37667
37925
  }
37668
37926
 
37927
+ // dist/native-turn-boundaries.js
37928
+ import { access } from "node:fs/promises";
37929
+ import os2 from "node:os";
37930
+ import path8 from "node:path";
37931
+ import { setTimeout as delay } from "node:timers/promises";
37932
+ function nativeConversationDbPath(id2, home = os2.homedir()) {
37933
+ return path8.join(home, ".gemini", "antigravity-cli", "conversations", `${id2}.db`);
37934
+ }
37935
+ async function readNativeTurnCount(dbPath) {
37936
+ return withReadSnapshot(dbPath, countInputs);
37937
+ }
37938
+ function countInputs(db) {
37939
+ return Number(db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
37940
+ }
37941
+ function latestInputCreatedAtMs(db) {
37942
+ const columns = db.prepare("PRAGMA table_info(steps)").all();
37943
+ if (!columns.some((column) => column.name === "metadata"))
37944
+ return void 0;
37945
+ const row = db.prepare("SELECT metadata FROM steps WHERE step_type = 14 ORDER BY idx DESC LIMIT 1").get();
37946
+ return nativeStepCreatedAtMs(row?.metadata);
37947
+ }
37948
+ async function withReadSnapshot(dbPath, read) {
37949
+ await access(dbPath);
37950
+ const { DatabaseSync } = await import("node:sqlite");
37951
+ const db = new DatabaseSync(dbPath, { readOnly: true });
37952
+ try {
37953
+ db.exec("BEGIN");
37954
+ return read(db);
37955
+ } finally {
37956
+ db.close();
37957
+ }
37958
+ }
37959
+ var COMMIT_BUDGET_MS = 250;
37960
+ var COMMIT_RECHECK_MS = [0, 25, 75, 175, COMMIT_BUDGET_MS];
37961
+ async function observeNativeTurnCount(dbPath, before, submittedAtMs, completedAtMs, retry, signal, options) {
37962
+ const expectedInputs = Math.max(1, options?.expectedInputs ?? 1);
37963
+ const latestSubmittedAtMs = options?.latestSubmittedAtMs ?? submittedAtMs;
37964
+ const started = performance.now();
37965
+ for (const at of retry ? COMMIT_RECHECK_MS : [0]) {
37966
+ if (at > 0) {
37967
+ const elapsed = performance.now() - started;
37968
+ if (elapsed >= COMMIT_BUDGET_MS && at < COMMIT_BUDGET_MS)
37969
+ continue;
37970
+ if (elapsed < at)
37971
+ await delay(Math.ceil(at - elapsed), void 0, { signal }).catch(() => void 0);
37972
+ if (signal.aborted)
37973
+ break;
37974
+ }
37975
+ try {
37976
+ const confirmed = await withReadSnapshot(dbPath, (db) => {
37977
+ const count4 = countInputs(db);
37978
+ const minCount = retry && before !== null ? before + expectedInputs : (before ?? 0) + 1;
37979
+ if (count4 < minCount)
37980
+ return null;
37981
+ const createdAtMs = latestInputCreatedAtMs(db);
37982
+ if (createdAtMs !== void 0) {
37983
+ if (retry && latestSubmittedAtMs > submittedAtMs) {
37984
+ return createdAtMs >= latestSubmittedAtMs && createdAtMs <= completedAtMs ? count4 : null;
37985
+ }
37986
+ return createdAtMs > submittedAtMs && createdAtMs <= completedAtMs ? count4 : null;
37987
+ }
37988
+ return before !== null && count4 <= before + expectedInputs ? count4 : null;
37989
+ });
37990
+ if (confirmed !== null)
37991
+ return confirmed;
37992
+ } catch (error62) {
37993
+ const { code } = nativeHistoryError(error62);
37994
+ if (code !== "sessionBusy" && code !== "sessionNotFound")
37995
+ break;
37996
+ }
37997
+ }
37998
+ return null;
37999
+ }
38000
+ function nativeHistoryError(error62) {
38001
+ const sqlite = error62;
38002
+ if (sqlite?.code === "ERR_SQLITE_ERROR" && sqlite.errcode !== void 0) {
38003
+ const primary = sqlite.errcode & 255;
38004
+ if (primary === 5 || primary === 6)
38005
+ return {
38006
+ code: "sessionBusy",
38007
+ message: "Antigravity native history database is locked; retry shortly",
38008
+ retryable: true
38009
+ };
38010
+ }
38011
+ const missing = sqlite?.code === "ENOENT";
38012
+ return {
38013
+ code: missing ? "sessionNotFound" : "nativeFailure",
38014
+ message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
38015
+ retryable: false
38016
+ };
38017
+ }
38018
+
37669
38019
  // dist/acp-usage.js
37670
38020
  function normalizeAntigravityUsageModel(rawModel) {
37671
38021
  if (typeof rawModel !== "string" || !rawModel.trim())
@@ -37767,6 +38117,7 @@ function usageMatches(actual, expected, exact) {
37767
38117
  }
37768
38118
  var AntigravitySessionUsageTracker = class {
37769
38119
  #file;
38120
+ #dbPath;
37770
38121
  #nativeSessionId;
37771
38122
  #home;
37772
38123
  #timingTurn = { startedAtMs: 0 };
@@ -37787,12 +38138,18 @@ var AntigravitySessionUsageTracker = class {
37787
38138
  #turnCollectionSteps = /* @__PURE__ */ new Set();
37788
38139
  #awaitingTiming = /* @__PURE__ */ new Map();
37789
38140
  #awaitingContextWindow = /* @__PURE__ */ new Map();
38141
+ #transcriptFingerprint = null;
38142
+ #cachedTranscript = null;
38143
+ #metadataFingerprint = null;
38144
+ #metadataNeededKey = null;
38145
+ #cachedMetadata = null;
37790
38146
  constructor(options) {
37791
38147
  this.#nativeSessionId = options.nativeSessionId;
37792
38148
  this.#home = options.homedir;
37793
38149
  this.#expectedInitialTurns = options.expectedInitialTurns ?? 0;
37794
38150
  this.#activeModel = normalizeAntigravityUsageModel(options.activeModel).model;
37795
- this.#file = path8.join(options.homedir, ".gemini", "antigravity-cli", "brain", options.nativeSessionId, ".system_generated", "logs", "transcript.jsonl");
38151
+ this.#dbPath = nativeConversationDbPath(options.nativeSessionId, options.homedir);
38152
+ this.#file = path9.join(options.homedir, ".gemini", "antigravity-cli", "brain", options.nativeSessionId, ".system_generated", "logs", "transcript.jsonl");
37796
38153
  }
37797
38154
  setActiveModel(rawModel) {
37798
38155
  this.#activeModel = normalizeAntigravityUsageModel(rawModel).model;
@@ -38034,15 +38391,19 @@ var AntigravitySessionUsageTracker = class {
38034
38391
  ...interval ? { startedAtMs, completedAtMs, timedOutputTokens: interval.outputTokens } : {}
38035
38392
  });
38036
38393
  }
38037
- async #read(signal) {
38394
+ async #readTranscript(signal) {
38038
38395
  signal?.throwIfAborted();
38396
+ const fingerprint = await readFileFingerprint(this.#file);
38397
+ signal?.throwIfAborted();
38398
+ if (fingerprint !== null && fingerprint === this.#transcriptFingerprint && this.#cachedTranscript !== null && this.#cachedTranscript.fileComplete) {
38399
+ return this.#cachedTranscript;
38400
+ }
38039
38401
  const stream = createReadStream(this.#file, { encoding: "utf8", signal });
38040
38402
  const lines = createInterface({ input: stream, crlfDelay: Infinity });
38041
- const result = {
38403
+ const parsed = {
38042
38404
  steps: /* @__PURE__ */ new Map(),
38043
38405
  toolCallSteps: /* @__PURE__ */ new Set(),
38044
- complete: true,
38045
- metadata: null
38406
+ fileComplete: true
38046
38407
  };
38047
38408
  try {
38048
38409
  for await (const line of lines) {
@@ -38055,13 +38416,13 @@ var AntigravitySessionUsageTracker = class {
38055
38416
  if (!record4 || typeof record4 !== "object" || Array.isArray(record4))
38056
38417
  throw new Error();
38057
38418
  } catch {
38058
- result.complete = false;
38419
+ parsed.fileComplete = false;
38059
38420
  continue;
38060
38421
  }
38061
38422
  if (record4.type !== "PLANNER_RESPONSE")
38062
38423
  continue;
38063
38424
  if (!count2(record4.step_index)) {
38064
- result.complete = false;
38425
+ parsed.fileComplete = false;
38065
38426
  continue;
38066
38427
  }
38067
38428
  let request = null;
@@ -38081,21 +38442,34 @@ var AntigravitySessionUsageTracker = class {
38081
38442
  });
38082
38443
  } catch {
38083
38444
  }
38084
- result.steps.set(record4.step_index, request);
38445
+ parsed.steps.set(record4.step_index, request);
38085
38446
  if (record4.tool_calls !== void 0 && (!Array.isArray(record4.tool_calls) || record4.tool_calls.length > 0))
38086
- result.toolCallSteps.add(record4.step_index);
38447
+ parsed.toolCallSteps.add(record4.step_index);
38087
38448
  else
38088
- result.toolCallSteps.delete(record4.step_index);
38449
+ parsed.toolCallSteps.delete(record4.step_index);
38089
38450
  }
38090
38451
  } catch (error62) {
38091
38452
  signal?.throwIfAborted();
38092
38453
  if (error62.code !== "ENOENT" || this.#expectedInitialTurns > 0)
38093
- result.complete = false;
38454
+ parsed.fileComplete = false;
38094
38455
  } finally {
38095
38456
  lines.close();
38096
38457
  stream.destroy();
38097
38458
  }
38098
- result.complete &&= [...result.steps.values()].every((request) => request !== null) && [...this.#consumed.keys()].every((step) => result.steps.has(step));
38459
+ if (fingerprint !== null) {
38460
+ this.#transcriptFingerprint = fingerprint;
38461
+ this.#cachedTranscript = parsed;
38462
+ }
38463
+ return parsed;
38464
+ }
38465
+ async #read(signal) {
38466
+ const parsed = await this.#readTranscript(signal);
38467
+ const result = {
38468
+ steps: parsed.steps,
38469
+ toolCallSteps: parsed.toolCallSteps,
38470
+ complete: parsed.fileComplete && [...parsed.steps.values()].every((request) => request !== null) && [...this.#consumed.keys()].every((step) => parsed.steps.has(step)),
38471
+ metadata: null
38472
+ };
38099
38473
  const needed = new Set(this.#awaitingTiming.keys());
38100
38474
  for (const step of this.#awaitingContextWindow.keys()) {
38101
38475
  if (result.steps.has(step))
@@ -38104,8 +38478,21 @@ var AntigravitySessionUsageTracker = class {
38104
38478
  for (const step of result.steps.keys())
38105
38479
  if (!this.#consumed.has(step))
38106
38480
  needed.add(step);
38107
- if (needed.size > 0)
38108
- result.metadata = await readAntigravityRequestMetadata(this.#nativeSessionId, this.#home, result.steps, needed);
38481
+ if (needed.size > 0) {
38482
+ const neededKey = [...needed].sort((left, right) => left - right).join(",");
38483
+ const dbFingerprint = await readNativeDbFingerprint(this.#dbPath);
38484
+ signal?.throwIfAborted();
38485
+ if (dbFingerprint !== null && dbFingerprint === this.#metadataFingerprint && neededKey === this.#metadataNeededKey) {
38486
+ result.metadata = this.#cachedMetadata;
38487
+ } else {
38488
+ result.metadata = await readAntigravityRequestMetadata(this.#nativeSessionId, this.#home, result.steps, needed);
38489
+ if (dbFingerprint !== null && result.metadata !== null) {
38490
+ this.#metadataFingerprint = dbFingerprint;
38491
+ this.#metadataNeededKey = neededKey;
38492
+ this.#cachedMetadata = result.metadata;
38493
+ }
38494
+ }
38495
+ }
38109
38496
  signal?.throwIfAborted();
38110
38497
  return result;
38111
38498
  }
@@ -38127,9 +38514,9 @@ function antigravityDelegationInstructions(environment) {
38127
38514
 
38128
38515
  // dist/fork.js
38129
38516
  import { randomUUID } from "node:crypto";
38130
- import { access as access2, cp, mkdir, open as open3, rm as rm2 } from "node:fs/promises";
38517
+ import { access as access2, cp, mkdir as mkdir2, open as open4, rm as rm3 } from "node:fs/promises";
38131
38518
  import os4 from "node:os";
38132
- import path11 from "node:path";
38519
+ import path12 from "node:path";
38133
38520
 
38134
38521
  // dist/native-trajectory-metadata.js
38135
38522
  var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
@@ -38226,96 +38613,371 @@ function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
38226
38613
  return Buffer.concat(chunks);
38227
38614
  }
38228
38615
 
38229
- // dist/native-turn-boundaries.js
38230
- import { access } from "node:fs/promises";
38231
- import os2 from "node:os";
38232
- import path9 from "node:path";
38233
- import { setTimeout as delay } from "node:timers/promises";
38234
- function nativeConversationDbPath(id2, home = os2.homedir()) {
38235
- return path9.join(home, ".gemini", "antigravity-cli", "conversations", `${id2}.db`);
38616
+ // dist/prompt-windows.js
38617
+ import { appendFile, mkdir, readFile, rm as rm2 } from "node:fs/promises";
38618
+ import path11 from "node:path";
38619
+ import { setTimeout as delay2 } from "node:timers/promises";
38620
+
38621
+ // dist/usage-statistics.js
38622
+ import { lstat, readdir } from "node:fs/promises";
38623
+ import os3 from "node:os";
38624
+ import path10 from "node:path";
38625
+
38626
+ // ../../harness-adapter/dist/usage-statistics.js
38627
+ import { createReadStream as createReadStream2 } from "node:fs";
38628
+ var HarnessUsageSourceChangedError = class extends Error {
38629
+ code = "HARNESS_USAGE_SOURCE_CHANGED";
38630
+ /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
38631
+ static is(error62) {
38632
+ return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === "HARNESS_USAGE_SOURCE_CHANGED";
38633
+ }
38634
+ };
38635
+ var MAX_SESSION_ID_LENGTH = 512;
38636
+ var MAX_CWD_LENGTH = 4096;
38637
+ var MAX_SESSION_TITLE_LENGTH = 200;
38638
+ function usageSessionTitle(value) {
38639
+ if (typeof value !== "string")
38640
+ return void 0;
38641
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
38642
+ if (!normalized)
38643
+ return void 0;
38644
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
38645
+ return normalized;
38646
+ let title = "";
38647
+ for (const character of normalized) {
38648
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
38649
+ break;
38650
+ title += character;
38651
+ }
38652
+ return `${title.trimEnd()}…`;
38236
38653
  }
38237
- async function readNativeTurnCount(dbPath) {
38238
- return withReadSnapshot(dbPath, countInputs);
38654
+ function sessionIdOk(value) {
38655
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
38239
38656
  }
38240
- function countInputs(db) {
38241
- return Number(db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
38657
+ function cwdOk(value) {
38658
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
38242
38659
  }
38243
- function latestInputCreatedAtMs(db) {
38244
- const columns = db.prepare("PRAGMA table_info(steps)").all();
38245
- if (!columns.some((column) => column.name === "metadata"))
38246
- return void 0;
38247
- const row = db.prepare("SELECT metadata FROM steps WHERE step_type = 14 ORDER BY idx DESC LIMIT 1").get();
38248
- return nativeStepCreatedAtMs(row?.metadata);
38660
+ function withUsageSession(entry, session) {
38661
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
38662
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
38663
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
38664
+ if (sessionId === void 0 && cwd === void 0)
38665
+ return entry;
38666
+ return {
38667
+ ...entry,
38668
+ ...sessionId !== void 0 ? { sessionId } : {},
38669
+ ...cwd !== void 0 ? { cwd } : {},
38670
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
38671
+ };
38249
38672
  }
38250
- async function withReadSnapshot(dbPath, read) {
38251
- await access(dbPath);
38252
- const { DatabaseSync } = await import("node:sqlite");
38253
- const db = new DatabaseSync(dbPath, { readOnly: true });
38673
+ var JSONL_CHUNK_BYTES = 128 * 1024;
38674
+ var JSONL_HEADER_CHUNK_BYTES = 16 * 1024;
38675
+ function concatParts(parts, total) {
38676
+ const [single] = parts;
38677
+ return single && parts.length === 1 ? single : Buffer.concat(parts, total);
38678
+ }
38679
+ async function* jsonlLineSlices(file2, signal, highWaterMark) {
38680
+ const stream = createReadStream2(file2, { highWaterMark, signal });
38681
+ let parts = [];
38682
+ let buffered = 0;
38254
38683
  try {
38255
- db.exec("BEGIN");
38256
- return read(db);
38684
+ for await (const raw of stream) {
38685
+ signal.throwIfAborted();
38686
+ const chunk = raw;
38687
+ let start = 0;
38688
+ let end;
38689
+ while ((end = chunk.indexOf(10, start)) >= 0) {
38690
+ const lineEnd = end > start && chunk[end - 1] === 13 ? end - 1 : end;
38691
+ const slice = chunk.subarray(start, lineEnd);
38692
+ if (buffered === 0) {
38693
+ yield slice;
38694
+ } else {
38695
+ if (slice.length > 0) {
38696
+ parts.push(slice);
38697
+ buffered += slice.length;
38698
+ }
38699
+ const combined = concatParts(parts, buffered);
38700
+ parts = [];
38701
+ buffered = 0;
38702
+ yield combined.length > 0 && combined[combined.length - 1] === 13 ? combined.subarray(0, combined.length - 1) : combined;
38703
+ }
38704
+ start = end + 1;
38705
+ }
38706
+ if (start < chunk.length) {
38707
+ const rest = chunk.subarray(start);
38708
+ parts.push(rest);
38709
+ buffered += rest.length;
38710
+ }
38711
+ }
38712
+ if (buffered > 0) {
38713
+ const combined = concatParts(parts, buffered);
38714
+ yield combined.length > 0 && combined[combined.length - 1] === 13 ? combined.subarray(0, combined.length - 1) : combined;
38715
+ }
38257
38716
  } finally {
38258
- db.close();
38717
+ stream.destroy();
38259
38718
  }
38260
38719
  }
38261
- var COMMIT_BUDGET_MS = 250;
38262
- var COMMIT_RECHECK_MS = [0, 25, 75, 175, COMMIT_BUDGET_MS];
38263
- async function observeNativeTurnCount(dbPath, before, submittedAtMs, completedAtMs, retry, signal, options) {
38264
- const expectedInputs = Math.max(1, options?.expectedInputs ?? 1);
38265
- const latestSubmittedAtMs = options?.latestSubmittedAtMs ?? submittedAtMs;
38266
- const started = performance.now();
38267
- for (const at of retry ? COMMIT_RECHECK_MS : [0]) {
38268
- if (at > 0) {
38269
- const elapsed = performance.now() - started;
38270
- if (elapsed >= COMMIT_BUDGET_MS && at < COMMIT_BUDGET_MS)
38271
- continue;
38272
- if (elapsed < at)
38273
- await delay(Math.ceil(at - elapsed), void 0, { signal }).catch(() => void 0);
38274
- if (signal.aborted)
38275
- break;
38276
- }
38720
+ async function* jsonlRecords(file2, marker, signal) {
38721
+ const markerBytes = marker.length > 0 ? Buffer.from(marker, "utf8") : null;
38722
+ for await (const rawLine of jsonlLineSlices(file2, signal, JSONL_CHUNK_BYTES)) {
38723
+ if (markerBytes && !rawLine.includes(markerBytes))
38724
+ continue;
38725
+ const line = rawLine.toString("utf8");
38726
+ if (!line.includes(marker))
38727
+ continue;
38728
+ let value;
38277
38729
  try {
38278
- const confirmed = await withReadSnapshot(dbPath, (db) => {
38279
- const count4 = countInputs(db);
38280
- const minCount = retry && before !== null ? before + expectedInputs : (before ?? 0) + 1;
38281
- if (count4 < minCount)
38282
- return null;
38283
- const createdAtMs = latestInputCreatedAtMs(db);
38284
- if (createdAtMs !== void 0) {
38285
- if (retry && latestSubmittedAtMs > submittedAtMs) {
38286
- return createdAtMs >= latestSubmittedAtMs && createdAtMs <= completedAtMs ? count4 : null;
38287
- }
38288
- return createdAtMs > submittedAtMs && createdAtMs <= completedAtMs ? count4 : null;
38730
+ value = JSON.parse(line);
38731
+ } catch {
38732
+ continue;
38733
+ }
38734
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
38735
+ yield value;
38736
+ }
38737
+ }
38738
+ }
38739
+ function nativeTimeMs(value) {
38740
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
38741
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
38742
+ }
38743
+
38744
+ // dist/usage-statistics.js
38745
+ function count3(value) {
38746
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
38747
+ }
38748
+ function antigravityHome(environment) {
38749
+ return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os3.homedir();
38750
+ }
38751
+ function transcriptPath(brainRoot, conversationId) {
38752
+ return path10.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
38753
+ }
38754
+ function isMissing2(error62) {
38755
+ const code = error62?.code;
38756
+ return code === "ENOENT" || code === "ENOTDIR";
38757
+ }
38758
+ async function lstatIfPresent(target2) {
38759
+ try {
38760
+ return await lstat(target2);
38761
+ } catch (error62) {
38762
+ if (isMissing2(error62))
38763
+ return null;
38764
+ throw error62;
38765
+ }
38766
+ }
38767
+ async function transcriptFingerprint(file2) {
38768
+ const logs = path10.dirname(file2);
38769
+ for (const directory of [path10.dirname(logs), logs]) {
38770
+ if (!(await lstatIfPresent(directory))?.isDirectory())
38771
+ return null;
38772
+ }
38773
+ const info = await lstatIfPresent(file2);
38774
+ return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
38775
+ }
38776
+ var LIST_CONCURRENCY = 32;
38777
+ async function listTranscripts(brainRoot, signal) {
38778
+ signal.throwIfAborted();
38779
+ const entries = await readdir(brainRoot, { withFileTypes: true }).catch((error62) => {
38780
+ if (error62.code === "ENOENT")
38781
+ return null;
38782
+ throw error62;
38783
+ });
38784
+ if (!entries)
38785
+ return [];
38786
+ const directories = entries.filter((entry) => entry.isDirectory());
38787
+ const sources = [];
38788
+ for (let offset = 0; offset < directories.length; offset += LIST_CONCURRENCY) {
38789
+ signal.throwIfAborted();
38790
+ const batch = directories.slice(offset, offset + LIST_CONCURRENCY);
38791
+ const inspected = await Promise.all(batch.map(async (entry) => {
38792
+ const file2 = transcriptPath(brainRoot, entry.name);
38793
+ const fingerprint = await transcriptFingerprint(file2);
38794
+ return fingerprint ? { id: file2, fingerprint } : null;
38795
+ }));
38796
+ for (const source of inspected) {
38797
+ if (source)
38798
+ sources.push(source);
38799
+ }
38800
+ }
38801
+ signal.throwIfAborted();
38802
+ return sources;
38803
+ }
38804
+ async function readAntigravityUsage(file2, signal) {
38805
+ const sessionId = path10.basename(path10.resolve(file2, "..", "..", ".."));
38806
+ const requests = /* @__PURE__ */ new Map();
38807
+ for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
38808
+ if (record4.type !== "PLANNER_RESPONSE")
38809
+ continue;
38810
+ const step = count3(record4.step_index);
38811
+ const input3 = count3(record4.input_tokens);
38812
+ const output2 = count3(record4.output_tokens);
38813
+ const cached2 = count3(record4.cache_read_tokens);
38814
+ const at = nativeTimeMs(record4.created_at);
38815
+ if (step === null || input3 === null || output2 === null || at === null)
38816
+ continue;
38817
+ const identity2 = normalizeAntigravityUsageModel(record4.model);
38818
+ requests.set(step, withUsageSession({
38819
+ id: `${String(record4.created_at)}:${step}:${input3}:${cached2 ?? "-"}:${output2}`,
38820
+ occurredAtMs: at,
38821
+ ...identity2,
38822
+ inputTokens: input3 + (cached2 ?? 0),
38823
+ ...cached2 !== null ? {
38824
+ cachedInputTokens: cached2,
38825
+ ...hasImplicitZeroCacheWrite(identity2) ? { cacheWriteInputTokens: 0 } : {}
38826
+ } : {},
38827
+ outputTokens: output2
38828
+ }, { sessionId }));
38829
+ }
38830
+ return [...requests.values()];
38831
+ }
38832
+ function createAntigravityUsageStatistics(environment) {
38833
+ const brainRoot = nativeBrainRoot(antigravityHome(environment));
38834
+ let listed = /* @__PURE__ */ new Map();
38835
+ return Object.freeze({
38836
+ async listSources(signal) {
38837
+ const sources = await listTranscripts(brainRoot, signal);
38838
+ listed = new Map(sources.map(({ id: id2, fingerprint }) => [id2, fingerprint]));
38839
+ return sources;
38840
+ },
38841
+ async readSource(id2, signal) {
38842
+ const expected = listed.get(id2);
38843
+ let entries;
38844
+ try {
38845
+ entries = await readAntigravityUsage(id2, signal);
38846
+ } catch (error62) {
38847
+ if (expected !== void 0 && isMissing2(error62)) {
38848
+ throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
38289
38849
  }
38290
- return before !== null && count4 <= before + expectedInputs ? count4 : null;
38291
- });
38292
- if (confirmed !== null)
38293
- return confirmed;
38850
+ throw error62;
38851
+ }
38852
+ if (expected !== void 0 && await transcriptFingerprint(id2) !== expected) {
38853
+ throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
38854
+ }
38855
+ return entries;
38856
+ }
38857
+ });
38858
+ }
38859
+
38860
+ // dist/prompt-windows.js
38861
+ var VALID_SESSION_ID = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u;
38862
+ var WINDOWS_RETRY_DELAYS_MS = [10, 30, 70, 150, 300];
38863
+ function promptWindowsDirectory(environment) {
38864
+ const dataDir = environment.CODEXHOST_DATA_DIR?.trim() || path11.join(antigravityHome(environment), ".codexhost");
38865
+ return path11.resolve(dataDir, "antigravity-prompt-windows");
38866
+ }
38867
+ function promptWindowsPath(sessionId, environment) {
38868
+ if (!VALID_SESSION_ID.test(sessionId))
38869
+ throw new Error("Invalid native Session ID");
38870
+ return path11.join(promptWindowsDirectory(environment), `${sessionId}.jsonl`);
38871
+ }
38872
+ function isValidWindow(value, requireFiniteEnd) {
38873
+ if (!value || typeof value !== "object" || Array.isArray(value))
38874
+ return false;
38875
+ const { submittedAtMs, returnedAtMs } = value;
38876
+ if (typeof submittedAtMs !== "number" || !Number.isFinite(submittedAtMs) || submittedAtMs < 0)
38877
+ return false;
38878
+ if (typeof returnedAtMs !== "number")
38879
+ return false;
38880
+ if (requireFiniteEnd ? !Number.isFinite(returnedAtMs) : Number.isNaN(returnedAtMs))
38881
+ return false;
38882
+ return returnedAtMs >= submittedAtMs;
38883
+ }
38884
+ function errnoCode(error62) {
38885
+ return error62?.code;
38886
+ }
38887
+ function isWindowsTransientError(error62) {
38888
+ if (process.platform !== "win32")
38889
+ return false;
38890
+ const code = errnoCode(error62);
38891
+ return code === "EPERM" || code === "EACCES" || code === "EBUSY";
38892
+ }
38893
+ async function retryOnWindows(operation) {
38894
+ for (let attempt = 0; ; attempt++) {
38895
+ try {
38896
+ return await operation();
38294
38897
  } catch (error62) {
38295
- const { code } = nativeHistoryError(error62);
38296
- if (code !== "sessionBusy" && code !== "sessionNotFound")
38297
- break;
38898
+ const wait = WINDOWS_RETRY_DELAYS_MS[attempt];
38899
+ if (wait === void 0 || !isWindowsTransientError(error62))
38900
+ throw error62;
38901
+ await delay2(wait);
38298
38902
  }
38299
38903
  }
38300
- return null;
38301
38904
  }
38302
- function nativeHistoryError(error62) {
38303
- const sqlite = error62;
38304
- if (sqlite?.code === "ERR_SQLITE_ERROR" && sqlite.errcode !== void 0) {
38305
- const primary = sqlite.errcode & 255;
38306
- if (primary === 5 || primary === 6)
38307
- return {
38308
- code: "sessionBusy",
38309
- message: "Antigravity native history database is locked; retry shortly",
38310
- retryable: true
38311
- };
38905
+ function parsePromptWindowLine(line) {
38906
+ if (!line.trim())
38907
+ return void 0;
38908
+ try {
38909
+ const parsed = JSON.parse(line);
38910
+ if (!isValidWindow(parsed, true))
38911
+ return void 0;
38912
+ return { submittedAtMs: parsed.submittedAtMs, returnedAtMs: parsed.returnedAtMs };
38913
+ } catch {
38914
+ return void 0;
38915
+ }
38916
+ }
38917
+ function isTimestampInPromptWindows(timestampMs, windows) {
38918
+ if (timestampMs === void 0 || !windows?.length)
38919
+ return false;
38920
+ return windows.some((window) => timestampMs >= window.submittedAtMs && timestampMs <= window.returnedAtMs);
38921
+ }
38922
+ function mergePromptWindows(...lists) {
38923
+ const valid = [];
38924
+ for (const list of lists) {
38925
+ if (!list)
38926
+ continue;
38927
+ for (const entry of list) {
38928
+ if (isValidWindow(entry, false)) {
38929
+ valid.push({ submittedAtMs: entry.submittedAtMs, returnedAtMs: entry.returnedAtMs });
38930
+ }
38931
+ }
38932
+ }
38933
+ valid.sort((left, right) => left.submittedAtMs !== right.submittedAtMs ? left.submittedAtMs - right.submittedAtMs : left.returnedAtMs - right.returnedAtMs);
38934
+ const merged = [];
38935
+ for (const entry of valid) {
38936
+ const previous = merged.at(-1);
38937
+ if (previous && previous.submittedAtMs === entry.submittedAtMs && previous.returnedAtMs === entry.returnedAtMs)
38938
+ continue;
38939
+ merged.push(entry);
38940
+ }
38941
+ return merged;
38942
+ }
38943
+ function filterRetainedPromptWindows(windows, cutoff, maxRetainedStepCreatedAtMs) {
38944
+ const finite = mergePromptWindows(windows).filter((entry) => isValidWindow(entry, true));
38945
+ if (cutoff === void 0)
38946
+ return finite;
38947
+ if (cutoff === 0 || maxRetainedStepCreatedAtMs === void 0)
38948
+ return [];
38949
+ return finite.filter((entry) => entry.submittedAtMs <= maxRetainedStepCreatedAtMs);
38950
+ }
38951
+ async function readPromptWindows(sessionId, environment) {
38952
+ if (!VALID_SESSION_ID.test(sessionId))
38953
+ return [];
38954
+ try {
38955
+ const raw = await retryOnWindows(() => readFile(promptWindowsPath(sessionId, environment), "utf8"));
38956
+ return mergePromptWindows(raw.split("\n").map(parsePromptWindowLine).filter((entry) => entry !== void 0));
38957
+ } catch (error62) {
38958
+ const code = errnoCode(error62);
38959
+ if (code === "ENOENT" || code === "ENOTDIR")
38960
+ return [];
38961
+ throw error62;
38312
38962
  }
38313
- const missing = sqlite?.code === "ENOENT";
38314
- return {
38315
- code: missing ? "sessionNotFound" : "nativeFailure",
38316
- message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
38317
- retryable: false
38318
- };
38963
+ }
38964
+ async function savePromptWindows(sessionId, windows, environment) {
38965
+ if (!VALID_SESSION_ID.test(sessionId))
38966
+ return;
38967
+ const lines = mergePromptWindows(windows).filter((entry) => isValidWindow(entry, true)).map((entry) => `${JSON.stringify(entry)}
38968
+ `);
38969
+ if (!lines.length)
38970
+ return;
38971
+ const file2 = promptWindowsPath(sessionId, environment);
38972
+ await mkdir(path11.dirname(file2), { recursive: true, mode: 448 });
38973
+ for (const line of lines) {
38974
+ await retryOnWindows(() => appendFile(file2, line, { mode: 384 }));
38975
+ }
38976
+ }
38977
+ async function removePromptWindows(sessionId, environment) {
38978
+ if (!VALID_SESSION_ID.test(sessionId))
38979
+ return;
38980
+ await retryOnWindows(() => rm2(promptWindowsPath(sessionId, environment), { force: true }));
38319
38981
  }
38320
38982
 
38321
38983
  // dist/native-replay.js
@@ -38346,9 +39008,16 @@ function textField(fields, number4) {
38346
39008
  const bytes = messageField(fields, number4);
38347
39009
  return bytes ? Buffer.from(bytes).toString("utf8") : "";
38348
39010
  }
38349
- function isPlanContinuation(step) {
39011
+ function planContinuationType(step) {
38350
39012
  const eventType = textField(nested(step, 114), 3);
38351
- return eventType === "plan_mode_handoff" || eventType === "plan_mode_handback";
39013
+ return eventType === "plan_mode_handoff" || eventType === "plan_mode_handback" ? eventType : void 0;
39014
+ }
39015
+ function planToolDirection(toolName) {
39016
+ if (toolName === "exit_plan_mode")
39017
+ return "plan_mode_handoff";
39018
+ if (toolName === "enter_plan_mode")
39019
+ return "plan_mode_handback";
39020
+ return void 0;
38352
39021
  }
38353
39022
  function argsValue(raw) {
38354
39023
  if (!raw)
@@ -38359,14 +39028,14 @@ function argsValue(raw) {
38359
39028
  return raw;
38360
39029
  }
38361
39030
  }
38362
- async function readNativeHistory(sessionId, home) {
39031
+ async function readNativeHistory(sessionId, home, options) {
38363
39032
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
38364
39033
  throw new Error("Invalid native Session ID");
38365
39034
  const { DatabaseSync } = await import("node:sqlite");
38366
39035
  const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
38367
39036
  try {
38368
39037
  db.exec("BEGIN");
38369
- return decodeNativeHistory(db);
39038
+ return decodeNativeHistory(db, options);
38370
39039
  } finally {
38371
39040
  db.close();
38372
39041
  }
@@ -38415,35 +39084,96 @@ async function readNativeTurnCompactions(dbPath, afterStepIndex, inPromptWindow)
38415
39084
  return [];
38416
39085
  const compactions = [];
38417
39086
  const foregroundRuns = /* @__PURE__ */ new Set();
38418
- let latestRun;
38419
- let seenUserInput = false;
38420
39087
  const wakeRuns = /* @__PURE__ */ new Set();
39088
+ const planCalls = /* @__PURE__ */ new Map();
39089
+ const pendingPlanHandoffs = [];
39090
+ let latestOwner;
39091
+ let seenUserInput = false;
38421
39092
  const hasMetadata = db.prepare("PRAGMA table_info(steps)").all().some((column) => column.name === "metadata");
39093
+ const resolveRunOwner = (stepRun) => {
39094
+ if (stepRun) {
39095
+ if (foregroundRuns.has(stepRun))
39096
+ return "foreground";
39097
+ if (wakeRuns.has(stepRun))
39098
+ return "wake";
39099
+ return void 0;
39100
+ }
39101
+ return latestOwner;
39102
+ };
38422
39103
  for (const row of db.prepare(`SELECT idx, step_type, status, step_payload${hasMetadata ? `, CASE WHEN step_type = ${SYSTEM_MESSAGE} THEN metadata END AS metadata` : ""} FROM steps
38423
- WHERE idx > ? AND step_type IN (${USER_INPUT}, ${SYSTEM_MESSAGE}, ${CHECKPOINT})
39104
+ WHERE idx > ? AND step_type IN (${USER_INPUT}, ${PLANNER_RESPONSE}, ${SYSTEM_MESSAGE}, ${GENERIC_TOOL}, ${CHECKPOINT})
38424
39105
  ORDER BY idx`).iterate(afterStepIndex)) {
38425
39106
  const idx = Number(row.idx);
38426
39107
  const step = message2(row.step_payload);
38427
- const stepRun = textField(nested(step, 5), 12);
39108
+ const metadata = nested(step, 5);
39109
+ const stepRun = textField(metadata, 12);
38428
39110
  if (row.step_type === USER_INPUT) {
38429
39111
  seenUserInput = true;
38430
39112
  if (stepRun)
38431
39113
  foregroundRuns.add(stepRun);
38432
- latestRun = stepRun || void 0;
39114
+ latestOwner = "foreground";
38433
39115
  continue;
38434
39116
  }
39117
+ if (IN_FLIGHT.has(Number(row.status)))
39118
+ continue;
38435
39119
  if (row.step_type === SYSTEM_MESSAGE) {
38436
39120
  if (!stepRun)
38437
39121
  continue;
38438
- if (!foregroundRuns.has(stepRun)) {
38439
- if (row.status === DONE && latestRun && foregroundRuns.has(latestRun) && !wakeRuns.has(stepRun) && isPlanContinuation(step)) {
39122
+ const planType = planContinuationType(step);
39123
+ if (planType) {
39124
+ const handoffIndex = pendingPlanHandoffs.findIndex((entry) => entry.direction === planType);
39125
+ const resolvedOwner = handoffIndex >= 0 ? pendingPlanHandoffs.splice(handoffIndex, 1)[0]?.owner : latestOwner;
39126
+ if (row.status === DONE && resolvedOwner === "foreground" && !wakeRuns.has(stepRun)) {
38440
39127
  foregroundRuns.add(stepRun);
38441
- } else if (seenUserInput && !wakeRuns.has(stepRun) && inPromptWindow?.(nativeStepCreatedAtMs(row.metadata))) {
38442
- foregroundRuns.add(stepRun);
38443
- } else
39128
+ latestOwner = "foreground";
39129
+ } else {
38444
39130
  wakeRuns.add(stepRun);
39131
+ latestOwner = "wake";
39132
+ }
39133
+ continue;
39134
+ }
39135
+ if (foregroundRuns.has(stepRun)) {
39136
+ latestOwner = "foreground";
39137
+ } else if (row.status === DONE && seenUserInput && !wakeRuns.has(stepRun) && inPromptWindow?.(nativeStepCreatedAtMs(row.metadata))) {
39138
+ foregroundRuns.add(stepRun);
39139
+ latestOwner = "foreground";
39140
+ } else {
39141
+ wakeRuns.add(stepRun);
39142
+ latestOwner = "wake";
39143
+ }
39144
+ continue;
39145
+ }
39146
+ if (row.step_type === PLANNER_RESPONSE) {
39147
+ const owner = resolveRunOwner(stepRun);
39148
+ if (!owner)
39149
+ continue;
39150
+ latestOwner = owner;
39151
+ const body = nested(step, 20);
39152
+ for (const field3 of body) {
39153
+ if (field3.number !== 7 || field3.wire !== 2)
39154
+ continue;
39155
+ const call = message2(field3.value);
39156
+ const toolCallId = textField(call, 1);
39157
+ const direction = planToolDirection(textField(call, 2));
39158
+ if (toolCallId && direction)
39159
+ planCalls.set(toolCallId, { direction, owner });
39160
+ }
39161
+ continue;
39162
+ }
39163
+ if (row.step_type === GENERIC_TOOL) {
39164
+ const call = nested(metadata, 4);
39165
+ const toolCallId = textField(call, 1);
39166
+ const planCall = toolCallId ? planCalls.get(toolCallId) : void 0;
39167
+ const owner = planCall?.owner ?? resolveRunOwner(stepRun);
39168
+ if (owner)
39169
+ latestOwner = owner;
39170
+ if (row.status === DONE) {
39171
+ const direction = planCall?.direction ?? planToolDirection(textField(call, 2));
39172
+ if (direction && owner)
39173
+ pendingPlanHandoffs.push({ direction, owner });
39174
+ if (toolCallId)
39175
+ planCalls.delete(toolCallId);
38445
39176
  }
38446
- latestRun = stepRun;
38447
39177
  continue;
38448
39178
  }
38449
39179
  if (!seenUserInput)
@@ -38463,43 +39193,110 @@ async function readNativeTurnCompactions(dbPath, afterStepIndex, inPromptWindow)
38463
39193
  db.close();
38464
39194
  }
38465
39195
  }
38466
- function decodeNativeHistory(db) {
39196
+ function decodeNativeHistory(db, options) {
38467
39197
  const events = [];
38468
- let toolCalls = /* @__PURE__ */ new Map();
39198
+ const interleavedPromptSteps = /* @__PURE__ */ new Map();
39199
+ let userToolCalls = /* @__PURE__ */ new Map();
39200
+ let toolCalls = userToolCalls;
39201
+ let foregroundRuns = /* @__PURE__ */ new Set();
39202
+ let inPromptRuns = /* @__PURE__ */ new Set();
39203
+ let planCalls = /* @__PURE__ */ new Map();
39204
+ let pendingPlanHandoffs = [];
38469
39205
  let turnCount = 0;
38470
39206
  let run = "";
39207
+ let lastOwner = "foreground";
38471
39208
  let candidate;
38472
39209
  let wake;
39210
+ let userInsertIndex;
39211
+ let routingToUser = false;
38473
39212
  let finalPlanner = false;
39213
+ let currentStepIndex = -1;
39214
+ let lastUserStepIndex = -1;
39215
+ const isUserOwner = (owner) => owner === "foreground" || owner === "in-prompt";
39216
+ const recordInterleavedStep = (stepIndex) => {
39217
+ const firstWake = userInsertIndex === void 0 ? void 0 : events[userInsertIndex];
39218
+ if (firstWake?.type === "history.autonomous") {
39219
+ const previous = interleavedPromptSteps.get(firstWake.stepIndex);
39220
+ if (previous === void 0 || stepIndex > previous) {
39221
+ interleavedPromptSteps.set(firstWake.stepIndex, stepIndex);
39222
+ }
39223
+ }
39224
+ };
38474
39225
  const endWake = () => {
38475
- if (wake && !wake.settled)
39226
+ if (wake && !wake.settled) {
38476
39227
  events.length = wake.eventIndex;
39228
+ interleavedPromptSteps.delete(wake.stepIndex);
39229
+ }
39230
+ if (userInsertIndex !== void 0 && userInsertIndex >= events.length) {
39231
+ userInsertIndex = void 0;
39232
+ routingToUser = false;
39233
+ }
38477
39234
  wake = void 0;
38478
39235
  candidate = void 0;
38479
39236
  };
38480
- const append = (type, text3) => {
38481
- if (text3)
38482
- events.push({ type, text: events.at(-1)?.type === type ? `
39237
+ const pushUserEvent = (event) => {
39238
+ if (userInsertIndex !== void 0) {
39239
+ events.splice(userInsertIndex, 0, event);
39240
+ if (wake && userInsertIndex <= wake.eventIndex)
39241
+ wake.eventIndex++;
39242
+ userInsertIndex++;
39243
+ recordInterleavedStep(currentStepIndex);
39244
+ } else {
39245
+ events.push(event);
39246
+ if (turnCount > 0)
39247
+ lastUserStepIndex = Math.max(lastUserStepIndex, currentStepIndex);
39248
+ }
39249
+ };
39250
+ const pushEvent = (event, toUser) => {
39251
+ if (toUser) {
39252
+ pushUserEvent(event);
39253
+ } else {
39254
+ events.push(event);
39255
+ if (!wake && userInsertIndex === void 0 && turnCount > 0) {
39256
+ lastUserStepIndex = Math.max(lastUserStepIndex, currentStepIndex);
39257
+ }
39258
+ }
39259
+ };
39260
+ const append = (type, text3, toUser) => {
39261
+ if (!text3)
39262
+ return;
39263
+ const previous = toUser && userInsertIndex !== void 0 ? events[userInsertIndex - 1] : events.at(-1);
39264
+ pushEvent({ type, text: previous?.type === type ? `
38483
39265
 
38484
- ${text3}` : text3 });
39266
+ ${text3}` : text3 }, toUser);
38485
39267
  };
38486
39268
  if (db.prepare("PRAGMA user_version").get()?.user_version !== 1)
38487
39269
  throw new Error("Unsupported Antigravity history database version");
39270
+ const promptWindows = typeof options?.promptWindows === "function" ? options.promptWindows() : options?.promptWindows;
38488
39271
  const hasMetadata = db.prepare("PRAGMA table_info(steps)").all().some((column) => column.name === "metadata");
38489
39272
  for (const row of db.prepare(`SELECT idx, step_type, status, step_payload${hasMetadata ? `, CASE WHEN step_type = ${SYSTEM_MESSAGE} THEN metadata END AS metadata` : ""} FROM steps
38490
39273
  WHERE step_type IN (${USER_INPUT}, ${PLANNER_RESPONSE}, ${ERROR_MESSAGE}, ${CHECKPOINT}, ${SYSTEM_MESSAGE}, ${GENERIC_TOOL})
38491
39274
  ORDER BY idx`).iterate()) {
38492
39275
  const idx = Number(row.idx);
39276
+ currentStepIndex = idx;
38493
39277
  const nativeTurnIndex = row.step_type === USER_INPUT ? turnCount++ : void 0;
38494
39278
  if (nativeTurnIndex !== void 0) {
38495
39279
  endWake();
38496
39280
  run = "";
39281
+ foregroundRuns = /* @__PURE__ */ new Set();
39282
+ inPromptRuns = /* @__PURE__ */ new Set();
39283
+ planCalls = /* @__PURE__ */ new Map();
39284
+ pendingPlanHandoffs = [];
39285
+ lastOwner = "foreground";
38497
39286
  finalPlanner = false;
38498
- toolCalls.clear();
39287
+ userInsertIndex = void 0;
39288
+ routingToUser = false;
39289
+ lastUserStepIndex = -1;
39290
+ userToolCalls = /* @__PURE__ */ new Map();
39291
+ toolCalls = userToolCalls;
38499
39292
  }
38500
39293
  if (IN_FLIGHT.has(Number(row.status))) {
38501
- if (wake && row.step_type === PLANNER_RESPONSE)
38502
- wake.settled = false;
39294
+ if (wake && row.step_type === PLANNER_RESPONSE) {
39295
+ const inFlightStep = message2(row.step_payload);
39296
+ const inFlightRun = textField(nested(inFlightStep, 5), 12);
39297
+ if (!inFlightRun || inFlightRun === wake.run)
39298
+ wake.settled = false;
39299
+ }
38503
39300
  continue;
38504
39301
  }
38505
39302
  const step = message2(row.step_payload);
@@ -38508,19 +39305,75 @@ ${text3}` : text3 });
38508
39305
  if (row.step_type === SYSTEM_MESSAGE) {
38509
39306
  if (row.status !== DONE)
38510
39307
  continue;
38511
- if (isPlanContinuation(step)) {
39308
+ const planType = planContinuationType(step);
39309
+ if (planType) {
38512
39310
  if (stepRun) {
38513
- if (candidate)
38514
- candidate.run = stepRun;
38515
- else
39311
+ const handoffIndex = pendingPlanHandoffs.findIndex((entry) => entry.direction === planType);
39312
+ const handoff2 = handoffIndex >= 0 ? pendingPlanHandoffs.splice(handoffIndex, 1)[0] : void 0;
39313
+ const owner = handoff2?.owner ?? lastOwner;
39314
+ if (owner === "candidate") {
39315
+ const targetCandidate = handoff2?.candidate ?? candidate;
39316
+ if (targetCandidate)
39317
+ targetCandidate.run = stepRun;
39318
+ lastOwner = "candidate";
39319
+ } else if (owner === "wake") {
39320
+ const targetWake = handoff2?.wake ?? wake;
39321
+ if (targetWake) {
39322
+ targetWake.run = stepRun;
39323
+ if (targetWake === wake)
39324
+ run = stepRun;
39325
+ } else {
39326
+ run = stepRun;
39327
+ }
39328
+ lastOwner = "wake";
39329
+ } else if (owner === "in-prompt") {
39330
+ inPromptRuns.add(stepRun);
39331
+ if (!wake)
39332
+ run = stepRun;
39333
+ lastOwner = "in-prompt";
39334
+ if (userInsertIndex !== void 0)
39335
+ recordInterleavedStep(idx);
39336
+ else if (turnCount > 0)
39337
+ lastUserStepIndex = Math.max(lastUserStepIndex, idx);
39338
+ } else {
39339
+ foregroundRuns.add(stepRun);
39340
+ if (!wake)
39341
+ run = stepRun;
39342
+ lastOwner = "foreground";
39343
+ if (userInsertIndex !== void 0)
39344
+ recordInterleavedStep(idx);
39345
+ else if (turnCount > 0)
39346
+ lastUserStepIndex = Math.max(lastUserStepIndex, idx);
39347
+ }
39348
+ }
39349
+ continue;
39350
+ }
39351
+ const createdAtMs = nativeStepCreatedAtMs(row.metadata);
39352
+ if (turnCount > 0 && isTimestampInPromptWindows(createdAtMs, promptWindows)) {
39353
+ if (stepRun)
39354
+ inPromptRuns.add(stepRun);
39355
+ else
39356
+ endWake();
39357
+ routingToUser = userInsertIndex !== void 0;
39358
+ lastOwner = "in-prompt";
39359
+ if (userInsertIndex !== void 0)
39360
+ recordInterleavedStep(idx);
39361
+ else
39362
+ lastUserStepIndex = Math.max(lastUserStepIndex, idx);
39363
+ if (!wake) {
39364
+ toolCalls = userToolCalls;
39365
+ if (stepRun)
38516
39366
  run = stepRun;
39367
+ finalPlanner = false;
38517
39368
  }
38518
39369
  continue;
38519
39370
  }
38520
- if (stepRun ? stepRun !== run : finalPlanner) {
39371
+ const activeRun = wake ? wake.run : run;
39372
+ const knownUserRun = !!stepRun && (inPromptRuns.has(stepRun) || foregroundRuns.has(stepRun));
39373
+ if (!knownUserRun && (stepRun ? stepRun !== activeRun : finalPlanner)) {
38521
39374
  if (candidate?.run !== stepRun) {
38522
39375
  endWake();
38523
- const createdAtMs = nativeStepCreatedAtMs(row.metadata);
39376
+ lastOwner = "candidate";
38524
39377
  candidate = {
38525
39378
  stepIndex: idx,
38526
39379
  run: stepRun,
@@ -38532,18 +39385,37 @@ ${text3}` : text3 });
38532
39385
  }
38533
39386
  continue;
38534
39387
  }
39388
+ const isInPromptRun = turnCount > 0 && (stepRun ? inPromptRuns.has(stepRun) : routingToUser);
39389
+ const isForegroundRun = turnCount > 0 && !!stepRun && foregroundRuns.has(stepRun);
39390
+ const belongsToUser = isInPromptRun || isForegroundRun;
39391
+ const userRunOwner = isInPromptRun ? "in-prompt" : "foreground";
38535
39392
  if (row.step_type === CHECKPOINT) {
38536
39393
  const event = decodeCheckpointEvent(idx, row.status, step);
38537
39394
  if (!event)
38538
39395
  continue;
39396
+ if (belongsToUser) {
39397
+ lastOwner = userRunOwner;
39398
+ pushUserEvent(event);
39399
+ continue;
39400
+ }
38539
39401
  const pendingWake = candidate?.run === stepRun ? candidate : void 0;
38540
- if (!pendingWake && (candidate || stepRun && run && stepRun !== run))
39402
+ const activeRun = wake ? wake.run : run;
39403
+ if (!pendingWake && (candidate || stepRun && activeRun && stepRun !== activeRun))
38541
39404
  continue;
38542
- (pendingWake?.events ?? events).push(event);
39405
+ if (pendingWake) {
39406
+ lastOwner = "candidate";
39407
+ pendingWake.events.push(event);
39408
+ } else {
39409
+ lastOwner = wake ? "wake" : "foreground";
39410
+ pushEvent(event, false);
39411
+ }
38543
39412
  continue;
38544
39413
  }
38545
- if (row.step_type === USER_INPUT)
39414
+ if (row.step_type === USER_INPUT) {
38546
39415
  run = stepRun;
39416
+ if (stepRun)
39417
+ foregroundRuns.add(stepRun);
39418
+ }
38547
39419
  const number4 = row.step_type === USER_INPUT ? 19 : row.step_type === PLANNER_RESPONSE ? 20 : 24;
38548
39420
  const body = row.step_type === GENERIC_TOOL ? nested(step, 140) : message2(messageField(step, number4));
38549
39421
  switch (row.step_type) {
@@ -38558,50 +39430,124 @@ ${text3}` : text3 });
38558
39430
  const thought = textField(body, 3);
38559
39431
  const text3 = textField(body, 1);
38560
39432
  const calls = body.filter((field3) => field3.number === 7 && field3.wire === 2);
39433
+ const isFinal = row.status === DONE && !!text3.trim() && calls.length === 0;
39434
+ if (belongsToUser) {
39435
+ lastOwner = userRunOwner;
39436
+ if (!wake && !candidate) {
39437
+ if (stepRun)
39438
+ run = stepRun;
39439
+ finalPlanner = isFinal;
39440
+ }
39441
+ append("agent.thought", thought, true);
39442
+ append("agent.text", text3, true);
39443
+ for (const field3 of body) {
39444
+ if (field3.number !== 7 || field3.wire !== 2)
39445
+ continue;
39446
+ const call = message2(field3.value);
39447
+ const toolCallId = textField(call, 1);
39448
+ const name = textField(call, 2);
39449
+ if (!toolCallId || !name || userToolCalls.get(toolCallId) === "settled")
39450
+ continue;
39451
+ userToolCalls.set(toolCallId, "pending");
39452
+ const planDir = planToolDirection(name);
39453
+ if (planDir)
39454
+ planCalls.set(toolCallId, { direction: planDir, owner: userRunOwner });
39455
+ pushUserEvent({
39456
+ type: "tool.call",
39457
+ toolCallId,
39458
+ name,
39459
+ args: argsValue(textField(call, 3))
39460
+ });
39461
+ }
39462
+ break;
39463
+ }
38561
39464
  if (candidate && candidate.run === stepRun) {
38562
39465
  const { stepIndex, events: earlierTools, calls: earlierCalls, createdAtMs } = candidate;
39466
+ const promotedCandidate = candidate;
38563
39467
  endWake();
38564
- wake = { eventIndex: events.length, settled: false };
39468
+ routingToUser = false;
39469
+ if (turnCount > 0 && userInsertIndex === void 0)
39470
+ userInsertIndex = events.length;
39471
+ wake = {
39472
+ eventIndex: events.length,
39473
+ stepIndex,
39474
+ run: stepRun,
39475
+ calls: earlierCalls,
39476
+ settled: false
39477
+ };
39478
+ for (const entry of planCalls.values()) {
39479
+ if (entry.candidate === promotedCandidate) {
39480
+ entry.owner = "wake";
39481
+ entry.wake = wake;
39482
+ delete entry.candidate;
39483
+ }
39484
+ }
39485
+ for (const entry of pendingPlanHandoffs) {
39486
+ if (entry.candidate === promotedCandidate) {
39487
+ entry.owner = "wake";
39488
+ entry.wake = wake;
39489
+ delete entry.candidate;
39490
+ }
39491
+ }
38565
39492
  events.push({
38566
39493
  type: "history.autonomous",
38567
39494
  stepIndex,
38568
39495
  ...createdAtMs !== void 0 ? { createdAtMs } : {}
38569
39496
  });
39497
+ if (turnCount > 0 && lastUserStepIndex >= stepIndex) {
39498
+ recordInterleavedStep(lastUserStepIndex);
39499
+ }
38570
39500
  for (const event of earlierTools)
38571
39501
  events.push(event);
38572
39502
  toolCalls = earlierCalls;
38573
39503
  }
38574
- if (stepRun)
39504
+ if (stepRun) {
38575
39505
  run = stepRun;
38576
- finalPlanner = row.status === DONE && !!text3.trim() && calls.length === 0;
39506
+ if (wake)
39507
+ wake.run = stepRun;
39508
+ }
39509
+ const plannerOwner = wake ? "wake" : "foreground";
39510
+ lastOwner = plannerOwner;
39511
+ finalPlanner = isFinal;
38577
39512
  if (wake)
38578
39513
  wake.settled = finalPlanner;
38579
- append("agent.thought", thought);
38580
- append("agent.text", text3);
39514
+ append("agent.thought", thought, false);
39515
+ append("agent.text", text3, false);
39516
+ const activeCalls = wake ? wake.calls : toolCalls;
38581
39517
  for (const field3 of body) {
38582
39518
  if (field3.number !== 7 || field3.wire !== 2)
38583
39519
  continue;
38584
39520
  const call = message2(field3.value);
38585
39521
  const toolCallId = textField(call, 1);
38586
39522
  const name = textField(call, 2);
38587
- if (!toolCallId || !name || toolCalls.get(toolCallId) === "settled")
39523
+ if (!toolCallId || !name || activeCalls.get(toolCallId) === "settled")
38588
39524
  continue;
38589
- toolCalls.set(toolCallId, "pending");
38590
- events.push({
39525
+ activeCalls.set(toolCallId, "pending");
39526
+ const planDir = planToolDirection(name);
39527
+ if (planDir) {
39528
+ planCalls.set(toolCallId, {
39529
+ direction: planDir,
39530
+ owner: plannerOwner,
39531
+ ...wake ? { wake } : {}
39532
+ });
39533
+ }
39534
+ pushEvent({
38591
39535
  type: "tool.call",
38592
39536
  toolCallId,
38593
39537
  name,
38594
39538
  args: argsValue(textField(call, 3))
38595
- });
39539
+ }, false);
38596
39540
  }
38597
39541
  break;
38598
39542
  }
38599
39543
  case ERROR_MESSAGE: {
38600
- if (candidate?.run === stepRun)
39544
+ if (!belongsToUser && candidate?.run === stepRun)
38601
39545
  break;
38602
39546
  const warning = textField(nested(body, 3), 2);
38603
- if (warning)
38604
- append("agent.text", `⚠ ${warning}`);
39547
+ if (warning) {
39548
+ lastOwner = belongsToUser ? userRunOwner : wake ? "wake" : "foreground";
39549
+ append("agent.text", `⚠ ${warning}`, belongsToUser);
39550
+ }
38605
39551
  break;
38606
39552
  }
38607
39553
  case GENERIC_TOOL: {
@@ -38609,292 +39555,111 @@ ${text3}` : text3 });
38609
39555
  const toolCallId = textField(call, 1);
38610
39556
  if (!toolCallId)
38611
39557
  break;
38612
- const pendingWake = candidate?.run === stepRun ? candidate : void 0;
38613
- const calls = pendingWake?.calls ?? toolCalls;
38614
- const target2 = pendingWake?.events ?? events;
39558
+ let resolvedUser = belongsToUser;
39559
+ let resolvedOwner = belongsToUser ? userRunOwner : wake ? "wake" : "foreground";
39560
+ let pendingWake = !belongsToUser && candidate?.run === stepRun ? candidate : void 0;
39561
+ let calls = belongsToUser ? userToolCalls : pendingWake?.calls ?? wake?.calls ?? toolCalls;
39562
+ if (!stepRun) {
39563
+ const userPending = turnCount > 0 && userToolCalls.get(toolCallId) === "pending";
39564
+ const wakePending = wake?.calls.get(toolCallId) === "pending";
39565
+ const candidatePending = candidate?.calls.get(toolCallId) === "pending";
39566
+ const matches = Number(userPending) + Number(wakePending) + Number(candidatePending);
39567
+ if (matches > 1)
39568
+ break;
39569
+ if (matches === 1) {
39570
+ if (userPending) {
39571
+ resolvedUser = true;
39572
+ resolvedOwner = planCalls.get(toolCallId)?.owner ?? (isInPromptRun ? "in-prompt" : "foreground");
39573
+ pendingWake = void 0;
39574
+ calls = userToolCalls;
39575
+ } else if (wakePending && wake) {
39576
+ resolvedUser = false;
39577
+ resolvedOwner = "wake";
39578
+ pendingWake = void 0;
39579
+ calls = wake.calls;
39580
+ } else if (candidatePending && candidate) {
39581
+ resolvedUser = false;
39582
+ resolvedOwner = "candidate";
39583
+ pendingWake = candidate;
39584
+ calls = candidate.calls;
39585
+ }
39586
+ } else if (pendingWake) {
39587
+ resolvedOwner = "candidate";
39588
+ }
39589
+ } else if (pendingWake) {
39590
+ resolvedOwner = "candidate";
39591
+ }
38615
39592
  const state = calls.get(toolCallId);
38616
39593
  if (state === "settled")
38617
39594
  break;
39595
+ const activeRun = wake ? wake.run : run;
39596
+ const name = textField(call, 2);
38618
39597
  if (state === void 0) {
38619
- const name = textField(call, 2);
38620
39598
  if (row.status !== DONE || !name)
38621
39599
  break;
38622
- if (!pendingWake && (candidate || stepRun && run && stepRun !== run))
39600
+ if (!isInPromptRun && !pendingWake && (candidate || wake && resolvedUser || stepRun && activeRun && stepRun !== activeRun))
38623
39601
  break;
38624
- target2.push({
39602
+ const callEvent = {
38625
39603
  type: "tool.call",
38626
39604
  toolCallId,
38627
39605
  name,
38628
39606
  args: argsValue(textField(call, 3))
38629
- });
39607
+ };
39608
+ if (pendingWake)
39609
+ pendingWake.events.push(callEvent);
39610
+ else
39611
+ pushEvent(callEvent, resolvedUser);
38630
39612
  }
38631
39613
  calls.set(toolCallId, "settled");
39614
+ const knownPlanCall = planCalls.get(toolCallId);
39615
+ if (knownPlanCall) {
39616
+ planCalls.delete(toolCallId);
39617
+ if (isUserOwner(knownPlanCall.owner))
39618
+ resolvedOwner = knownPlanCall.owner;
39619
+ }
39620
+ lastOwner = resolvedOwner;
39621
+ if (row.status === DONE) {
39622
+ const planDir = knownPlanCall?.direction ?? planToolDirection(name);
39623
+ if (planDir) {
39624
+ pendingPlanHandoffs.push(knownPlanCall ?? {
39625
+ direction: planDir,
39626
+ owner: resolvedOwner,
39627
+ ...resolvedOwner === "wake" && wake ? { wake } : {},
39628
+ ...resolvedOwner === "candidate" && pendingWake ? { candidate: pendingWake } : {}
39629
+ });
39630
+ }
39631
+ }
38632
39632
  const error62 = nested(step, 31);
38633
39633
  const output2 = textField(nested(body, 2), 1) || textField(error62, 3) || textField(error62, 2) || textField(error62, 1);
38634
39634
  const status = row.status === DONE ? "completed" : row.status === ERROR ? "failed" : "cancelled";
38635
- target2.push({
39635
+ const updateEvent = {
38636
39636
  type: "tool.update",
38637
39637
  toolCallId,
38638
39638
  status,
38639
39639
  ...output2 ? { rawOutput: output2 } : {}
38640
- });
39640
+ };
39641
+ if (pendingWake)
39642
+ pendingWake.events.push(updateEvent);
39643
+ else
39644
+ pushEvent(updateEvent, resolvedUser);
38641
39645
  break;
38642
39646
  }
38643
39647
  }
38644
39648
  }
38645
39649
  endWake();
38646
39650
  const wakeWatermark = events.findLast((event) => event.type === "history.autonomous")?.stepIndex ?? -1;
38647
- return { events, turnCount, wakeWatermark };
38648
- }
38649
-
38650
- // dist/usage-statistics.js
38651
- import { lstat, readdir } from "node:fs/promises";
38652
- import os3 from "node:os";
38653
- import path10 from "node:path";
38654
-
38655
- // ../../harness-adapter/dist/usage-statistics.js
38656
- import { createReadStream as createReadStream2 } from "node:fs";
38657
- var HarnessUsageSourceChangedError = class extends Error {
38658
- code = "HARNESS_USAGE_SOURCE_CHANGED";
38659
- /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
38660
- static is(error62) {
38661
- return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === "HARNESS_USAGE_SOURCE_CHANGED";
38662
- }
38663
- };
38664
- var MAX_SESSION_ID_LENGTH = 512;
38665
- var MAX_CWD_LENGTH = 4096;
38666
- var MAX_SESSION_TITLE_LENGTH = 200;
38667
- function usageSessionTitle(value) {
38668
- if (typeof value !== "string")
38669
- return void 0;
38670
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
38671
- if (!normalized)
38672
- return void 0;
38673
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
38674
- return normalized;
38675
- let title = "";
38676
- for (const character of normalized) {
38677
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
38678
- break;
38679
- title += character;
38680
- }
38681
- return `${title.trimEnd()}…`;
38682
- }
38683
- function sessionIdOk(value) {
38684
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
38685
- }
38686
- function cwdOk(value) {
38687
- return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
38688
- }
38689
- function withUsageSession(entry, session) {
38690
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
38691
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
38692
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
38693
- if (sessionId === void 0 && cwd === void 0)
38694
- return entry;
38695
- return {
38696
- ...entry,
38697
- ...sessionId !== void 0 ? { sessionId } : {},
38698
- ...cwd !== void 0 ? { cwd } : {},
38699
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
38700
- };
38701
- }
38702
- var JSONL_CHUNK_BYTES = 128 * 1024;
38703
- var JSONL_HEADER_CHUNK_BYTES = 16 * 1024;
38704
- function concatParts(parts, total) {
38705
- const [single] = parts;
38706
- return single && parts.length === 1 ? single : Buffer.concat(parts, total);
38707
- }
38708
- async function* jsonlLineSlices(file2, signal, highWaterMark) {
38709
- const stream = createReadStream2(file2, { highWaterMark, signal });
38710
- let parts = [];
38711
- let buffered = 0;
38712
- try {
38713
- for await (const raw of stream) {
38714
- signal.throwIfAborted();
38715
- const chunk = raw;
38716
- let start = 0;
38717
- let end;
38718
- while ((end = chunk.indexOf(10, start)) >= 0) {
38719
- const lineEnd = end > start && chunk[end - 1] === 13 ? end - 1 : end;
38720
- const slice = chunk.subarray(start, lineEnd);
38721
- if (buffered === 0) {
38722
- yield slice;
38723
- } else {
38724
- if (slice.length > 0) {
38725
- parts.push(slice);
38726
- buffered += slice.length;
38727
- }
38728
- const combined = concatParts(parts, buffered);
38729
- parts = [];
38730
- buffered = 0;
38731
- yield combined.length > 0 && combined[combined.length - 1] === 13 ? combined.subarray(0, combined.length - 1) : combined;
38732
- }
38733
- start = end + 1;
38734
- }
38735
- if (start < chunk.length) {
38736
- const rest = chunk.subarray(start);
38737
- parts.push(rest);
38738
- buffered += rest.length;
38739
- }
38740
- }
38741
- if (buffered > 0) {
38742
- const combined = concatParts(parts, buffered);
38743
- yield combined.length > 0 && combined[combined.length - 1] === 13 ? combined.subarray(0, combined.length - 1) : combined;
38744
- }
38745
- } finally {
38746
- stream.destroy();
38747
- }
38748
- }
38749
- async function* jsonlRecords(file2, marker, signal) {
38750
- const markerBytes = marker.length > 0 ? Buffer.from(marker, "utf8") : null;
38751
- for await (const rawLine of jsonlLineSlices(file2, signal, JSONL_CHUNK_BYTES)) {
38752
- if (markerBytes && !rawLine.includes(markerBytes))
38753
- continue;
38754
- const line = rawLine.toString("utf8");
38755
- if (!line.includes(marker))
38756
- continue;
38757
- let value;
38758
- try {
38759
- value = JSON.parse(line);
38760
- } catch {
38761
- continue;
38762
- }
38763
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
38764
- yield value;
38765
- }
38766
- }
38767
- }
38768
- function nativeTimeMs(value) {
38769
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
38770
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
38771
- }
38772
-
38773
- // dist/usage-statistics.js
38774
- function count3(value) {
38775
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
38776
- }
38777
- function antigravityHome(environment) {
38778
- return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os3.homedir();
38779
- }
38780
- function transcriptPath(brainRoot, conversationId) {
38781
- return path10.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
38782
- }
38783
- function isMissing(error62) {
38784
- const code = error62?.code;
38785
- return code === "ENOENT" || code === "ENOTDIR";
38786
- }
38787
- async function lstatIfPresent(target2) {
38788
- try {
38789
- return await lstat(target2);
38790
- } catch (error62) {
38791
- if (isMissing(error62))
38792
- return null;
38793
- throw error62;
38794
- }
38795
- }
38796
- async function transcriptFingerprint(file2) {
38797
- const logs = path10.dirname(file2);
38798
- for (const directory of [path10.dirname(logs), logs]) {
38799
- if (!(await lstatIfPresent(directory))?.isDirectory())
38800
- return null;
38801
- }
38802
- const info = await lstatIfPresent(file2);
38803
- return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
38804
- }
38805
- var LIST_CONCURRENCY = 32;
38806
- async function listTranscripts(brainRoot, signal) {
38807
- signal.throwIfAborted();
38808
- const entries = await readdir(brainRoot, { withFileTypes: true }).catch((error62) => {
38809
- if (error62.code === "ENOENT")
38810
- return null;
38811
- throw error62;
38812
- });
38813
- if (!entries)
38814
- return [];
38815
- const directories = entries.filter((entry) => entry.isDirectory());
38816
- const sources = [];
38817
- for (let offset = 0; offset < directories.length; offset += LIST_CONCURRENCY) {
38818
- signal.throwIfAborted();
38819
- const batch = directories.slice(offset, offset + LIST_CONCURRENCY);
38820
- const inspected = await Promise.all(batch.map(async (entry) => {
38821
- const file2 = transcriptPath(brainRoot, entry.name);
38822
- const fingerprint = await transcriptFingerprint(file2);
38823
- return fingerprint ? { id: file2, fingerprint } : null;
38824
- }));
38825
- for (const source of inspected) {
38826
- if (source)
38827
- sources.push(source);
38828
- }
38829
- }
38830
- signal.throwIfAborted();
38831
- return sources;
38832
- }
38833
- async function readAntigravityUsage(file2, signal) {
38834
- const sessionId = path10.basename(path10.resolve(file2, "..", "..", ".."));
38835
- const requests = /* @__PURE__ */ new Map();
38836
- for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
38837
- if (record4.type !== "PLANNER_RESPONSE")
38838
- continue;
38839
- const step = count3(record4.step_index);
38840
- const input3 = count3(record4.input_tokens);
38841
- const output2 = count3(record4.output_tokens);
38842
- const cached2 = count3(record4.cache_read_tokens);
38843
- const at = nativeTimeMs(record4.created_at);
38844
- if (step === null || input3 === null || output2 === null || at === null)
38845
- continue;
38846
- const identity2 = normalizeAntigravityUsageModel(record4.model);
38847
- requests.set(step, withUsageSession({
38848
- id: `${String(record4.created_at)}:${step}:${input3}:${cached2 ?? "-"}:${output2}`,
38849
- occurredAtMs: at,
38850
- ...identity2,
38851
- inputTokens: input3 + (cached2 ?? 0),
38852
- ...cached2 !== null ? {
38853
- cachedInputTokens: cached2,
38854
- ...hasImplicitZeroCacheWrite(identity2) ? { cacheWriteInputTokens: 0 } : {}
38855
- } : {},
38856
- outputTokens: output2
38857
- }, { sessionId }));
38858
- }
38859
- return [...requests.values()];
38860
- }
38861
- function createAntigravityUsageStatistics(environment) {
38862
- const brainRoot = nativeBrainRoot(antigravityHome(environment));
38863
- let listed = /* @__PURE__ */ new Map();
38864
- return Object.freeze({
38865
- async listSources(signal) {
38866
- const sources = await listTranscripts(brainRoot, signal);
38867
- listed = new Map(sources.map(({ id: id2, fingerprint }) => [id2, fingerprint]));
38868
- return sources;
38869
- },
38870
- async readSource(id2, signal) {
38871
- const expected = listed.get(id2);
38872
- let entries;
38873
- try {
38874
- entries = await readAntigravityUsage(id2, signal);
38875
- } catch (error62) {
38876
- if (expected !== void 0 && isMissing(error62)) {
38877
- throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
38878
- }
38879
- throw error62;
38880
- }
38881
- if (expected !== void 0 && await transcriptFingerprint(id2) !== expected) {
38882
- throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
38883
- }
38884
- return entries;
38885
- }
38886
- });
39651
+ return { events, turnCount, wakeWatermark, interleavedPromptSteps };
38887
39652
  }
38888
39653
 
38889
39654
  // dist/fork.js
38890
39655
  function nativeConversationSummariesDbPath(home = os4.homedir()) {
38891
- return path11.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
39656
+ return path12.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
38892
39657
  }
38893
39658
  function nativeBrainRoot(home = os4.homedir()) {
38894
- return path11.join(home, ".gemini", "antigravity-cli", "brain");
39659
+ return path12.join(home, ".gemini", "antigravity-cli", "brain");
38895
39660
  }
38896
39661
  function nativeBrainDirPath(id2, home = os4.homedir()) {
38897
- return path11.join(nativeBrainRoot(home), id2);
39662
+ return path12.join(nativeBrainRoot(home), id2);
38898
39663
  }
38899
39664
  function validNativeSessionRef(ref, harnessId2) {
38900
39665
  return nativeSessionRefSchema.safeParse(ref).success && ref.harnessId === harnessId2 && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(ref.nativeSessionId);
@@ -38903,6 +39668,8 @@ var ForkBoundaryError = class extends Error {
38903
39668
  };
38904
39669
  var ActiveForkUnavailable = class extends Error {
38905
39670
  };
39671
+ var NoRollbackTurn = class extends Error {
39672
+ };
38906
39673
  async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os4.homedir(), fork) {
38907
39674
  if (![sourceId, derivedId].every((id2) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id2)))
38908
39675
  throw new Error("Invalid native conversation ID");
@@ -38930,20 +39697,39 @@ async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCount
38930
39697
  throw new Error("Invalid retained native Turn count");
38931
39698
  }
38932
39699
  if (typeof retainedTurnsCountOrHome === "object") {
39700
+ const { boundaries, interleavedPromptSteps } = readDerivationSnapshot(source, fork?.promptWindows ? { promptWindows: fork.promptWindows } : void 0);
38933
39701
  if ("checkpointId" in retainedTurnsCountOrHome) {
38934
- const boundaries = derivationBoundaries(source);
38935
39702
  const index = boundaries.findIndex(({ checkpointId }) => checkpointId === retainedTurnsCountOrHome.checkpointId);
38936
39703
  if (index < 0)
38937
39704
  throw new ForkBoundaryError();
38938
39705
  cutoff = boundaries[index + 1]?.idx;
38939
- } else
38940
- cutoff = retainedTurnsCountOrHome.cutoff;
39706
+ } else {
39707
+ const last = boundaries.at(-1);
39708
+ if (!last)
39709
+ throw new NoRollbackTurn();
39710
+ cutoff = boundaries.length === 1 ? 0 : last.idx;
39711
+ }
39712
+ requireContinuousPrefix(cutoff, interleavedPromptSteps);
38941
39713
  } else if (retained !== void 0 && retained < count4) {
38942
39714
  const boundary = source.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
38943
39715
  cutoff = retained === 0 ? 0 : Number(boundary?.idx);
38944
39716
  }
38945
- await mkdir(path11.dirname(targetPath2), { recursive: true });
38946
- const reservation = await open3(targetPath2, "wx");
39717
+ if (fork?.onRetainedBounds) {
39718
+ let maxRetainedStepCreatedAtMs;
39719
+ if (cutoff !== void 0 && cutoff > 0) {
39720
+ const hasMetadata = source.prepare("PRAGMA table_info(steps)").all().some((column) => column.name === "metadata");
39721
+ if (hasMetadata) {
39722
+ for (const row of source.prepare("SELECT metadata FROM steps WHERE idx < ? AND metadata IS NOT NULL").iterate(cutoff)) {
39723
+ const createdAtMs = nativeStepCreatedAtMs(row.metadata);
39724
+ if (createdAtMs !== void 0 && (maxRetainedStepCreatedAtMs === void 0 || createdAtMs > maxRetainedStepCreatedAtMs))
39725
+ maxRetainedStepCreatedAtMs = createdAtMs;
39726
+ }
39727
+ }
39728
+ }
39729
+ fork.onRetainedBounds({ cutoff, maxRetainedStepCreatedAtMs });
39730
+ }
39731
+ await mkdir2(path12.dirname(targetPath2), { recursive: true });
39732
+ const reservation = await open4(targetPath2, "wx");
38947
39733
  owned = true;
38948
39734
  await reservation.close();
38949
39735
  await backup(source, targetPath2);
@@ -39089,7 +39875,7 @@ async function removeDerivedSummary(id2, home) {
39089
39875
  }
39090
39876
  async function removeDerivedDb(id2, home) {
39091
39877
  const file2 = nativeConversationDbPath(id2, home);
39092
- await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
39878
+ await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm3(target2, { force: true })));
39093
39879
  }
39094
39880
  async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os4.homedir()) {
39095
39881
  try {
@@ -39103,7 +39889,7 @@ async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os4.homedi
39103
39889
  recursive: true,
39104
39890
  errorOnExist: true,
39105
39891
  force: false,
39106
- filter: (source) => path11.basename(source) !== ".system_generated"
39892
+ filter: (source) => path12.basename(source) !== ".system_generated"
39107
39893
  });
39108
39894
  return true;
39109
39895
  }
@@ -39113,8 +39899,21 @@ async function openDerivedAntigravitySession(options, input3, sourceRef, retaine
39113
39899
  const derivedId = randomUUID();
39114
39900
  let cloned = false;
39115
39901
  try {
39116
- await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home, fork);
39902
+ const persistedPromptWindows = await readPromptWindows(sourceRef.nativeSessionId, environment).catch(() => []);
39903
+ const resolveSourcePromptWindows = () => mergePromptWindows(persistedPromptWindows, typeof options.sourcePromptWindows === "function" ? options.sourcePromptWindows() : options.sourcePromptWindows);
39904
+ let retainedBounds = { cutoff: void 0, maxRetainedStepCreatedAtMs: void 0 };
39905
+ await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home, {
39906
+ ...fork,
39907
+ promptWindows: resolveSourcePromptWindows,
39908
+ onRetainedBounds: (bounds) => {
39909
+ retainedBounds = bounds;
39910
+ }
39911
+ });
39117
39912
  cloned = true;
39913
+ const inheritedWindows = filterRetainedPromptWindows(resolveSourcePromptWindows(), retainedBounds.cutoff, retainedBounds.maxRetainedStepCreatedAtMs);
39914
+ if (inheritedWindows.length) {
39915
+ await savePromptWindows(derivedId, inheritedWindows, environment).catch(() => void 0);
39916
+ }
39118
39917
  if (fork?.activeTurnIndex === void 0)
39119
39918
  await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
39120
39919
  const result = await options.openSession({
@@ -39128,9 +39927,18 @@ async function openDerivedAntigravitySession(options, input3, sourceRef, retaine
39128
39927
  return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
39129
39928
  } catch (error62) {
39130
39929
  if (error62 instanceof ForkBoundaryError)
39131
- return checkpointError();
39930
+ return checkpointError(error62.message || void 0);
39132
39931
  if (error62 instanceof ActiveForkUnavailable)
39133
39932
  return activeForkError(error62.message);
39933
+ if (error62 instanceof NoRollbackTurn)
39934
+ return {
39935
+ ok: false,
39936
+ error: {
39937
+ code: "invalidState",
39938
+ message: "Antigravity Native Session has no Turn to roll back",
39939
+ retryable: false
39940
+ }
39941
+ };
39134
39942
  const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
39135
39943
  return {
39136
39944
  ok: false,
@@ -39145,8 +39953,9 @@ async function openDerivedAntigravitySession(options, input3, sourceRef, retaine
39145
39953
  return;
39146
39954
  await Promise.all([
39147
39955
  removeDerivedDb(derivedId, home),
39148
- rm2(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
39149
- removeDerivedSummary(derivedId, home)
39956
+ rm3(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
39957
+ removeDerivedSummary(derivedId, home),
39958
+ removePromptWindows(derivedId, environment).catch(() => void 0)
39150
39959
  ]);
39151
39960
  }
39152
39961
  }
@@ -39187,38 +39996,37 @@ async function forkAntigravitySession(options) {
39187
39996
  function activeForkError(message3) {
39188
39997
  return { ok: false, error: { code: "sessionBusy", message: message3, retryable: true } };
39189
39998
  }
39190
- async function readDerivationBoundaries(dbPath) {
39191
- await access2(dbPath);
39192
- const { DatabaseSync } = await import("node:sqlite");
39193
- const db = new DatabaseSync(dbPath, { readOnly: true });
39194
- try {
39195
- db.exec("BEGIN");
39196
- return derivationBoundaries(db);
39197
- } finally {
39198
- db.close();
39199
- }
39200
- }
39201
- function derivationBoundaries(db) {
39999
+ function readDerivationSnapshot(db, options) {
39202
40000
  const users = db.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx").all();
39203
40001
  const boundaries = users.map((row, index) => ({
39204
40002
  idx: Number(row.idx),
39205
40003
  checkpointId: `turn-${index}`
39206
40004
  }));
39207
- if (db.prepare("SELECT 1 FROM steps WHERE step_type = 101 LIMIT 1").get()) {
39208
- for (const event of decodeNativeHistory(db).events) {
39209
- if (event.type === "history.autonomous")
39210
- boundaries.push({ idx: event.stepIndex, checkpointId: `wake-${event.stepIndex}` });
39211
- }
39212
- boundaries.sort((a, b) => a.idx - b.idx);
40005
+ if (!db.prepare("SELECT 1 FROM steps WHERE step_type = 101 LIMIT 1").get()) {
40006
+ return { boundaries, interleavedPromptSteps: void 0 };
40007
+ }
40008
+ const { events, interleavedPromptSteps } = decodeNativeHistory(db, options);
40009
+ for (const event of events) {
40010
+ if (event.type === "history.autonomous")
40011
+ boundaries.push({ idx: event.stepIndex, checkpointId: `wake-${event.stepIndex}` });
39213
40012
  }
39214
- return boundaries;
40013
+ boundaries.sort((a, b) => a.idx - b.idx);
40014
+ return { boundaries, interleavedPromptSteps };
39215
40015
  }
39216
- function checkpointError() {
40016
+ function requireContinuousPrefix(cutoff, interleavedPromptSteps) {
40017
+ if (cutoff === void 0 || !interleavedPromptSteps)
40018
+ return;
40019
+ for (const [wakeStart, promptContinuation] of interleavedPromptSteps) {
40020
+ if (wakeStart <= cutoff && cutoff <= promptContinuation)
40021
+ throw new ForkBoundaryError("Antigravity checkpoint cuts through an interleaved user Turn");
40022
+ }
40023
+ }
40024
+ function checkpointError(message3 = "Antigravity native Turn checkpoint not found") {
39217
40025
  return {
39218
40026
  ok: false,
39219
40027
  error: {
39220
40028
  code: "checkpointNotFound",
39221
- message: "Antigravity native Turn checkpoint not found",
40029
+ message: message3,
39222
40030
  retryable: false
39223
40031
  }
39224
40032
  };
@@ -39381,18 +40189,27 @@ function splitAntigravityModelAndEffort(rawModelId) {
39381
40189
  }
39382
40190
 
39383
40191
  // dist/wake-observer.js
39384
- var COMMIT_POLL_MS = 100;
40192
+ var WAKE_COMMIT_POLL_DELAYS_MS = [150, 250, 400, 600, 1e3];
39385
40193
  var COMMIT_WAIT_MS = 1e4;
39386
40194
  var AntigravityWakeObserver = class {
39387
40195
  options;
40196
+ #dbPath;
40197
+ #readHistory;
40198
+ #pollDelaysMs;
39388
40199
  #cursor;
39389
40200
  #deadline = 0;
40201
+ #pollAttempt = 0;
40202
+ #timerDelayMs = 0;
40203
+ #lastFingerprint = null;
39390
40204
  #work;
39391
40205
  #timer;
39392
40206
  #closed = false;
39393
40207
  constructor(options) {
39394
40208
  this.options = options;
39395
40209
  this.#cursor = options.cursor;
40210
+ this.#dbPath = nativeConversationDbPath(options.nativeSessionId, options.home);
40211
+ this.#readHistory = options.readHistory ?? readNativeHistory;
40212
+ this.#pollDelaysMs = options.pollDelaysMs && options.pollDelaysMs.length > 0 ? options.pollDelaysMs : WAKE_COMMIT_POLL_DELAYS_MS;
39396
40213
  }
39397
40214
  get observing() {
39398
40215
  return this.#work !== void 0 || this.#timer !== void 0;
@@ -39401,8 +40218,16 @@ var AntigravityWakeObserver = class {
39401
40218
  if (this.#closed)
39402
40219
  return;
39403
40220
  this.#deadline = Date.now() + COMMIT_WAIT_MS;
39404
- if (!this.observing)
39405
- void this.#startRead();
40221
+ this.#pollAttempt = 0;
40222
+ const firstDelay = this.#pollDelaysMs[0] ?? WAKE_COMMIT_POLL_DELAYS_MS[0];
40223
+ if (!this.observing) {
40224
+ void this.#startRead(false);
40225
+ } else if (this.#timer && this.#timerDelayMs > firstDelay) {
40226
+ clearTimeout(this.#timer);
40227
+ this.#timer = void 0;
40228
+ this.#timerDelayMs = 0;
40229
+ this.#scheduleNextPoll();
40230
+ }
39406
40231
  }
39407
40232
  /** Probe once before submitting a successor, without waiting on a pending native wake. */
39408
40233
  async flush() {
@@ -39412,19 +40237,46 @@ var AntigravityWakeObserver = class {
39412
40237
  return this.#work;
39413
40238
  clearTimeout(this.#timer);
39414
40239
  this.#timer = void 0;
39415
- return this.#startRead();
40240
+ this.#timerDelayMs = 0;
40241
+ return this.#startRead(true);
39416
40242
  }
39417
- #startRead() {
39418
- return this.#work = this.#read().finally(() => {
40243
+ #startRead(force) {
40244
+ return this.#work = this.#read(force).finally(() => {
39419
40245
  this.#work = void 0;
39420
40246
  });
39421
40247
  }
39422
- async #read() {
40248
+ #scheduleNextPoll() {
40249
+ if (this.#closed || Date.now() >= this.#deadline)
40250
+ return;
40251
+ const index = Math.min(this.#pollAttempt, this.#pollDelaysMs.length - 1);
40252
+ const delay3 = this.#pollDelaysMs[index] ?? this.#pollDelaysMs[this.#pollDelaysMs.length - 1] ?? WAKE_COMMIT_POLL_DELAYS_MS[0];
40253
+ this.#pollAttempt += 1;
40254
+ this.#timerDelayMs = delay3;
40255
+ this.#timer = setTimeout(() => {
40256
+ this.#timer = void 0;
40257
+ this.#timerDelayMs = 0;
40258
+ void this.#startRead(false);
40259
+ }, delay3);
40260
+ this.#timer.unref();
40261
+ }
40262
+ async #read(force) {
39423
40263
  try {
40264
+ const fingerprint = await readNativeDbFingerprint(this.#dbPath);
40265
+ if (this.#closed)
40266
+ return;
40267
+ if (!force && fingerprint !== null && fingerprint === this.#lastFingerprint) {
40268
+ return;
40269
+ }
40270
+ if (fingerprint !== this.#lastFingerprint) {
40271
+ this.#pollAttempt = 0;
40272
+ }
39424
40273
  const { nativeSessionId, home, cwd, outputLimit } = this.options;
39425
- const { events, wakeWatermark } = await readNativeHistory(nativeSessionId, home);
40274
+ const promptWindows = await this.options.promptWindows?.();
40275
+ const { events, wakeWatermark } = await this.#readHistory(nativeSessionId, home, promptWindows ? { promptWindows } : void 0);
39426
40276
  if (this.#closed || !this.options.canPublish())
39427
40277
  return;
40278
+ if (fingerprint !== null)
40279
+ this.#lastFingerprint = fingerprint;
39428
40280
  if (wakeWatermark <= this.#cursor)
39429
40281
  return;
39430
40282
  const turns = projectReplayedEventsToTurns({
@@ -39447,19 +40299,14 @@ var AntigravityWakeObserver = class {
39447
40299
  }
39448
40300
  } catch {
39449
40301
  } finally {
39450
- if (!this.#closed && Date.now() < this.#deadline) {
39451
- this.#timer = setTimeout(() => {
39452
- this.#timer = void 0;
39453
- void this.#startRead();
39454
- }, COMMIT_POLL_MS);
39455
- this.#timer.unref();
39456
- }
40302
+ this.#scheduleNextPoll();
39457
40303
  }
39458
40304
  }
39459
40305
  close() {
39460
40306
  this.#closed = true;
39461
40307
  clearTimeout(this.#timer);
39462
40308
  this.#timer = void 0;
40309
+ this.#timerDelayMs = 0;
39463
40310
  }
39464
40311
  };
39465
40312
 
@@ -39886,36 +40733,21 @@ async function rollbackAntigravityLastTurn(options) {
39886
40733
  retryable: true
39887
40734
  }
39888
40735
  };
39889
- try {
39890
- const boundaries = await readDerivationBoundaries(nativeConversationDbPath(input3.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input3.environment })));
39891
- const last = boundaries.at(-1);
39892
- if (!last)
39893
- return {
39894
- ok: false,
39895
- error: {
39896
- code: "invalidState",
39897
- message: "Antigravity Native Session has no Turn to roll back",
39898
- retryable: false
39899
- }
39900
- };
39901
- return openDerivedAntigravitySession(options, {
39902
- kind: "resume",
39903
- nativeRef: input3.sourceRef,
39904
- cwd: input3.cwd,
39905
- ...input3.environment ? { environment: input3.environment } : {},
39906
- ...input3.model ? { model: input3.model } : {},
39907
- ...input3.thinkingOptionId ? { thinkingOptionId: input3.thinkingOptionId } : {},
39908
- ...input3.permissionModeId ? { permissionModeId: input3.permissionModeId } : {}
39909
- }, input3.sourceRef, { cutoff: boundaries.length === 1 ? 0 : last.idx });
39910
- } catch (error62) {
39911
- return { ok: false, error: nativeHistoryError(error62) };
39912
- }
40736
+ return openDerivedAntigravitySession(options, {
40737
+ kind: "resume",
40738
+ nativeRef: input3.sourceRef,
40739
+ cwd: input3.cwd,
40740
+ ...input3.environment ? { environment: input3.environment } : {},
40741
+ ...input3.model ? { model: input3.model } : {},
40742
+ ...input3.thinkingOptionId ? { thinkingOptionId: input3.thinkingOptionId } : {},
40743
+ ...input3.permissionModeId ? { permissionModeId: input3.permissionModeId } : {}
40744
+ }, input3.sourceRef, { rollbackLastTurn: true });
39913
40745
  }
39914
40746
 
39915
40747
  // dist/session-import.js
39916
40748
  import { constants, createReadStream as createReadStream3 } from "node:fs";
39917
- import { access as access3, stat as stat2 } from "node:fs/promises";
39918
- import path12 from "node:path";
40749
+ import { access as access3, stat as stat3 } from "node:fs/promises";
40750
+ import path13 from "node:path";
39919
40751
  import { createInterface as createInterface2 } from "node:readline";
39920
40752
  import { fileURLToPath } from "node:url";
39921
40753
  var SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
@@ -39942,9 +40774,9 @@ function workspacePaths(raw) {
39942
40774
  continue;
39943
40775
  cwd = fileURLToPath(url2);
39944
40776
  }
39945
- if (!path12.isAbsolute(cwd))
40777
+ if (!path13.isAbsolute(cwd))
39946
40778
  continue;
39947
- cwd = path12.resolve(cwd);
40779
+ cwd = path13.resolve(cwd);
39948
40780
  const normalized = `${cwd.replaceAll("\\", "/")}/`;
39949
40781
  if (normalized.includes("/.codexhost/antigravity-history/hooks/"))
39950
40782
  continue;
@@ -40049,14 +40881,14 @@ var AntigravitySessionImport = class {
40049
40881
  await access3(file2, constants.R_OK);
40050
40882
  let cwd;
40051
40883
  for (const directory of workspacePaths(row.workspace_uris)) {
40052
- if ((await stat2(directory).catch(() => null))?.isDirectory()) {
40884
+ if ((await stat3(directory).catch(() => null))?.isDirectory()) {
40053
40885
  cwd = directory;
40054
40886
  break;
40055
40887
  }
40056
40888
  }
40057
40889
  if (!cwd)
40058
40890
  return null;
40059
- const title = sessionImportTitle(row.title) ?? sessionImportTitle(row.preview) ?? await firstUserTitle(path12.join(nativeBrainDirPath(id2, this.#home), ".system_generated", "logs", "transcript.jsonl"), signal);
40891
+ const title = sessionImportTitle(row.title) ?? sessionImportTitle(row.preview) ?? await firstUserTitle(path13.join(nativeBrainDirPath(id2, this.#home), ".system_generated", "logs", "transcript.jsonl"), signal);
40060
40892
  signal.throwIfAborted();
40061
40893
  const candidate = sessionImportCandidate({
40062
40894
  nativeSessionId: id2,
@@ -40084,8 +40916,8 @@ var AntigravitySessionImport = class {
40084
40916
  };
40085
40917
 
40086
40918
  // dist/subagent-transcript.js
40087
- import { open as open4, realpath as realpath2 } from "node:fs/promises";
40088
- import path13 from "node:path";
40919
+ import { open as open5, realpath as realpath2 } from "node:fs/promises";
40920
+ import path14 from "node:path";
40089
40921
  var nativeSubagentIdSchema = external_exports.uuid();
40090
40922
  var MAX_TRANSCRIPT_BYTES = 8 * 1024 * 1024;
40091
40923
  var transcriptStepSchema = external_exports.object({
@@ -40216,14 +41048,14 @@ async function readSubagentTranscript(input3) {
40216
41048
  };
40217
41049
  }
40218
41050
  try {
40219
- const file2 = path13.join(nativeBrainDirPath(input3.childId, input3.home), ".system_generated", "logs", "transcript.jsonl");
40220
- const brainRoot = await realpath2(path13.dirname(nativeBrainDirPath(input3.childId, input3.home)));
41051
+ const file2 = path14.join(nativeBrainDirPath(input3.childId, input3.home), ".system_generated", "logs", "transcript.jsonl");
41052
+ const brainRoot = await realpath2(path14.dirname(nativeBrainDirPath(input3.childId, input3.home)));
40221
41053
  const resolved = await realpath2(file2);
40222
- const expected = path13.join(brainRoot, input3.childId, ".system_generated", "logs", "transcript.jsonl");
41054
+ const expected = path14.join(brainRoot, input3.childId, ".system_generated", "logs", "transcript.jsonl");
40223
41055
  const normalize = (value) => process.platform === "win32" ? value.toLowerCase() : value;
40224
41056
  if (normalize(resolved) !== normalize(expected))
40225
41057
  throw new Error("Subagent log redirects outside its native location");
40226
- const handle = await open4(resolved, "r");
41058
+ const handle = await open5(resolved, "r");
40227
41059
  let text3;
40228
41060
  try {
40229
41061
  const size = (await handle.stat()).size;
@@ -40421,7 +41253,8 @@ var AntigravitySubagents = class {
40421
41253
  // dist/antigravity-adapter.js
40422
41254
  var harnessId = harnessIdSchema.parse("antigravity");
40423
41255
  var SKIP = "dangerously-skip-permissions";
40424
- var QUOTA_REFRESH_COOLDOWN_MS = 6e4;
41256
+ var QUOTA_REFRESH_COOLDOWN_MS = 6e5;
41257
+ var COMPACTION_SYNC_DEBOUNCE_MS = 120;
40425
41258
  var antigravitySessionCapabilities = {
40426
41259
  configuration: {
40427
41260
  selectModel: true,
@@ -40489,6 +41322,8 @@ function runQuotaCli(executable, args, cwd, environment, timeout, signal) {
40489
41322
  if (settled)
40490
41323
  return;
40491
41324
  settled = true;
41325
+ clearTimeout(timer);
41326
+ signal.removeEventListener("abort", onAbort);
40492
41327
  done();
40493
41328
  };
40494
41329
  const onAbort = () => {
@@ -40502,8 +41337,6 @@ function runQuotaCli(executable, args, cwd, environment, timeout, signal) {
40502
41337
  timer.unref?.();
40503
41338
  signal.addEventListener("abort", onAbort, { once: true });
40504
41339
  child.on("error", (error62) => {
40505
- clearTimeout(timer);
40506
- signal.removeEventListener("abort", onAbort);
40507
41340
  finish(() => reject(error62));
40508
41341
  });
40509
41342
  child.stdout.setEncoding("utf8");
@@ -40513,14 +41346,17 @@ function runQuotaCli(executable, args, cwd, environment, timeout, signal) {
40513
41346
  stdout += chunk;
40514
41347
  if (Buffer.byteLength(stdout, "utf8") > maxBytes) {
40515
41348
  child.kill("SIGKILL");
40516
- clearTimeout(timer);
40517
- signal.removeEventListener("abort", onAbort);
40518
41349
  finish(() => reject(new Error("Antigravity quota output exceeded 4 MiB")));
40519
41350
  return;
40520
41351
  }
40521
41352
  if (stdout.includes("\n") && stdout.includes('"command_result"')) {
40522
41353
  for (const line of stdout.split(/\r?\n/u).slice(0, -1)) {
40523
41354
  if (line.includes('"command_result"')) {
41355
+ const exitTimer = setTimeout(() => {
41356
+ child.kill("SIGKILL");
41357
+ }, 2e3);
41358
+ exitTimer.unref?.();
41359
+ child.once("close", () => clearTimeout(exitTimer));
40524
41360
  child.unref();
40525
41361
  finish(() => resolve(stdout));
40526
41362
  return;
@@ -40529,8 +41365,6 @@ function runQuotaCli(executable, args, cwd, environment, timeout, signal) {
40529
41365
  }
40530
41366
  });
40531
41367
  child.on("close", (code) => {
40532
- clearTimeout(timer);
40533
- signal.removeEventListener("abort", onAbort);
40534
41368
  if (code === 0)
40535
41369
  finish(() => resolve(stdout));
40536
41370
  else
@@ -40569,9 +41403,11 @@ var AntigravitySession = class {
40569
41403
  #active;
40570
41404
  #wakes;
40571
41405
  #postPromptWake = false;
40572
- // Intervals during which a prompt was in flight on ACP; wakes started inside
40573
- // any window streamed into that user Turn and must not be republished.
41406
+ // Intervals during which a prompt chain was in flight on ACP; wakes started inside
41407
+ // any window streamed into that user Turn and must not be split or republished.
40574
41408
  #promptWindows = [];
41409
+ #unsavedPromptWindows = [];
41410
+ #promptWindowWrites = Promise.resolve();
40575
41411
  #toolOwners = /* @__PURE__ */ new Map();
40576
41412
  #pending = /* @__PURE__ */ new Map();
40577
41413
  #usage;
@@ -40579,6 +41415,9 @@ var AntigravitySession = class {
40579
41415
  #usageDirty = false;
40580
41416
  #usageRetry;
40581
41417
  #usageTurnId;
41418
+ #lastUsageKey;
41419
+ #lastUsageComplete;
41420
+ #lastUsageTurnId;
40582
41421
  #abort = new AbortController();
40583
41422
  #closed = false;
40584
41423
  #faulted = false;
@@ -40628,6 +41467,45 @@ var AntigravitySession = class {
40628
41467
  hasBackgroundWork() {
40629
41468
  return this.#subagents.running || !!this.#wakes?.observing || this.#pending.size > 0 || [...this.#toolOwners.values()].some((turn) => turn.detachedToolCallIds.size > 0);
40630
41469
  }
41470
+ currentPromptWindows() {
41471
+ const turn = this.#active;
41472
+ const activeWindow = turn?.promptPhase === "submitted" && turn.submittedAtMs !== void 0 && turn.returnedAtMs === void 0 ? [{ submittedAtMs: turn.submittedAtMs, returnedAtMs: Number.POSITIVE_INFINITY }] : void 0;
41473
+ return mergePromptWindows(this.#promptWindows, activeWindow);
41474
+ }
41475
+ async #readPersistedPromptWindows(nativeSessionId) {
41476
+ try {
41477
+ return await readPromptWindows(nativeSessionId, this.#options.environment);
41478
+ } catch {
41479
+ return [];
41480
+ }
41481
+ }
41482
+ async #preparePromptWindows(nativeSessionId) {
41483
+ const persisted = await this.#readPersistedPromptWindows(nativeSessionId);
41484
+ return () => mergePromptWindows(persisted, this.currentPromptWindows());
41485
+ }
41486
+ #recordPromptWindow(turn, nativeSessionId) {
41487
+ if (turn.returnedAtMs !== void 0 || turn.submittedAtMs === void 0)
41488
+ return false;
41489
+ const returnedAtMs = Math.max(Date.now(), turn.lastSubmittedAtMs ?? turn.submittedAtMs);
41490
+ turn.returnedAtMs = returnedAtMs;
41491
+ const window = { submittedAtMs: turn.submittedAtMs, returnedAtMs };
41492
+ this.#promptWindows.push(window);
41493
+ this.#unsavedPromptWindows.push(window);
41494
+ void this.#flushPromptWindows(nativeSessionId);
41495
+ return true;
41496
+ }
41497
+ #flushPromptWindows(nativeSessionId, options) {
41498
+ const attempt = this.#promptWindowWrites.then(async () => {
41499
+ const batch = mergePromptWindows(this.#unsavedPromptWindows);
41500
+ if (!batch.length)
41501
+ return;
41502
+ await savePromptWindows(nativeSessionId, batch, this.#options.environment);
41503
+ const saved = new Set(batch.map((entry) => `${entry.submittedAtMs}:${entry.returnedAtMs}`));
41504
+ this.#unsavedPromptWindows = this.#unsavedPromptWindows.filter((entry) => !saved.has(`${entry.submittedAtMs}:${entry.returnedAtMs}`));
41505
+ });
41506
+ this.#promptWindowWrites = attempt.catch(() => void 0);
41507
+ return options?.propagateError ? attempt : this.#promptWindowWrites;
41508
+ }
40631
41509
  activeForkTurnIndex(checkpointId, home) {
40632
41510
  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))
40633
41511
  return this.#confirmedCount;
@@ -40684,11 +41562,14 @@ var AntigravitySession = class {
40684
41562
  this.#titleReadWork = work;
40685
41563
  await work;
40686
41564
  }
41565
+ get hasActiveTurn() {
41566
+ return this.#active !== void 0;
41567
+ }
40687
41568
  /** Leads with the quota group that bills this Session's current Model. */
40688
41569
  readAccountCredits() {
40689
41570
  if (this.#closed)
40690
41571
  return Promise.resolve(null);
40691
- this.#options.quota.refresh();
41572
+ this.#options.quota.refresh({ activeTurn: this.#active !== void 0 });
40692
41573
  return Promise.resolve(this.#options.quota.read(this.#creditsModelId));
40693
41574
  }
40694
41575
  #delegationPrompt() {
@@ -40753,7 +41634,14 @@ var AntigravitySession = class {
40753
41634
  this.#initializeUsage(opened.sessionId);
40754
41635
  if (!this.#wakes) {
40755
41636
  const home = antigravityHome(this.#options.environment);
40756
- const cursor = ref ? await readNativeHistory(opened.sessionId, home).then((value) => value.wakeWatermark, () => -1) : -1;
41637
+ const persistedWindows = ref ? await this.#readPersistedPromptWindows(opened.sessionId) : [];
41638
+ if (this.#closed || this.#faulted)
41639
+ return;
41640
+ if (persistedWindows.length)
41641
+ this.#promptWindows = mergePromptWindows(persistedWindows, this.#promptWindows);
41642
+ const cursor = ref ? await readNativeHistory(opened.sessionId, home, {
41643
+ promptWindows: () => this.currentPromptWindows()
41644
+ }).then((value) => value.wakeWatermark, () => -1) : -1;
40757
41645
  if (this.#closed || this.#faulted)
40758
41646
  return;
40759
41647
  this.#wakes = new AntigravityWakeObserver({
@@ -40763,14 +41651,8 @@ var AntigravitySession = class {
40763
41651
  cursor,
40764
41652
  outputLimit: this.#options.adapter.toolOutputLimit,
40765
41653
  canPublish: () => this.#active?.promptPhase !== "returned",
40766
- streamedIntoPrompt: (startedAtMs) => {
40767
- if (startedAtMs === void 0)
40768
- return false;
40769
- const turn = this.#active;
40770
- if (turn?.promptPhase === "submitted" && turn.submittedAtMs !== void 0 && startedAtMs >= turn.submittedAtMs)
40771
- return true;
40772
- return this.#promptWindows.some((window) => startedAtMs >= window.submittedAtMs && startedAtMs <= window.returnedAtMs);
40773
- },
41654
+ promptWindows: () => this.#preparePromptWindows(opened.sessionId),
41655
+ streamedIntoPrompt: (startedAtMs) => isTimestampInPromptWindows(startedAtMs, this.currentPromptWindows()),
40774
41656
  publish: (snapshot) => this.#emit({ type: "turn.autonomous.completed", snapshot })
40775
41657
  });
40776
41658
  }
@@ -40982,7 +41864,7 @@ var AntigravitySession = class {
40982
41864
  this.#emit({ type: "session.usage.changed", usage });
40983
41865
  if (this.#active?.promptPhase === "submitted") {
40984
41866
  void this.refreshUsage();
40985
- void this.#syncTurnCompactions(this.#active);
41867
+ this.#scheduleTurnCompactionSync(this.#active);
40986
41868
  this.#scheduleUsageRetry();
40987
41869
  }
40988
41870
  break;
@@ -41002,11 +41884,16 @@ var AntigravitySession = class {
41002
41884
  return;
41003
41885
  for (const request of history.requests)
41004
41886
  this.#emit({ type: "usage.request", request });
41887
+ this.#lastUsageComplete = history.complete;
41888
+ this.#lastUsageKey = JSON.stringify(history.usage);
41889
+ this.#lastUsageTurnId = void 0;
41005
41890
  this.#emit({ type: "usage.history", complete: history.complete });
41006
41891
  this.#emit({ type: "session.usage.changed", usage: history.usage });
41007
41892
  } catch {
41008
- if (!this.#closed && !this.#faulted)
41893
+ if (!this.#closed && !this.#faulted) {
41894
+ this.#lastUsageComplete = false;
41009
41895
  this.#emit({ type: "usage.history", complete: false });
41896
+ }
41010
41897
  }
41011
41898
  }
41012
41899
  async refreshUsage() {
@@ -41066,18 +41953,27 @@ var AntigravitySession = class {
41066
41953
  return;
41067
41954
  for (const request of update.requests)
41068
41955
  this.#emit({ type: "usage.request", request });
41069
- this.#emit({ type: "usage.history", complete: recorded.complete });
41070
- this.#emit({
41071
- type: "session.usage.changed",
41072
- usage: recorded.usage,
41073
- ...this.#usageTurnId && { observedForTurnId: this.#usageTurnId }
41074
- });
41956
+ const usageKey = JSON.stringify(recorded.usage);
41957
+ const changed = final !== void 0 || update.requests.length > 0 || update.timings.length > 0 || this.#lastUsageComplete !== recorded.complete || this.#lastUsageKey !== usageKey || this.#lastUsageTurnId !== this.#usageTurnId;
41958
+ if (changed) {
41959
+ this.#lastUsageComplete = recorded.complete;
41960
+ this.#lastUsageKey = usageKey;
41961
+ this.#lastUsageTurnId = this.#usageTurnId;
41962
+ this.#emit({ type: "usage.history", complete: recorded.complete });
41963
+ this.#emit({
41964
+ type: "session.usage.changed",
41965
+ usage: recorded.usage,
41966
+ ...this.#usageTurnId && { observedForTurnId: this.#usageTurnId }
41967
+ });
41968
+ }
41075
41969
  for (const { turnId, ...timing2 } of update.timings)
41076
41970
  if (turnId)
41077
41971
  this.#emit({ type: "usage.request.timing", turnId, timing: timing2 });
41078
41972
  } catch {
41079
- if (!this.#closed && !this.#faulted)
41973
+ if (!this.#closed && !this.#faulted) {
41974
+ this.#lastUsageComplete = false;
41080
41975
  this.#emit({ type: "usage.history", complete: false });
41976
+ }
41081
41977
  }
41082
41978
  }
41083
41979
  #notifyCommandsChanged() {
@@ -41163,7 +42059,8 @@ var AntigravitySession = class {
41163
42059
  return ok({ turns: [], state: { ...this.#state } });
41164
42060
  const { nativeSessionId } = nativeRef;
41165
42061
  try {
41166
- const { events, turnCount } = await readNativeHistory(nativeSessionId, antigravityHome(this.#options.environment));
42062
+ const promptWindows = await this.#preparePromptWindows(nativeSessionId);
42063
+ const { events, turnCount } = await readNativeHistory(nativeSessionId, antigravityHome(this.#options.environment), { promptWindows });
41167
42064
  if (this.#closed || this.#faulted)
41168
42065
  return err("invalidState", "Session is closed");
41169
42066
  const turns = projectReplayedEventsToTurns({
@@ -41475,14 +42372,8 @@ var AntigravitySession = class {
41475
42372
  this.#usage?.beginTurn(submittedAtMs, turn.turnId);
41476
42373
  this.#usageTurnId = turn.turnId;
41477
42374
  turn.promptPhase = "submitted";
41478
- let windowRecorded = false;
41479
42375
  const recordPromptWindow = () => {
41480
- if (windowRecorded)
41481
- return;
41482
- windowRecorded = true;
41483
- const returnedAtMs = Date.now();
41484
- turn.returnedAtMs = returnedAtMs;
41485
- this.#promptWindows.push({ submittedAtMs, returnedAtMs });
42376
+ void this.#recordPromptWindow(turn, ref.nativeSessionId);
41486
42377
  };
41487
42378
  const responded = () => {
41488
42379
  if (turn.promptPhase === "returned")
@@ -41556,13 +42447,12 @@ var AntigravitySession = class {
41556
42447
  }
41557
42448
  }
41558
42449
  } finally {
41559
- recordPromptWindow();
42450
+ responded();
41560
42451
  }
41561
42452
  if (hasLatestError || !result)
41562
42453
  throw latestError;
41563
42454
  if (turn.steered)
41564
42455
  mayWriteInput = true;
41565
- responded();
41566
42456
  const completedAtMs = Date.now();
41567
42457
  if (!this.#isCurrent(turn))
41568
42458
  return;
@@ -41597,7 +42487,7 @@ var AntigravitySession = class {
41597
42487
  completedAtMs,
41598
42488
  ...combinedUsage && { usage: combinedUsage }
41599
42489
  })));
41600
- await this.#syncTurnCompactions(turn);
42490
+ await this.#syncTurnCompactions(turn, true);
41601
42491
  this.#scheduleUsageRetry();
41602
42492
  } catch (error62) {
41603
42493
  if (error62 instanceof AntigravityTransportError && (error62.kind === "processExited" || error62.kind === "protocolError" || this.#transport?.isClosed)) {
@@ -41606,6 +42496,7 @@ var AntigravitySession = class {
41606
42496
  outcome = turn.cancelled ? { status: "cancelled" } : { status: "failed", error: normalizeAntigravityError(error62) };
41607
42497
  } finally {
41608
42498
  this.#usage?.endTurn();
42499
+ await this.#promptWindowWrites;
41609
42500
  }
41610
42501
  if (turn.cancelled && outcome.status === "succeeded")
41611
42502
  outcome = { ...outcome, status: "cancelled" };
@@ -41665,12 +42556,67 @@ var AntigravitySession = class {
41665
42556
  });
41666
42557
  turn.textItem = void 0;
41667
42558
  }
41668
- async #syncTurnCompactions(turn) {
42559
+ #scheduleTurnCompactionSync(turn) {
42560
+ if (!this.#isCurrent(turn) || turn.cancelled || this.#abort.signal.aborted)
42561
+ return;
42562
+ if (turn.compactionTimer)
42563
+ return;
42564
+ const elapsed = Date.now() - (turn.compactionLastSyncAtMs ?? 0);
42565
+ if (!turn.compactionWork && elapsed >= COMPACTION_SYNC_DEBOUNCE_MS) {
42566
+ void this.#syncTurnCompactions(turn);
42567
+ return;
42568
+ }
42569
+ const delay3 = turn.compactionWork ? COMPACTION_SYNC_DEBOUNCE_MS : Math.max(1, COMPACTION_SYNC_DEBOUNCE_MS - elapsed);
42570
+ turn.compactionTimer = setTimeout(() => {
42571
+ turn.compactionTimer = void 0;
42572
+ void this.#syncTurnCompactions(turn);
42573
+ }, delay3);
42574
+ turn.compactionTimer.unref();
42575
+ }
42576
+ async #syncTurnCompactions(turn, force = false) {
42577
+ if (force && turn.compactionTimer) {
42578
+ clearTimeout(turn.compactionTimer);
42579
+ turn.compactionTimer = void 0;
42580
+ }
42581
+ if (turn.compactionWork) {
42582
+ turn.compactionDirty = true;
42583
+ if (force)
42584
+ turn.compactionForce = true;
42585
+ await turn.compactionWork;
42586
+ return;
42587
+ }
42588
+ const drain = async () => {
42589
+ try {
42590
+ await this.#runTurnCompactionSync(turn, force);
42591
+ while (turn.compactionWork === tracked && turn.compactionDirty) {
42592
+ const rerunForce = turn.compactionForce === true;
42593
+ turn.compactionDirty = false;
42594
+ turn.compactionForce = false;
42595
+ await this.#runTurnCompactionSync(turn, rerunForce);
42596
+ }
42597
+ } finally {
42598
+ if (turn.compactionWork === tracked)
42599
+ turn.compactionWork = void 0;
42600
+ }
42601
+ };
42602
+ const tracked = drain();
42603
+ turn.compactionWork = tracked;
42604
+ await tracked;
42605
+ }
42606
+ async #runTurnCompactionSync(turn, force) {
41669
42607
  if (!this.#isCurrent(turn) || turn.cancelled || turn.dbPath === void 0 || turn.compactionAfterStep === void 0)
41670
42608
  return;
42609
+ turn.compactionLastSyncAtMs = Date.now();
42610
+ const fingerprint = await readNativeDbFingerprint(turn.dbPath);
42611
+ if (!this.#isCurrent(turn) || turn.cancelled)
42612
+ return;
42613
+ if (!force && fingerprint !== null && fingerprint === turn.compactionDbFingerprint)
42614
+ return;
41671
42615
  const compactions = await readNativeTurnCompactions(turn.dbPath, turn.compactionAfterStep, (createdAtMs) => createdAtMs !== void 0 && turn.submittedAtMs !== void 0 && createdAtMs >= turn.submittedAtMs && (turn.returnedAtMs === void 0 || createdAtMs <= turn.returnedAtMs));
41672
42616
  if (!this.#isCurrent(turn) || turn.cancelled)
41673
42617
  return;
42618
+ if (fingerprint !== null)
42619
+ turn.compactionDbFingerprint = fingerprint;
41674
42620
  for (const compaction of compactions) {
41675
42621
  if (turn.emittedCompactions.has(compaction.stepIndex))
41676
42622
  continue;
@@ -41691,6 +42637,10 @@ var AntigravitySession = class {
41691
42637
  #finish(turn, outcome, nativeTurnRef) {
41692
42638
  if (!this.#isCurrent(turn))
41693
42639
  return;
42640
+ if (turn.compactionTimer) {
42641
+ clearTimeout(turn.compactionTimer);
42642
+ turn.compactionTimer = void 0;
42643
+ }
41694
42644
  this.#completeText(turn, outcome);
41695
42645
  const pendingToolCallIds = new Set([...this.#pending.values()].filter((pending) => pending.owner === turn && pending.interaction.type === "question" && pending.toolCallId !== void 0).map((pending) => pending.toolCallId));
41696
42646
  turn.detachedToolCallIds = outcome.status === "succeeded" ? turn.tracker?.detachPending(pendingToolCallIds) ?? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set();
@@ -41859,8 +42809,15 @@ var AntigravitySession = class {
41859
42809
  this.#wakes?.close();
41860
42810
  this.#postPromptWake = false;
41861
42811
  this.#closeInteractions("cancelled");
41862
- if (this.#active)
41863
- this.#finish(this.#active, { status: "failed", error: normalizeAntigravityError(error62) });
42812
+ const active2 = this.#active;
42813
+ if (this.nativeRef) {
42814
+ const recorded = active2 ? this.#recordPromptWindow(active2, this.nativeRef.nativeSessionId) : false;
42815
+ if (!recorded && this.#unsavedPromptWindows.length) {
42816
+ void this.#flushPromptWindows(this.nativeRef.nativeSessionId);
42817
+ }
42818
+ }
42819
+ if (active2)
42820
+ this.#finish(active2, { status: "failed", error: normalizeAntigravityError(error62) });
41864
42821
  this.#settleDetachedOwners({ status: "failed", error: normalizeAntigravityError(error62) });
41865
42822
  this.#emit({ type: "session.faulted", error: normalizeAntigravityError(error62) });
41866
42823
  this.#channel.end();
@@ -41883,6 +42840,8 @@ var AntigravitySession = class {
41883
42840
  this.#pendingTitle = void 0;
41884
42841
  this.#closeInteractions("cancelled");
41885
42842
  const active2 = this.#active;
42843
+ if (active2 && this.nativeRef)
42844
+ this.#recordPromptWindow(active2, this.nativeRef.nativeSessionId);
41886
42845
  if (active2)
41887
42846
  this.#finish(active2, { status: "cancelled", reason: "Session closed" });
41888
42847
  this.#settleDetachedOwners({ status: "cancelled", reason: "Session closed" });
@@ -41892,6 +42851,10 @@ var AntigravitySession = class {
41892
42851
  if (active2?.promptPhase === "submitted")
41893
42852
  await this.#transport?.cancel().catch(() => void 0);
41894
42853
  await Promise.all([this.#transport?.close(), this.#subagents.close()]);
42854
+ await this.#promptWindowWrites;
42855
+ if (this.nativeRef && this.#unsavedPromptWindows.length) {
42856
+ await this.#flushPromptWindows(this.nativeRef.nativeSessionId, { propagateError: true });
42857
+ }
41895
42858
  this.#options.onClosed(this);
41896
42859
  }
41897
42860
  };
@@ -41957,7 +42920,7 @@ var AntigravityAdapter = class {
41957
42920
  status: "unavailable",
41958
42921
  error: { code: "invalidState", message: "Adapter is closed", retryable: false }
41959
42922
  };
41960
- const cwd = path14.resolve(input3.cwd ?? process.cwd());
42923
+ const cwd = path15.resolve(input3.cwd ?? process.cwd());
41961
42924
  const key = `${cwd}\0${input3.purpose ?? "catalog"}`;
41962
42925
  const cached2 = this.#cache.get(key);
41963
42926
  const inFlight = this.#inflight.get(key);
@@ -42027,10 +42990,10 @@ var AntigravityAdapter = class {
42027
42990
  async open(input3) {
42028
42991
  if (this.#closed)
42029
42992
  return err("invalidState", "Adapter is closed");
42030
- if (!input3.cwd || !path14.isAbsolute(input3.cwd))
42993
+ if (!input3.cwd || !path15.isAbsolute(input3.cwd))
42031
42994
  return err("invalidRequest", "cwd must be an absolute directory");
42032
42995
  try {
42033
- if (!(await stat3(input3.cwd)).isDirectory())
42996
+ if (!(await stat4(input3.cwd)).isDirectory())
42034
42997
  return err("invalidRequest", "cwd is not a directory");
42035
42998
  } catch {
42036
42999
  return err("invalidRequest", "cwd is unavailable");
@@ -42044,6 +43007,7 @@ var AntigravityAdapter = class {
42044
43007
  const common = {
42045
43008
  harnessId,
42046
43009
  adapterEnvironment: this.#environment,
43010
+ ...source ? { sourcePromptWindows: () => source.currentPromptWindows() } : {},
42047
43011
  openSession: async (resume) => {
42048
43012
  const result = await this.open(resume);
42049
43013
  if (!result.ok || !(result.value instanceof AntigravitySession))
@@ -42096,7 +43060,7 @@ var AntigravityAdapter = class {
42096
43060
  adapter: this.options,
42097
43061
  quota: {
42098
43062
  read: (modelId2) => this.#quota ? projectAntigravityQuota(this.#quota, modelId2) : null,
42099
- refresh: () => void this.#refreshQuota().catch(() => void 0)
43063
+ refresh: (options) => void this.#refreshQuota(false, options).catch(() => void 0)
42100
43064
  },
42101
43065
  onClosed: (closed) => this.#sessions.delete(closed)
42102
43066
  });
@@ -42126,7 +43090,8 @@ var AntigravityAdapter = class {
42126
43090
  environment[key] = value;
42127
43091
  }
42128
43092
  }
42129
- const { events } = await readNativeHistory(input3.nativeRef.nativeSessionId, antigravityHome(environment));
43093
+ const promptWindows = await readPromptWindows(input3.nativeRef.nativeSessionId, environment).catch(() => []);
43094
+ const { events } = await readNativeHistory(input3.nativeRef.nativeSessionId, antigravityHome(environment), { promptWindows });
42130
43095
  const turns = projectReplayedEventsToTurns({
42131
43096
  nativeSessionId: input3.nativeRef.nativeSessionId,
42132
43097
  cwd: input3.cwd,
@@ -42162,14 +43127,20 @@ var AntigravityAdapter = class {
42162
43127
  return this.#quota ? projectAntigravityQuota(this.#quota) : null;
42163
43128
  }
42164
43129
  async refreshCredits() {
42165
- const quota = await this.#refreshQuota();
43130
+ const activeTurn = [...this.#sessions].some((session) => session.hasActiveTurn);
43131
+ const quota = await this.#refreshQuota(false, { activeTurn });
42166
43132
  return quota ? projectAntigravityQuota(quota) : null;
42167
43133
  }
42168
- #refreshQuota(force = false) {
43134
+ #refreshQuota(force = false, options) {
42169
43135
  if (this.#closed)
42170
43136
  return Promise.resolve(null);
42171
- if (!force && !this.#quotaRefresh && Date.now() - this.#quotaFetchedAt < QUOTA_REFRESH_COOLDOWN_MS) {
42172
- return Promise.resolve(this.#quota);
43137
+ if (!force && !this.#quotaRefresh) {
43138
+ if (options?.activeTurn && this.#quotaFetchedAt !== Number.NEGATIVE_INFINITY) {
43139
+ return Promise.resolve(this.#quota);
43140
+ }
43141
+ if (Date.now() - this.#quotaFetchedAt < QUOTA_REFRESH_COOLDOWN_MS) {
43142
+ return Promise.resolve(this.#quota);
43143
+ }
42173
43144
  }
42174
43145
  return this.#quotaRefresh ??= (async () => {
42175
43146
  const command = resolveAntigravityExecutable({