@karlorz/codexhost-cli-darwin-x64 0.21.0-1 → 0.22.0-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 (45) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +1 -0
  4. package/app/console-web.js +2 -1
  5. package/app/cpa-live-voice-hook.js +213 -181
  6. package/app/desktop-controller.mjs +4 -1
  7. package/app/host-runtime.mjs +96 -26
  8. package/app/overlay-voice-bootstrap.js +1 -1616
  9. package/app/plugins/antigravity/plugin.mjs +1144 -1254
  10. package/app/plugins/claude-code/plugin.mjs +389 -80
  11. package/app/plugins/codebuddy/plugin.mjs +1 -0
  12. package/app/plugins/codex-usage/plugin.mjs +1 -0
  13. package/app/plugins/copilot/plugin.mjs +1 -0
  14. package/app/plugins/cursor-cli/plugin.mjs +1 -0
  15. package/app/plugins/deepseek-harness/plugin.mjs +1 -0
  16. package/app/plugins/devin/plugin.mjs +1 -0
  17. package/app/plugins/grok/plugin.mjs +232 -217
  18. package/app/plugins/hermes/plugin.mjs +1 -0
  19. package/app/plugins/kimi-code/plugin.mjs +1 -0
  20. package/app/plugins/kiro-cli/plugin.mjs +1 -0
  21. package/app/plugins/omp/plugin.mjs +108 -22
  22. package/app/plugins/opencode/plugin.mjs +1 -0
  23. package/app/plugins/pi/plugin.mjs +119 -23
  24. package/app/plugins/qoder/plugin.mjs +1 -0
  25. package/app/plugins/qoder-cn/plugin.mjs +1 -0
  26. package/app/plugins/qwen-code/plugin.mjs +1 -0
  27. package/app/plugins/workbuddy/plugin.mjs +1 -0
  28. package/app/plugins/zcode/plugin.mjs +1 -0
  29. package/app/renderer-extension.js +764 -477
  30. package/app/voice-qualification.json +10 -10
  31. package/app/web/assets/index-CYo5zTz_.js +201 -0
  32. package/app/web/codexhost-settings.js +2 -1
  33. package/app/web/index.html +1 -1
  34. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  35. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +3 -3
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +9 -9
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +2 -2
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +1 -1
  40. package/app/web-modules/server.mjs +130 -74
  41. package/bin/codexhost +0 -0
  42. package/libexec/codexhost-shim +0 -0
  43. package/libexec/codexhost-updater +0 -0
  44. package/package.json +1 -1
  45. package/app/web/assets/index-DLXdvkWR.js +0 -201
@@ -1600,14 +1600,14 @@ function prefixIssues(path13, issues) {
1600
1600
  return iss;
1601
1601
  });
1602
1602
  }
1603
- function unwrapMessage(message2) {
1604
- return typeof message2 === "string" ? message2 : message2?.message;
1603
+ function unwrapMessage(message3) {
1604
+ return typeof message3 === "string" ? message3 : message3?.message;
1605
1605
  }
1606
1606
  function finalizeIssue(iss, ctx, config2) {
1607
- const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
1607
+ const message3 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
1608
1608
  const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
1609
1609
  rest.path ?? (rest.path = []);
1610
- rest.message = message2;
1610
+ rest.message = message3;
1611
1611
  if (ctx?.reportInput) {
1612
1612
  rest.input = _input;
1613
1613
  }
@@ -17376,6 +17376,7 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17376
17376
  message: "A history continuation requires its connection epoch"
17377
17377
  }).optional()
17378
17378
  }),
17379
+ external_exports.strictObject({ kind: external_exports.literal("usage"), ...thread, epoch: identity }),
17379
17380
  external_exports.strictObject({
17380
17381
  kind: external_exports.literal("configure"),
17381
17382
  ...thread,
@@ -17538,16 +17539,16 @@ var threadActivityStopResultSchema = external_exports.strictObject({
17538
17539
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
17539
17540
 
17540
17541
  // ../../harness-adapter/dist/approval.js
17541
- function invalidRequest(message2) {
17542
- return { code: "invalidRequest", message: message2, retryable: false };
17542
+ function invalidRequest(message3) {
17543
+ return { code: "invalidRequest", message: message3, retryable: false };
17543
17544
  }
17544
17545
  function validateHostApprovalResponse(interaction, response) {
17545
17546
  return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17546
17547
  }
17547
17548
 
17548
17549
  // ../../harness-adapter/dist/question.js
17549
- function invalidRequest2(message2) {
17550
- return { code: "invalidRequest", message: message2, retryable: false };
17550
+ function invalidRequest2(message3) {
17551
+ return { code: "invalidRequest", message: message3, retryable: false };
17551
17552
  }
17552
17553
  function validateHostQuestionResponse(interaction, response) {
17553
17554
  const questionIds = new Set(interaction.questions.map(({ id }) => id));
@@ -19763,8 +19764,8 @@ var Handled = {
19763
19764
  /**
19764
19765
  * Leaves a message unhandled so later handlers can process it.
19765
19766
  */
19766
- no(message2, retry = false) {
19767
- return { handled: false, message: message2, retry };
19767
+ no(message3, retry = false) {
19768
+ return { handled: false, message: message3, retry };
19768
19769
  }
19769
19770
  };
19770
19771
  function rejectedPromise(error51) {
@@ -20011,8 +20012,8 @@ var Connection = class {
20011
20012
  addDynamicHandler(handler) {
20012
20013
  this.dynamicHandlers.add(handler);
20013
20014
  if (this.retryQueue.length > 0) {
20014
- for (const message2 of this.retryQueue.splice(0)) {
20015
- void this.processIncomingMessage(message2).catch((error51) => this.close(error51));
20015
+ for (const message3 of this.retryQueue.splice(0)) {
20016
+ void this.processIncomingMessage(message3).catch((error51) => this.close(error51));
20016
20017
  }
20017
20018
  }
20018
20019
  return new HandlerRegistration(() => {
@@ -20191,12 +20192,12 @@ var Connection = class {
20191
20192
  }
20192
20193
  legacyHandler(requestHandler, notificationHandler) {
20193
20194
  return {
20194
- handleMessage: async (message2, cx) => {
20195
- if (message2.kind === "request") {
20196
- const result = await requestHandler(message2.method, message2.params, cx);
20197
- await message2.responder.respond(result);
20195
+ handleMessage: async (message3, cx) => {
20196
+ if (message3.kind === "request") {
20197
+ const result = await requestHandler(message3.method, message3.params, cx);
20198
+ await message3.responder.respond(result);
20198
20199
  } else {
20199
- await notificationHandler(message2.method, message2.params, cx);
20200
+ await notificationHandler(message3.method, message3.params, cx);
20200
20201
  }
20201
20202
  return Handled.yes();
20202
20203
  }
@@ -20209,17 +20210,17 @@ var Connection = class {
20209
20210
  this.receiveReader = reader;
20210
20211
  try {
20211
20212
  while (!this.abortController.signal.aborted) {
20212
- const { value: message2, done } = await reader.read();
20213
+ const { value: message3, done } = await reader.read();
20213
20214
  if (this.abortController.signal.aborted) {
20214
20215
  break;
20215
20216
  }
20216
20217
  if (done) {
20217
20218
  break;
20218
20219
  }
20219
- if (!message2) {
20220
+ if (!message3) {
20220
20221
  continue;
20221
20222
  }
20222
- this.receiveWireMessage(message2);
20223
+ this.receiveWireMessage(message3);
20223
20224
  }
20224
20225
  } finally {
20225
20226
  if (this.receiveReader === reader) {
@@ -20233,20 +20234,20 @@ var Connection = class {
20233
20234
  this.close(closeError);
20234
20235
  }
20235
20236
  }
20236
- receiveWireMessage(message2) {
20237
- if (Array.isArray(message2)) {
20237
+ receiveWireMessage(message3) {
20238
+ if (Array.isArray(message3)) {
20238
20239
  if (!this.allowBatches) {
20239
20240
  this.close(new TypeError("JSON-RPC batches are not supported on this connection"));
20240
20241
  return;
20241
20242
  }
20242
- this.receiveBatch(message2);
20243
+ this.receiveBatch(message3);
20243
20244
  return;
20244
20245
  }
20245
- if (!isRecord2(message2)) {
20246
- console.error("Invalid message", { message: message2 });
20246
+ if (!isRecord2(message3)) {
20247
+ console.error("Invalid message", { message: message3 });
20247
20248
  return;
20248
20249
  }
20249
- this.receiveMessage(message2);
20250
+ this.receiveMessage(message3);
20250
20251
  }
20251
20252
  receiveBatch(batch) {
20252
20253
  if (batch.length === 0) {
@@ -20259,9 +20260,9 @@ var Connection = class {
20259
20260
  return;
20260
20261
  }
20261
20262
  const responseBatch = isResponseBatch(batch);
20262
- const responseCount = responseBatch ? 0 : batch.reduce((count5, message2) => count5 + (isNotificationMessage(message2) ? 0 : 1), 0);
20263
+ const responseCount = responseBatch ? 0 : batch.reduce((count5, message3) => count5 + (isNotificationMessage(message3) ? 0 : 1), 0);
20263
20264
  let remaining = responseCount;
20264
- let remainingNotifications = batch.reduce((count5, message2) => count5 + (isNotificationMessage(message2) ? 1 : 0), 0);
20265
+ let remainingNotifications = batch.reduce((count5, message3) => count5 + (isNotificationMessage(message3) ? 1 : 0), 0);
20265
20266
  let responseSent = false;
20266
20267
  const responses = [];
20267
20268
  const sendResponsesIfReady = async () => {
@@ -20276,24 +20277,24 @@ var Connection = class {
20276
20277
  remaining -= 1;
20277
20278
  await sendResponsesIfReady();
20278
20279
  };
20279
- for (const message2 of batch) {
20280
+ for (const message3 of batch) {
20280
20281
  if (responseBatch) {
20281
- if (isResponseShapedMessage(message2)) {
20282
- this.receiveMessage(message2);
20282
+ if (isResponseShapedMessage(message3)) {
20283
+ this.receiveMessage(message3);
20283
20284
  }
20284
20285
  continue;
20285
20286
  }
20286
- if (!isRequestMessage(message2) && !isNotificationMessage(message2)) {
20287
+ if (!isRequestMessage(message3) && !isNotificationMessage(message3)) {
20287
20288
  void collectResponse({
20288
20289
  jsonrpc: "2.0",
20289
20290
  id: null,
20290
- error: RequestError.invalidRequest(message2).toErrorResponse()
20291
+ error: RequestError.invalidRequest(message3).toErrorResponse()
20291
20292
  }).catch(() => {
20292
20293
  });
20293
20294
  continue;
20294
20295
  }
20295
- const processing = this.receiveMessage(message2, isRequestMessage(message2) ? collectResponse : void 0);
20296
- if (isNotificationMessage(message2)) {
20296
+ const processing = this.receiveMessage(message3, isRequestMessage(message3) ? collectResponse : void 0);
20297
+ if (isNotificationMessage(message3)) {
20297
20298
  void processing.finally(() => {
20298
20299
  remainingNotifications -= 1;
20299
20300
  void sendResponsesIfReady().catch((error51) => this.close(error51));
@@ -20301,31 +20302,31 @@ var Connection = class {
20301
20302
  }
20302
20303
  }
20303
20304
  }
20304
- receiveMessage(message2, sendResponse) {
20305
+ receiveMessage(message3, sendResponse) {
20305
20306
  if (this.abortController.signal.aborted) {
20306
20307
  return Promise.resolve();
20307
20308
  }
20308
- if (!isRecord2(message2)) {
20309
- console.error("Invalid message", { message: message2 });
20309
+ if (!isRecord2(message3)) {
20310
+ console.error("Invalid message", { message: message3 });
20310
20311
  return Promise.resolve();
20311
20312
  }
20312
- if ("method" in message2) {
20313
- if (!("id" in message2)) {
20314
- this.handleProtocolNotification(message2);
20313
+ if ("method" in message3) {
20314
+ if (!("id" in message3)) {
20315
+ this.handleProtocolNotification(message3);
20315
20316
  }
20316
- return this.processIncomingMessage(this.toIncomingMessage(message2, sendResponse)).catch((error51) => this.close(error51));
20317
- } else if ("id" in message2) {
20318
- this.handleResponse(message2);
20317
+ return this.processIncomingMessage(this.toIncomingMessage(message3, sendResponse)).catch((error51) => this.close(error51));
20318
+ } else if ("id" in message3) {
20319
+ this.handleResponse(message3);
20319
20320
  } else {
20320
- console.error("Invalid message", { message: message2 });
20321
+ console.error("Invalid message", { message: message3 });
20321
20322
  }
20322
20323
  return Promise.resolve();
20323
20324
  }
20324
- async processIncomingMessage(message2) {
20325
+ async processIncomingMessage(message3) {
20325
20326
  if (this.abortController.signal.aborted) {
20326
20327
  return;
20327
20328
  }
20328
- let current = message2;
20329
+ let current = message3;
20329
20330
  let retry = false;
20330
20331
  try {
20331
20332
  for (const handler of [
@@ -20358,30 +20359,30 @@ var Connection = class {
20358
20359
  } else {
20359
20360
  const response = errorToResult(error51);
20360
20361
  if ("error" in response) {
20361
- console.error("Error handling notification", message2.raw, response.error);
20362
+ console.error("Error handling notification", message3.raw, response.error);
20362
20363
  }
20363
20364
  }
20364
20365
  }
20365
20366
  }
20366
- toIncomingMessage(message2, sendResponse) {
20367
- if ("id" in message2) {
20367
+ toIncomingMessage(message3, sendResponse) {
20368
+ if ("id" in message3) {
20368
20369
  const abortController = new AbortController();
20369
- this.incomingRequests.set(message2.id, abortController);
20370
+ this.incomingRequests.set(message3.id, abortController);
20370
20371
  const finishRequest = () => {
20371
- if (this.incomingRequests.get(message2.id) === abortController) {
20372
- this.incomingRequests.delete(message2.id);
20372
+ if (this.incomingRequests.get(message3.id) === abortController) {
20373
+ this.incomingRequests.delete(message3.id);
20373
20374
  }
20374
20375
  };
20375
20376
  return {
20376
20377
  kind: "request",
20377
- method: message2.method,
20378
- params: message2.params,
20379
- raw: message2,
20378
+ method: message3.method,
20379
+ params: message3.params,
20380
+ raw: message3,
20380
20381
  signal: abortController.signal,
20381
- responder: new RequestResponder(message2.id, (result) => {
20382
+ responder: new RequestResponder(message3.id, (result) => {
20382
20383
  const response = {
20383
20384
  jsonrpc: "2.0",
20384
- id: message2.id,
20385
+ id: message3.id,
20385
20386
  ...result
20386
20387
  };
20387
20388
  return sendResponse ? sendResponse(response) : this.sendWireMessage(response);
@@ -20390,9 +20391,9 @@ var Connection = class {
20390
20391
  }
20391
20392
  return {
20392
20393
  kind: "notification",
20393
- method: message2.method,
20394
- params: message2.params,
20395
- raw: message2
20394
+ method: message3.method,
20395
+ params: message3.params,
20396
+ raw: message3
20396
20397
  };
20397
20398
  }
20398
20399
  handleResponse(response) {
@@ -20405,18 +20406,18 @@ var Connection = class {
20405
20406
  } else if ("result" in response) {
20406
20407
  pendingResponse.resolve(response.result);
20407
20408
  } else {
20408
- const { code, message: message2, data } = response.error;
20409
- pendingResponse.reject(new RequestError(code, message2, data));
20409
+ const { code, message: message3, data } = response.error;
20410
+ pendingResponse.reject(new RequestError(code, message3, data));
20410
20411
  }
20411
20412
  } else {
20412
20413
  console.error("Got response to unknown request", response.id);
20413
20414
  }
20414
20415
  }
20415
- handleProtocolNotification(message2) {
20416
- if (message2.method !== CANCEL_REQUEST_METHOD) {
20416
+ handleProtocolNotification(message3) {
20417
+ if (message3.method !== CANCEL_REQUEST_METHOD) {
20417
20418
  return;
20418
20419
  }
20419
- const requestId2 = cancelRequestId(message2.params);
20420
+ const requestId2 = cancelRequestId(message3.params);
20420
20421
  if (requestId2 === void 0) {
20421
20422
  return;
20422
20423
  }
@@ -20429,7 +20430,7 @@ var Connection = class {
20429
20430
  closedReason() {
20430
20431
  return this.abortController.signal.reason ?? new Error("ACP connection closed");
20431
20432
  }
20432
- async sendWireMessage(message2) {
20433
+ async sendWireMessage(message3) {
20433
20434
  if (this.abortController.signal.aborted) {
20434
20435
  return rejectedPromise(this.closedReason());
20435
20436
  }
@@ -20439,7 +20440,7 @@ var Connection = class {
20439
20440
  }
20440
20441
  const writer = this.stream.writable.getWriter();
20441
20442
  try {
20442
- await writer.write(message2);
20443
+ await writer.write(message3);
20443
20444
  } finally {
20444
20445
  writer.releaseLock();
20445
20446
  }
@@ -20475,7 +20476,7 @@ var ConnectionBuilder = class {
20475
20476
  */
20476
20477
  onReceiveMessage(handler) {
20477
20478
  return this.withHandler({
20478
- handleMessage: async (message2, cx) => await handler(message2, cx) ?? Handled.no(message2),
20479
+ handleMessage: async (message3, cx) => await handler(message3, cx) ?? Handled.no(message3),
20479
20480
  describe: () => this.connectionName ?? "onReceiveMessage"
20480
20481
  });
20481
20482
  }
@@ -20484,12 +20485,12 @@ var ConnectionBuilder = class {
20484
20485
  */
20485
20486
  onReceiveRequest(method, parse3, handler) {
20486
20487
  return this.withHandler({
20487
- handleMessage: async (message2, cx) => {
20488
- if (message2.kind !== "request" || message2.method !== method) {
20489
- return Handled.no(message2);
20488
+ handleMessage: async (message3, cx) => {
20489
+ if (message3.kind !== "request" || message3.method !== method) {
20490
+ return Handled.no(message3);
20490
20491
  }
20491
- const request = parse3(message2.params);
20492
- return await handler(request, message2.responder, cx) ?? Handled.yes();
20492
+ const request = parse3(message3.params);
20493
+ return await handler(request, message3.responder, cx) ?? Handled.yes();
20493
20494
  },
20494
20495
  describe: () => `${this.connectionName ?? "request"}:${method}`
20495
20496
  });
@@ -20499,11 +20500,11 @@ var ConnectionBuilder = class {
20499
20500
  */
20500
20501
  onReceiveNotification(method, parse3, handler) {
20501
20502
  return this.withHandler({
20502
- handleMessage: async (message2, cx) => {
20503
- if (message2.kind !== "notification" || message2.method !== method) {
20504
- return Handled.no(message2);
20503
+ handleMessage: async (message3, cx) => {
20504
+ if (message3.kind !== "notification" || message3.method !== method) {
20505
+ return Handled.no(message3);
20505
20506
  }
20506
- const notification = parse3(message2.params);
20507
+ const notification = parse3(message3.params);
20507
20508
  return await handler(notification, cx) ?? Handled.yes();
20508
20509
  },
20509
20510
  describe: () => `${this.connectionName ?? "notification"}:${method}`
@@ -20528,8 +20529,8 @@ var RequestError = class _RequestError extends Error {
20528
20529
  * Additional JSON-RPC error data.
20529
20530
  */
20530
20531
  data;
20531
- constructor(code, message2, data) {
20532
- super(message2);
20532
+ constructor(code, message3, data) {
20533
+ super(message3);
20533
20534
  this.code = code;
20534
20535
  this.name = "RequestError";
20535
20536
  this.data = data;
@@ -20674,9 +20675,9 @@ function ndJsonStream(output, input) {
20674
20675
  const trimmedLine = textDecoder.decode(lineBytes).trim();
20675
20676
  if (trimmedLine) {
20676
20677
  try {
20677
- const message2 = JSON.parse(trimmedLine);
20678
- if (isRecord2(message2) || Array.isArray(message2)) {
20679
- controller.enqueue(message2);
20678
+ const message3 = JSON.parse(trimmedLine);
20679
+ if (isRecord2(message3) || Array.isArray(message3)) {
20680
+ controller.enqueue(message3);
20680
20681
  } else {
20681
20682
  console.warn("Skipping JSON line that is not an object:", trimmedLine);
20682
20683
  }
@@ -20736,8 +20737,8 @@ function ndJsonStream(output, input) {
20736
20737
  }
20737
20738
  });
20738
20739
  const writable = new WritableStream({
20739
- async write(message2) {
20740
- const content = JSON.stringify(message2) + "\n";
20740
+ async write(message3) {
20741
+ const content = JSON.stringify(message3) + "\n";
20741
20742
  const writer = output.getWriter();
20742
20743
  try {
20743
20744
  await writer.write(textEncoder.encode(content));
@@ -21224,11 +21225,11 @@ var ActiveSession = class _ActiveSession {
21224
21225
  async readText() {
21225
21226
  let output = "";
21226
21227
  for (; ; ) {
21227
- const message2 = await this.nextUpdate();
21228
- if (message2.kind === "stop") {
21228
+ const message3 = await this.nextUpdate();
21229
+ if (message3.kind === "stop") {
21229
21230
  return output;
21230
21231
  }
21231
- const { update } = message2;
21232
+ const { update } = message3;
21232
21233
  if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
21233
21234
  output += update.content.text;
21234
21235
  }
@@ -21376,11 +21377,11 @@ function clientNotificationContext(params, agent, signal) {
21376
21377
  }
21377
21378
  var SessionUpdateRouter = class {
21378
21379
  activeSessions = /* @__PURE__ */ new Map();
21379
- handleMessage(message2) {
21380
- if (message2.kind !== "notification" || message2.method !== CLIENT_METHODS.session_update) {
21381
- return Handled.no(message2);
21380
+ handleMessage(message3) {
21381
+ if (message3.kind !== "notification" || message3.method !== CLIENT_METHODS.session_update) {
21382
+ return Handled.no(message3);
21382
21383
  }
21383
- const notification = zSessionNotification.parse(message2.params);
21384
+ const notification = zSessionNotification.parse(message3.params);
21384
21385
  const update = {
21385
21386
  kind: "session_update",
21386
21387
  notification,
@@ -21392,7 +21393,7 @@ var SessionUpdateRouter = class {
21392
21393
  session.enqueue(update);
21393
21394
  }
21394
21395
  }
21395
- return Handled.no(message2);
21396
+ return Handled.no(message3);
21396
21397
  }
21397
21398
  attach(response, updates) {
21398
21399
  const sessions = this.activeSessions.get(response.sessionId) ?? /* @__PURE__ */ new Set();
@@ -21537,7 +21538,7 @@ var ClientApp = class {
21537
21538
  this.builder.name(options.name);
21538
21539
  }
21539
21540
  this.builder.withHandler({
21540
- handleMessage: (message2, cx) => sessionUpdateRouter(cx).handleMessage(message2),
21541
+ handleMessage: (message3, cx) => sessionUpdateRouter(cx).handleMessage(message3),
21541
21542
  describe: () => "client-session-update-router"
21542
21543
  });
21543
21544
  }
@@ -21680,11 +21681,11 @@ function legacyClientApp(implementation) {
21680
21681
  }
21681
21682
  if (implementation.extMethod) {
21682
21683
  app[appBuilder]().withHandler({
21683
- handleMessage: async (message2) => {
21684
- if (message2.kind !== "request" || legacyClientRequestMethods.has(message2.method)) {
21685
- return Handled.no(message2);
21684
+ handleMessage: async (message3) => {
21685
+ if (message3.kind !== "request" || legacyClientRequestMethods.has(message3.method)) {
21686
+ return Handled.no(message3);
21686
21687
  }
21687
- await message2.responder.respond(await implementation.extMethod(message2.method, message2.params));
21688
+ await message3.responder.respond(await implementation.extMethod(message3.method, message3.params));
21688
21689
  return Handled.yes();
21689
21690
  },
21690
21691
  describe: () => "legacy-client-extension-request"
@@ -21692,11 +21693,11 @@ function legacyClientApp(implementation) {
21692
21693
  }
21693
21694
  if (implementation.extNotification) {
21694
21695
  app[appBuilder]().withHandler({
21695
- handleMessage: async (message2) => {
21696
- if (message2.kind !== "notification" || legacyClientNotificationMethods.has(message2.method)) {
21697
- return Handled.no(message2);
21696
+ handleMessage: async (message3) => {
21697
+ if (message3.kind !== "notification" || legacyClientNotificationMethods.has(message3.method)) {
21698
+ return Handled.no(message3);
21698
21699
  }
21699
- await implementation.extNotification(message2.method, message2.params);
21700
+ await implementation.extNotification(message3.method, message3.params);
21700
21701
  return Handled.yes();
21701
21702
  },
21702
21703
  describe: () => "legacy-client-extension-notification"
@@ -22751,9 +22752,9 @@ function extractString(record4, keys) {
22751
22752
  }
22752
22753
  for (const wrapper of ["input", "arguments", "params", "parameters"]) {
22753
22754
  if (isRecord3(record4[wrapper])) {
22754
- const nested = extractString(record4[wrapper], keys);
22755
- if (nested !== void 0)
22756
- return nested;
22755
+ const nested2 = extractString(record4[wrapper], keys);
22756
+ if (nested2 !== void 0)
22757
+ return nested2;
22757
22758
  }
22758
22759
  }
22759
22760
  return void 0;
@@ -23226,6 +23227,7 @@ var AntigravityToolTracker = class {
23226
23227
  };
23227
23228
  function projectReplayedEventsToTurns(params) {
23228
23229
  const turns = [];
23230
+ const usedTurnKeys = new Set(params.knownTurnRefs?.map(({ nativeTurnKey }) => nativeTurnKey));
23229
23231
  let active;
23230
23232
  let userRun = false;
23231
23233
  let textItem;
@@ -23233,15 +23235,23 @@ function projectReplayedEventsToTurns(params) {
23233
23235
  const begin = () => {
23234
23236
  active?.tracker.finishPending({
23235
23237
  status: "cancelled",
23236
- reason: "No terminal tool status in ACP replay"
23238
+ reason: "No terminal tool status in native history"
23237
23239
  });
23238
23240
  const index = turns.length;
23239
23241
  const turnId = hostTurnIdSchema.parse(`turn-${index}`);
23242
+ let nativeTurnKey = params.knownTurnRefs?.[index]?.nativeTurnKey;
23243
+ if (nativeTurnKey === void 0) {
23244
+ let n = index;
23245
+ nativeTurnKey = `turn-${n}`;
23246
+ while (usedTurnKeys.has(nativeTurnKey))
23247
+ nativeTurnKey = `turn-${++n}`;
23248
+ usedTurnKeys.add(nativeTurnKey);
23249
+ }
23240
23250
  const turn = {
23241
23251
  nativeTurnRef: nativeTurnRefSchema.parse({
23242
23252
  harnessId: "antigravity",
23243
23253
  nativeSessionId: params.nativeSessionId,
23244
- nativeTurnKey: params.knownTurnRefs?.[index]?.nativeTurnKey ?? `turn-${index}`,
23254
+ nativeTurnKey,
23245
23255
  formatVersion: 1
23246
23256
  }),
23247
23257
  checkpoint: nativeCheckpointRefSchema.parse({
@@ -23252,7 +23262,7 @@ function projectReplayedEventsToTurns(params) {
23252
23262
  }),
23253
23263
  input: [],
23254
23264
  items: [],
23255
- outcome: { status: "unknown", reason: "ACP replay does not include prompt stop reasons" }
23265
+ outcome: { status: "unknown", reason: "Native history does not include prompt stop reasons" }
23256
23266
  };
23257
23267
  turns.push(turn);
23258
23268
  sequence = 0;
@@ -23312,7 +23322,7 @@ function projectReplayedEventsToTurns(params) {
23312
23322
  }
23313
23323
  active?.tracker.finishPending({
23314
23324
  status: "cancelled",
23315
- reason: "No terminal tool status in ACP replay"
23325
+ reason: "No terminal tool status in native history"
23316
23326
  });
23317
23327
  return turns;
23318
23328
  }
@@ -23350,8 +23360,8 @@ var AntigravityTransportError = class extends Error {
23350
23360
  kind;
23351
23361
  diagnostic;
23352
23362
  retryable;
23353
- constructor(kind, message2, options) {
23354
- super(message2, options);
23363
+ constructor(kind, message3, options) {
23364
+ super(message3, options);
23355
23365
  this.kind = kind;
23356
23366
  this.name = "AntigravityTransportError";
23357
23367
  this.diagnostic = options?.diagnostic;
@@ -23375,264 +23385,393 @@ var AntigravityTransportError = class extends Error {
23375
23385
  }
23376
23386
  };
23377
23387
 
23378
- // dist/fork.js
23379
- import { randomUUID } from "node:crypto";
23380
- import { access as access2, cp, mkdir, open, rm as rm2 } from "node:fs/promises";
23381
- import os3 from "node:os";
23382
- import path9 from "node:path";
23383
-
23384
- // dist/native-protobuf.js
23385
- function decodeVarint(buffer, start) {
23386
- let value = 0n;
23387
- for (let index = 0; index < 10; index++) {
23388
- const byte = buffer[start + index];
23389
- if (byte === void 0 || index === 9 && byte > 1)
23390
- return null;
23391
- value |= BigInt(byte & 127) << BigInt(index * 7);
23392
- if ((byte & 128) === 0)
23393
- return [value, start + index + 1];
23388
+ // dist/acp-transport.js
23389
+ var AntigravityAcpTransport = class {
23390
+ options;
23391
+ skipPermissions;
23392
+ #child = null;
23393
+ #connection = null;
23394
+ #initializing = null;
23395
+ #sessionId = null;
23396
+ #sessionHandler = null;
23397
+ #active = null;
23398
+ #callbacks = /* @__PURE__ */ new Set();
23399
+ #acceptCallbacks = false;
23400
+ #promptInterrupted = null;
23401
+ #opening = null;
23402
+ #pendingEvents = [];
23403
+ #closed = false;
23404
+ #closing = null;
23405
+ #stderrRaw = "";
23406
+ get #stderr() {
23407
+ return sanitizeDiagnosticTail(this.#stderrRaw);
23394
23408
  }
23395
- return null;
23396
- }
23397
- function readProtoFields(blob) {
23398
- const fields = [];
23399
- let offset = 0;
23400
- while (offset < blob.length) {
23401
- if (fields.length >= 1e4)
23402
- return null;
23403
- const tag = decodeVarint(blob, offset);
23404
- if (!tag || tag[0] < 8n || tag[0] > 0xffffffffn)
23405
- return null;
23406
- offset = tag[1];
23407
- const number4 = Number(tag[0] >> 3n);
23408
- const wire = Number(tag[0] & 7n);
23409
- if (wire === 0) {
23410
- const value = decodeVarint(blob, offset);
23411
- if (!value)
23412
- return null;
23413
- fields.push({ number: number4, wire, value: value[0] });
23414
- offset = value[1];
23415
- } else if (wire === 1 || wire === 5) {
23416
- const length = wire === 1 ? 8 : 4;
23417
- if (offset + length > blob.length)
23418
- return null;
23419
- fields.push({ number: number4, wire, value: blob.subarray(offset, offset + length) });
23420
- offset += length;
23421
- } else if (wire === 2) {
23422
- const length = decodeVarint(blob, offset);
23423
- if (!length || length[0] > BigInt(blob.length - length[1]))
23424
- return null;
23425
- offset = length[1];
23426
- const end = offset + Number(length[0]);
23427
- fields.push({ number: number4, wire, value: blob.subarray(offset, end) });
23428
- offset = end;
23429
- } else
23430
- return null;
23409
+ #faultSignal = new AbortController();
23410
+ constructor(options) {
23411
+ this.options = options;
23412
+ this.skipPermissions = options.skipPermissions === true;
23431
23413
  }
23432
- return fields;
23433
- }
23434
-
23435
- // dist/native-trajectory-metadata.js
23436
- var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
23437
- function encodeVarint(value) {
23438
- const bytes = [];
23439
- let remaining = value >>> 0;
23440
- while (remaining >= 128) {
23441
- bytes.push(remaining & 127 | 128);
23442
- remaining >>>= 7;
23414
+ get sessionId() {
23415
+ return this.#sessionId;
23443
23416
  }
23444
- bytes.push(remaining);
23445
- return Buffer.from(bytes);
23446
- }
23447
- function encodeLengthDelimited(fieldNumber, payload) {
23448
- return Buffer.concat([
23449
- encodeVarint(fieldNumber << 3 | 2),
23450
- encodeVarint(payload.length),
23451
- Buffer.from(payload)
23452
- ]);
23453
- }
23454
- function minimalTrajectoryMetadataBlob(cascadeId, projectId = DEFAULT_CLI_PROJECT_ID) {
23455
- return Buffer.concat([
23456
- encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")),
23457
- encodeLengthDelimited(18, Buffer.from(projectId, "utf8"))
23458
- ]);
23459
- }
23460
- function minimalRawSummaryBlob(trajectoryId, metadataBlob) {
23461
- return Buffer.concat([
23462
- encodeLengthDelimited(4, Buffer.from(trajectoryId, "utf8")),
23463
- Buffer.from([40, 1]),
23464
- encodeLengthDelimited(17, metadataBlob),
23465
- Buffer.from([176, 1, 4])
23466
- ]);
23467
- }
23468
- function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
23469
- const chunks = [];
23470
- let offset = 0;
23471
- let wroteCascadeId = false;
23472
- let hasProjectId = false;
23473
- while (offset < blob.length) {
23474
- const fieldStart = offset;
23475
- const tagParsed = decodeVarint(blob, offset);
23476
- if (!tagParsed)
23477
- return null;
23478
- const [tag, afterTag] = tagParsed;
23479
- if (tag < 8n || tag > 0xffffffffn)
23480
- return null;
23481
- const fieldNumber = Number(tag >> 3n);
23482
- const wireType = Number(tag & 7n);
23483
- if (fieldNumber === 6 && wireType !== 2)
23484
- return null;
23485
- offset = afterTag;
23486
- if (wireType === 0) {
23487
- const valParsed = decodeVarint(blob, offset);
23488
- if (!valParsed)
23489
- return null;
23490
- offset = valParsed[1];
23491
- } else if (wireType === 1) {
23492
- if (offset + 8 > blob.length)
23493
- return null;
23494
- offset += 8;
23495
- } else if (wireType === 2) {
23496
- const lenParsed = decodeVarint(blob, offset);
23497
- if (!lenParsed)
23498
- return null;
23499
- const [length, afterLen] = lenParsed;
23500
- if (length > BigInt(blob.length - afterLen))
23501
- return null;
23502
- offset = afterLen + Number(length);
23503
- if (fieldNumber === 6) {
23504
- if (!wroteCascadeId) {
23505
- chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23506
- wroteCascadeId = true;
23507
- }
23508
- continue;
23509
- }
23510
- if (fieldNumber === 18)
23511
- hasProjectId = true;
23512
- } else if (wireType === 5) {
23513
- if (offset + 4 > blob.length)
23514
- return null;
23515
- offset += 4;
23516
- } else {
23517
- return null;
23518
- }
23519
- chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
23417
+ get isClosed() {
23418
+ return this.#closed;
23520
23419
  }
23521
- if (!wroteCascadeId) {
23522
- chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23420
+ setSessionEventHandler(handler) {
23421
+ this.#sessionHandler = handler;
23422
+ if (handler)
23423
+ for (const event of this.#pendingEvents.splice(0))
23424
+ handler(event);
23523
23425
  }
23524
- if (!hasProjectId) {
23525
- chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
23426
+ initialize() {
23427
+ if (this.#closed)
23428
+ return Promise.reject(new AntigravityTransportError("unavailable", "Antigravity ACP is closed"));
23429
+ return this.#initializing ??= this.#start();
23526
23430
  }
23527
- return Buffer.concat(chunks);
23528
- }
23529
-
23530
- // dist/native-turn-boundaries.js
23531
- import { access } from "node:fs/promises";
23532
- async function readNativeTurnCount(dbPath) {
23533
- await access(dbPath);
23534
- const { DatabaseSync } = await import("node:sqlite");
23535
- const db = new DatabaseSync(dbPath, { readOnly: true });
23536
- try {
23537
- const row = db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get();
23538
- return Number(row?.n ?? 0);
23539
- } finally {
23540
- db.close();
23431
+ async #start() {
23432
+ try {
23433
+ const executable = resolveAntigravityExecutable(this.options);
23434
+ if (!executable)
23435
+ throw new AntigravityTransportError("notInstalled", "Antigravity CLI was not found");
23436
+ const invocation = commandInvocation(executable, this.skipPermissions ? ["acp", "--dangerously-skip-permissions"] : ["acp"], this.options.environment ?? process.env);
23437
+ const child = spawn(invocation.command, invocation.arguments, {
23438
+ cwd: this.options.cwd,
23439
+ env: this.options.environment ?? process.env,
23440
+ stdio: ["pipe", "pipe", "pipe"],
23441
+ windowsHide: true,
23442
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
23443
+ });
23444
+ this.#child = child;
23445
+ child.stderr.on("data", (chunk) => {
23446
+ this.#stderrRaw = (this.#stderrRaw + chunk.toString()).slice(-32e3);
23447
+ });
23448
+ child.on("error", (error51) => this.#fault(new AntigravityTransportError(error51.code === "ENOENT" ? "notInstalled" : "unavailable", error51.message, { diagnostic: this.#stderr })));
23449
+ child.on("exit", (code, signal) => this.#fault(new AntigravityTransportError("processExited", `Antigravity ACP exited (code ${code}, signal ${signal})`, { diagnostic: this.#stderr })));
23450
+ child.stdin.on("error", (error51) => this.#fault(this.#error(error51)));
23451
+ const stream = ndJsonStream2(
23452
+ Writable.toWeb(child.stdin),
23453
+ // Keep draining ACP stdout even when the consumer is slow.
23454
+ Readable.toWeb(child.stdout, {
23455
+ strategy: { highWaterMark: Infinity }
23456
+ })
23457
+ );
23458
+ const nativeMethods = /* @__PURE__ */ new Set(["session/request_permission", "elicitation/create"]);
23459
+ stream.readable = stream.readable.pipeThrough(new TransformStream({
23460
+ transform: (message3, controller) => {
23461
+ if ("method" in message3 && message3.method === "session/update") {
23462
+ const params = message3.params;
23463
+ this.#update(params.sessionId, params.update);
23464
+ return;
23465
+ }
23466
+ if ("method" in message3 && nativeMethods.has(message3.method))
23467
+ message3.method = `_antigravity/${message3.method}`;
23468
+ controller.enqueue(message3);
23469
+ }
23470
+ }));
23471
+ const onElicitation = (request) => this.#callback("sessionId" in request ? request.sessionId : void 0, (handler) => handler.onElicitation(request), { action: "cancel" });
23472
+ const client2 = {
23473
+ sessionUpdate: ({ sessionId, update }) => this.#update(sessionId, update),
23474
+ requestPermission: (request) => this.#callback(request.sessionId, (handler) => handler.onPermission(request), {
23475
+ outcome: { outcome: "cancelled" }
23476
+ }),
23477
+ unstable_createElicitation: onElicitation,
23478
+ extMethod: async (method, params) => {
23479
+ if (method === "_antigravity/session/request_permission")
23480
+ return await client2.requestPermission(params);
23481
+ if (method === "_antigravity/elicitation/create")
23482
+ return await onElicitation(params);
23483
+ throw new AntigravityTransportError("unsupported", `Unsupported ACP client method: ${method}`);
23484
+ }
23485
+ };
23486
+ const connection = new ClientSideConnection(() => client2, stream);
23487
+ this.#connection = connection;
23488
+ connection.signal.addEventListener("abort", () => this.#fault(new AntigravityTransportError("processExited", "Antigravity ACP connection closed", {
23489
+ diagnostic: this.#stderr
23490
+ })), { once: true });
23491
+ const response = await this.#request(connection.initialize({
23492
+ protocolVersion: 1,
23493
+ clientCapabilities: { elicitation: { form: {} } }
23494
+ }), "initialize");
23495
+ if (response.protocolVersion !== 1)
23496
+ throw new AntigravityTransportError("protocolError", `Unsupported ACP version ${response.protocolVersion}`);
23497
+ return response;
23498
+ } catch (error51) {
23499
+ await this.close();
23500
+ throw this.#error(error51);
23501
+ }
23541
23502
  }
23542
- }
23543
- function nativeHistoryError(error51) {
23544
- const missing = error51?.code === "ENOENT";
23545
- return {
23546
- code: missing ? "sessionNotFound" : "nativeFailure",
23547
- message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
23548
- retryable: false
23549
- };
23550
- }
23551
-
23552
- // dist/usage-statistics.js
23553
- import { lstat, opendir } from "node:fs/promises";
23554
- import os2 from "node:os";
23555
- import path8 from "node:path";
23556
-
23557
- // ../../harness-adapter/dist/usage-statistics.js
23558
- import { createReadStream } from "node:fs";
23559
- import { createInterface } from "node:readline";
23560
- var HarnessUsageSourceChangedError = class extends Error {
23561
- code = "HARNESS_USAGE_SOURCE_CHANGED";
23562
- /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
23563
- static is(error51) {
23564
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
23503
+ async openSession(input) {
23504
+ await this.initialize();
23505
+ if (this.#closed || !this.#connection || this.#active || this.#opening || this.#sessionId)
23506
+ throw new AntigravityTransportError("unavailable", "Close the current ACP session before opening another");
23507
+ const connection = this.#connection;
23508
+ const buffered = [];
23509
+ this.#opening = buffered;
23510
+ this.#pendingEvents = [];
23511
+ const params = {
23512
+ cwd: input.cwd,
23513
+ mcpServers: [],
23514
+ ...input.additionalDirectories?.length ? { additionalDirectories: input.additionalDirectories } : {},
23515
+ ...input.systemPromptAppend ? { _meta: { antigravity: { systemPrompt: { append: input.systemPromptAppend } } } } : {}
23516
+ };
23517
+ try {
23518
+ let request;
23519
+ if (input.kind === "create")
23520
+ request = connection.newSession(params);
23521
+ else {
23522
+ if (!input.sessionId)
23523
+ throw new AntigravityTransportError("protocolError", "Session ID required for resume");
23524
+ request = connection.resumeSession({ ...params, sessionId: input.sessionId });
23525
+ }
23526
+ const result = await this.#request(request, `session/${input.kind === "create" ? "new" : input.kind}`);
23527
+ const raw = result;
23528
+ const sessionId = raw.sessionId ?? input.sessionId;
23529
+ if (!sessionId)
23530
+ throw new AntigravityTransportError("protocolError", "Antigravity session/new returned no sessionId");
23531
+ this.#sessionId = sessionId;
23532
+ for (const entry of buffered)
23533
+ if (entry.sessionId === sessionId)
23534
+ this.#dispatch(entry.event);
23535
+ return {
23536
+ opened: {
23537
+ sessionId,
23538
+ ...raw.models ? { models: raw.models } : {},
23539
+ ...raw.modes ? { modes: raw.modes } : {},
23540
+ ...raw.configOptions ? { configOptions: raw.configOptions } : {},
23541
+ ...raw._meta?.antigravity?.tier ? { tier: raw._meta.antigravity.tier } : {}
23542
+ }
23543
+ };
23544
+ } finally {
23545
+ this.#opening = null;
23546
+ }
23565
23547
  }
23566
- };
23567
- var MAX_SESSION_ID_LENGTH = 512;
23568
- var MAX_CWD_LENGTH = 4096;
23569
- var MAX_SESSION_TITLE_LENGTH = 200;
23570
- function usageSessionTitle(value) {
23571
- if (typeof value !== "string")
23572
- return void 0;
23573
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
23574
- if (!normalized)
23575
- return void 0;
23576
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
23577
- return normalized;
23578
- let title = "";
23579
- for (const character of normalized) {
23580
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
23581
- break;
23582
- title += character;
23548
+ async setMode(modeId) {
23549
+ const { connection, sessionId } = this.#session();
23550
+ await this.#request(connection.setSessionMode({ sessionId, modeId }), "session/set_mode");
23583
23551
  }
23584
- return `${title.trimEnd()}…`;
23585
- }
23586
- function sessionIdOk(value) {
23587
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
23588
- }
23589
- function cwdOk(value) {
23590
- 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("\\\\"));
23591
- }
23592
- function withUsageSession(entry, session) {
23593
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
23594
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
23595
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
23596
- if (sessionId === void 0 && cwd === void 0)
23597
- return entry;
23598
- return {
23599
- ...entry,
23600
- ...sessionId !== void 0 ? { sessionId } : {},
23601
- ...cwd !== void 0 ? { cwd } : {},
23602
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
23603
- };
23604
- }
23605
- async function* jsonlRecords(file2, marker, signal) {
23606
- const lines = createInterface({
23607
- input: createReadStream(file2, { encoding: "utf8", signal }),
23608
- crlfDelay: Infinity
23609
- });
23610
- for await (const line of lines) {
23611
- if (!line.includes(marker))
23612
- continue;
23613
- let value;
23552
+ async setConfigOption(configId, value) {
23553
+ const { connection, sessionId } = this.#session();
23554
+ const response = await this.#request(connection.setSessionConfigOption({ sessionId, configId, value }), "session/set_config_option");
23555
+ return response.configOptions;
23556
+ }
23557
+ async prompt(parts, handler) {
23558
+ const { connection, sessionId } = this.#session();
23559
+ if (this.#active)
23560
+ throw new AntigravityTransportError("unavailable", "An ACP prompt is already active");
23561
+ this.#active = handler;
23562
+ this.#acceptCallbacks = true;
23563
+ const interrupted = new AbortController();
23564
+ this.#promptInterrupted = interrupted;
23614
23565
  try {
23615
- value = JSON.parse(line);
23616
- } catch {
23617
- continue;
23566
+ return await this.#request(connection.prompt({ sessionId, prompt: [...parts] }), "session/prompt", null, interrupted.signal);
23567
+ } finally {
23568
+ this.#clearCallbacks();
23569
+ this.#acceptCallbacks = false;
23570
+ this.#active = null;
23571
+ this.#promptInterrupted = null;
23618
23572
  }
23619
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
23620
- yield value;
23573
+ }
23574
+ async cancel() {
23575
+ const { connection, sessionId } = this.#session();
23576
+ this.#acceptCallbacks = false;
23577
+ this.#clearCallbacks();
23578
+ await this.#request(connection.cancel({ sessionId }), "session/cancel");
23579
+ }
23580
+ async closeSession() {
23581
+ const sessionId = this.#sessionId;
23582
+ this.#sessionId = null;
23583
+ this.#acceptCallbacks = false;
23584
+ this.#promptInterrupted?.abort(new AntigravityTransportError("unavailable", "ACP session closed"));
23585
+ this.#active = null;
23586
+ this.#pendingEvents = [];
23587
+ this.#clearCallbacks();
23588
+ if (sessionId && this.#connection)
23589
+ await this.#request(this.#connection.closeSession({ sessionId }), "session/close", this.options.closeTimeoutMs ?? 2e3);
23590
+ }
23591
+ close() {
23592
+ if (this.#closing)
23593
+ return this.#closing;
23594
+ this.#closed = true;
23595
+ return this.#closing = this.#shutdown();
23596
+ }
23597
+ async #shutdown() {
23598
+ try {
23599
+ await this.closeSession();
23600
+ } catch (error51) {
23601
+ this.#stderrRaw = `${this.#stderrRaw}
23602
+ ${this.#error(error51).message}`.slice(-32e3);
23603
+ }
23604
+ this.#faultSignal.abort(new AntigravityTransportError("unavailable", "Antigravity ACP closed"));
23605
+ this.#opening = null;
23606
+ this.#sessionHandler = null;
23607
+ const child = this.#child;
23608
+ if (child && child.exitCode === null && child.signalCode === null && child.pid) {
23609
+ const exited = new Promise((resolve) => child.once("exit", () => resolve()));
23610
+ const timeout = this.options.closeTimeoutMs ?? 2e3;
23611
+ const term = setTimeout(() => child.kill("SIGTERM"), Math.max(1, timeout / 2));
23612
+ const kill = setTimeout(() => child.kill("SIGKILL"), Math.max(2, timeout));
23613
+ child.stdin.end();
23614
+ try {
23615
+ await exited;
23616
+ } finally {
23617
+ clearTimeout(term);
23618
+ clearTimeout(kill);
23619
+ }
23620
+ }
23621
+ this.#connection = null;
23622
+ this.#child = null;
23623
+ }
23624
+ #session() {
23625
+ if (this.#closed || !this.#connection || !this.#sessionId)
23626
+ throw new AntigravityTransportError("unavailable", "Antigravity ACP session is unavailable");
23627
+ return { connection: this.#connection, sessionId: this.#sessionId };
23628
+ }
23629
+ #update(sessionId, raw) {
23630
+ if (this.#closed)
23631
+ return;
23632
+ const event = projectAcpSessionUpdate(raw);
23633
+ if (!event)
23634
+ return;
23635
+ if (this.#opening) {
23636
+ this.#opening.push({ sessionId, event });
23637
+ return;
23638
+ }
23639
+ if (sessionId === this.#sessionId)
23640
+ this.#dispatch(event);
23641
+ }
23642
+ #dispatch(event) {
23643
+ if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type)) {
23644
+ if (this.#sessionHandler)
23645
+ this.#sessionHandler(event);
23646
+ else
23647
+ this.#pendingEvents.push(event);
23648
+ } else
23649
+ this.#active?.onEvent(event);
23650
+ }
23651
+ async #callback(sessionId, invoke, cancelled) {
23652
+ const active = this.#active;
23653
+ if (!active || !this.#acceptCallbacks || sessionId !== this.#sessionId || this.#closed)
23654
+ return cancelled;
23655
+ let cancel;
23656
+ const cancellation = new Promise((resolve) => {
23657
+ cancel = () => resolve(cancelled);
23658
+ });
23659
+ this.#callbacks.add(cancel);
23660
+ try {
23661
+ return await Promise.race([invoke(active), cancellation]);
23662
+ } finally {
23663
+ this.#callbacks.delete(cancel);
23664
+ }
23665
+ }
23666
+ #clearCallbacks() {
23667
+ for (const cancel of this.#callbacks)
23668
+ cancel();
23669
+ this.#callbacks.clear();
23670
+ }
23671
+ async #request(promise2, operation, timeoutMs = this.options.commandTimeoutMs ?? 3e4, signal) {
23672
+ let timer;
23673
+ let abort;
23674
+ const signals = [this.#faultSignal.signal, ...signal ? [signal] : []];
23675
+ const interrupted = new Promise((_, reject) => {
23676
+ abort = () => reject(signal?.aborted ? signal.reason : this.#faultSignal.signal.reason);
23677
+ if (signals.some((candidate) => candidate.aborted))
23678
+ abort();
23679
+ else
23680
+ for (const candidate of signals)
23681
+ candidate.addEventListener("abort", abort, { once: true });
23682
+ if (timeoutMs !== null)
23683
+ timer = setTimeout(() => reject(new AntigravityTransportError("unavailable", `${operation} timed out after ${timeoutMs}ms`, { diagnostic: this.#stderr })), timeoutMs);
23684
+ });
23685
+ try {
23686
+ return await Promise.race([promise2, interrupted]);
23687
+ } catch (error51) {
23688
+ const normalized = this.#error(error51);
23689
+ if (normalized.kind === "unavailable" && normalized.message.includes("timed out"))
23690
+ void this.close();
23691
+ throw normalized;
23692
+ } finally {
23693
+ clearTimeout(timer);
23694
+ for (const candidate of signals)
23695
+ candidate.removeEventListener("abort", abort);
23621
23696
  }
23622
23697
  }
23698
+ #error(error51) {
23699
+ if (error51 instanceof AntigravityTransportError)
23700
+ return error51;
23701
+ const message3 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
23702
+ const code = error51?.code;
23703
+ return new AntigravityTransportError(code === -32e3 || /auth|login|sign[ -]?in|unauthenticated/iu.test(message3) ? "authenticationRequired" : "unavailable", message3, { cause: error51, diagnostic: this.#stderr });
23704
+ }
23705
+ #fault(error51) {
23706
+ if (this.#closed || this.#faultSignal.signal.aborted)
23707
+ return;
23708
+ this.#faultSignal.abort(error51);
23709
+ this.#clearCallbacks();
23710
+ void this.close();
23711
+ this.options.onFault?.(error51);
23712
+ }
23713
+ };
23714
+
23715
+ // dist/acp-usage.js
23716
+ import { createReadStream } from "node:fs";
23717
+ import path7 from "node:path";
23718
+ import { createInterface } from "node:readline";
23719
+
23720
+ // dist/native-request-timing.js
23721
+ import path6 from "node:path";
23722
+
23723
+ // dist/native-protobuf.js
23724
+ function decodeVarint(buffer, start) {
23725
+ let value = 0n;
23726
+ for (let index = 0; index < 10; index++) {
23727
+ const byte = buffer[start + index];
23728
+ if (byte === void 0 || index === 9 && byte > 1)
23729
+ return null;
23730
+ value |= BigInt(byte & 127) << BigInt(index * 7);
23731
+ if ((byte & 128) === 0)
23732
+ return [value, start + index + 1];
23733
+ }
23734
+ return null;
23735
+ }
23736
+ function readProtoFields(blob) {
23737
+ const fields = [];
23738
+ let offset = 0;
23739
+ while (offset < blob.length) {
23740
+ if (fields.length >= 1e4)
23741
+ return null;
23742
+ const tag = decodeVarint(blob, offset);
23743
+ if (!tag || tag[0] < 8n || tag[0] > 0xffffffffn)
23744
+ return null;
23745
+ offset = tag[1];
23746
+ const number4 = Number(tag[0] >> 3n);
23747
+ const wire = Number(tag[0] & 7n);
23748
+ if (wire === 0) {
23749
+ const value = decodeVarint(blob, offset);
23750
+ if (!value)
23751
+ return null;
23752
+ fields.push({ number: number4, wire, value: value[0] });
23753
+ offset = value[1];
23754
+ } else if (wire === 1 || wire === 5) {
23755
+ const length = wire === 1 ? 8 : 4;
23756
+ if (offset + length > blob.length)
23757
+ return null;
23758
+ fields.push({ number: number4, wire, value: blob.subarray(offset, offset + length) });
23759
+ offset += length;
23760
+ } else if (wire === 2) {
23761
+ const length = decodeVarint(blob, offset);
23762
+ if (!length || length[0] > BigInt(blob.length - length[1]))
23763
+ return null;
23764
+ offset = length[1];
23765
+ const end = offset + Number(length[0]);
23766
+ fields.push({ number: number4, wire, value: blob.subarray(offset, end) });
23767
+ offset = end;
23768
+ } else
23769
+ return null;
23770
+ }
23771
+ return fields;
23623
23772
  }
23624
- function nativeTimeMs(value) {
23625
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
23626
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
23627
- }
23628
-
23629
- // dist/acp-usage.js
23630
- import { createReadStream as createReadStream2 } from "node:fs";
23631
- import path7 from "node:path";
23632
- import { createInterface as createInterface2 } from "node:readline";
23633
23773
 
23634
23774
  // dist/native-request-timing.js
23635
- import path6 from "node:path";
23636
23775
  var MAX_METADATA_BYTES = 8 * 1024 * 1024;
23637
23776
  var NANOSECONDS_PER_MS = 1000000n;
23638
23777
  var MAX_MS = BigInt(Number.MAX_SAFE_INTEGER);
@@ -23889,9 +24028,6 @@ var AntigravitySessionUsageTracker = class {
23889
24028
  this.#home = options.homedir;
23890
24029
  this.#expectedInitialTurns = options.expectedInitialTurns ?? 0;
23891
24030
  this.#file = path7.join(options.homedir, ".gemini", "antigravity-cli", "brain", options.nativeSessionId, ".system_generated", "logs", "transcript.jsonl");
23892
- if (options.initialContextUsedTokens !== void 0 && options.initialContextWindowTokens !== void 0) {
23893
- this.recordContextWindow(options.initialContextUsedTokens, options.initialContextWindowTokens);
23894
- }
23895
24031
  }
23896
24032
  currentUsage() {
23897
24033
  const recorded = [...this.#requests].sort(([left], [right]) => left - right).map(([, request]) => request);
@@ -24059,8 +24195,8 @@ var AntigravitySessionUsageTracker = class {
24059
24195
  }
24060
24196
  async #read(signal, withTimings = true) {
24061
24197
  signal?.throwIfAborted();
24062
- const stream = createReadStream2(this.#file, { encoding: "utf8", signal });
24063
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
24198
+ const stream = createReadStream(this.#file, { encoding: "utf8", signal });
24199
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
24064
24200
  const result = {
24065
24201
  steps: /* @__PURE__ */ new Map(),
24066
24202
  toolCallSteps: /* @__PURE__ */ new Set(),
@@ -24127,771 +24263,566 @@ var AntigravitySessionUsageTracker = class {
24127
24263
  }
24128
24264
  };
24129
24265
 
24130
- // dist/usage-statistics.js
24131
- function count4(value) {
24132
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
24133
- }
24134
- function antigravityHome(environment) {
24135
- return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
24136
- }
24137
- function transcriptPath(brainRoot, conversationId) {
24138
- return path8.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
24139
- }
24140
- function isMissing(error51) {
24141
- const code = error51?.code;
24142
- return code === "ENOENT" || code === "ENOTDIR";
24143
- }
24144
- async function lstatIfPresent(target2) {
24145
- try {
24146
- return await lstat(target2);
24147
- } catch (error51) {
24148
- if (isMissing(error51))
24149
- return null;
24150
- throw error51;
24151
- }
24152
- }
24153
- async function transcriptFingerprint(file2) {
24154
- const logs = path8.dirname(file2);
24155
- for (const directory of [path8.dirname(logs), logs]) {
24156
- if (!(await lstatIfPresent(directory))?.isDirectory())
24157
- return null;
24158
- }
24159
- const info = await lstatIfPresent(file2);
24160
- return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
24161
- }
24162
- async function listTranscripts(brainRoot, signal) {
24163
- signal.throwIfAborted();
24164
- const conversations = await opendir(brainRoot).catch((error51) => {
24165
- if (error51.code === "ENOENT")
24166
- return null;
24167
- throw error51;
24168
- });
24169
- if (!conversations)
24170
- return [];
24171
- const sources = [];
24172
- for await (const entry of conversations) {
24173
- signal.throwIfAborted();
24174
- if (!entry.isDirectory())
24175
- continue;
24176
- const file2 = transcriptPath(brainRoot, entry.name);
24177
- const fingerprint = await transcriptFingerprint(file2);
24178
- if (fingerprint)
24179
- sources.push({ id: file2, fingerprint });
24180
- }
24181
- return sources;
24182
- }
24183
- async function readAntigravityUsage(file2, signal) {
24184
- const sessionId = path8.basename(path8.resolve(file2, "..", "..", ".."));
24185
- const requests = /* @__PURE__ */ new Map();
24186
- for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
24187
- if (record4.type !== "PLANNER_RESPONSE")
24188
- continue;
24189
- const step = count4(record4.step_index);
24190
- const input = count4(record4.input_tokens);
24191
- const output = count4(record4.output_tokens);
24192
- const cached2 = count4(record4.cache_read_tokens);
24193
- const at = nativeTimeMs(record4.created_at);
24194
- if (step === null || input === null || output === null || at === null)
24195
- continue;
24196
- const identity2 = normalizeAntigravityUsageModel(record4.model);
24197
- requests.set(step, withUsageSession({
24198
- id: `${String(record4.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
24199
- occurredAtMs: at,
24200
- ...identity2,
24201
- inputTokens: input + (cached2 ?? 0),
24202
- ...cached2 !== null ? {
24203
- cachedInputTokens: cached2,
24204
- ...hasImplicitZeroCacheWrite(identity2) ? { cacheWriteInputTokens: 0 } : {}
24205
- } : {},
24206
- outputTokens: output
24207
- }, { sessionId }));
24208
- }
24209
- return [...requests.values()];
24210
- }
24211
- function createAntigravityUsageStatistics(environment) {
24212
- const brainRoot = nativeBrainRoot(antigravityHome(environment));
24213
- let listed = /* @__PURE__ */ new Map();
24214
- return Object.freeze({
24215
- async listSources(signal) {
24216
- const sources = await listTranscripts(brainRoot, signal);
24217
- listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
24218
- return sources;
24219
- },
24220
- async readSource(id, signal) {
24221
- const expected = listed.get(id);
24222
- let entries;
24223
- try {
24224
- entries = await readAntigravityUsage(id, signal);
24225
- } catch (error51) {
24226
- if (expected !== void 0 && isMissing(error51)) {
24227
- throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
24228
- }
24229
- throw error51;
24230
- }
24231
- if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
24232
- throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
24233
- }
24234
- return entries;
24235
- }
24236
- });
24266
+ // dist/delegation.js
24267
+ var DELEGATION_ENVIRONMENT_KEYS = [
24268
+ "CODEXHOST_CLI_PATH",
24269
+ "CODEXHOST_RUNTIME_ENDPOINT",
24270
+ "CODEXHOST_RUNTIME_TOKEN",
24271
+ "CODEXHOST_THREAD_ID"
24272
+ ];
24273
+ var ANTIGRAVITY_DELEGATION_INSTRUCTIONS = `This Antigravity Session runs inside codexhost.
24274
+ When the user requests cross-Harness delegation, use the executable specified by the CODEXHOST_CLI_PATH environment variable through your native shell tool. Start with --help and harness list, then use delegate start and thread send/read/wait/cancel as documented. Use --format compact for results. Keep the inherited CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID environment variables for every call; they identify this Runtime and parent Thread. Never print their values, substitute another executable, or delegate without user authorization. Native Antigravity subagents are separate from cross-Harness delegation.`;
24275
+ function antigravityDelegationInstructions(environment) {
24276
+ return DELEGATION_ENVIRONMENT_KEYS.every((key) => environment[key]) ? ANTIGRAVITY_DELEGATION_INSTRUCTIONS : void 0;
24237
24277
  }
24238
24278
 
24239
24279
  // dist/fork.js
24240
- function nativeConversationDbPath(id, home = os3.homedir()) {
24241
- return path9.join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
24242
- }
24243
- function nativeConversationSummariesDbPath(home = os3.homedir()) {
24244
- return path9.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
24280
+ import { randomUUID } from "node:crypto";
24281
+ import { access as access2, cp, mkdir, open, rm as rm2 } from "node:fs/promises";
24282
+ import os3 from "node:os";
24283
+ import path9 from "node:path";
24284
+
24285
+ // dist/native-trajectory-metadata.js
24286
+ var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
24287
+ function encodeVarint(value) {
24288
+ const bytes = [];
24289
+ let remaining = value >>> 0;
24290
+ while (remaining >= 128) {
24291
+ bytes.push(remaining & 127 | 128);
24292
+ remaining >>>= 7;
24293
+ }
24294
+ bytes.push(remaining);
24295
+ return Buffer.from(bytes);
24245
24296
  }
24246
- function nativeBrainRoot(home = os3.homedir()) {
24247
- return path9.join(home, ".gemini", "antigravity-cli", "brain");
24297
+ function encodeLengthDelimited(fieldNumber, payload) {
24298
+ return Buffer.concat([
24299
+ encodeVarint(fieldNumber << 3 | 2),
24300
+ encodeVarint(payload.length),
24301
+ Buffer.from(payload)
24302
+ ]);
24248
24303
  }
24249
- function nativeBrainDirPath(id, home = os3.homedir()) {
24250
- return path9.join(nativeBrainRoot(home), id);
24304
+ function minimalTrajectoryMetadataBlob(cascadeId, projectId = DEFAULT_CLI_PROJECT_ID) {
24305
+ return Buffer.concat([
24306
+ encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")),
24307
+ encodeLengthDelimited(18, Buffer.from(projectId, "utf8"))
24308
+ ]);
24251
24309
  }
24252
- function validNativeSessionRef(ref, harnessId2) {
24253
- return nativeSessionRefSchema.safeParse(ref).success && ref.harnessId === harnessId2 && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(ref.nativeSessionId);
24310
+ function minimalRawSummaryBlob(trajectoryId, metadataBlob) {
24311
+ return Buffer.concat([
24312
+ encodeLengthDelimited(4, Buffer.from(trajectoryId, "utf8")),
24313
+ Buffer.from([40, 1]),
24314
+ encodeLengthDelimited(17, metadataBlob),
24315
+ Buffer.from([176, 1, 4])
24316
+ ]);
24254
24317
  }
24255
- async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os3.homedir()) {
24256
- if (![sourceId, derivedId].every((id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id)))
24257
- throw new Error("Invalid native conversation ID");
24258
- const home = typeof retainedTurnsCountOrHome === "string" ? retainedTurnsCountOrHome : homeOption;
24259
- const retained = typeof retainedTurnsCountOrHome === "number" ? retainedTurnsCountOrHome : void 0;
24260
- const sourcePath = nativeConversationDbPath(sourceId, home);
24261
- const targetPath2 = nativeConversationDbPath(derivedId, home);
24262
- await access2(sourcePath);
24263
- const { DatabaseSync, backup } = await import("node:sqlite");
24264
- const source = new DatabaseSync(sourcePath, { readOnly: true });
24265
- let owned = false;
24266
- try {
24267
- source.exec("BEGIN");
24268
- const count5 = Number(source.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
24269
- if (retained !== void 0 && (!Number.isSafeInteger(retained) || retained < 0 || retained > count5))
24270
- throw new Error("Invalid retained native Turn count");
24271
- await mkdir(path9.dirname(targetPath2), { recursive: true });
24272
- const reservation = await open(targetPath2, "wx");
24273
- owned = true;
24274
- await reservation.close();
24275
- await backup(source, targetPath2);
24276
- const target2 = new DatabaseSync(targetPath2);
24277
- try {
24278
- target2.exec("BEGIN IMMEDIATE");
24279
- target2.prepare("UPDATE trajectory_meta SET cascade_id = ?").run(derivedId);
24280
- const row = target2.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get();
24281
- const blob = row?.data instanceof Uint8Array ? rewriteTrajectoryMetadataCascadeId(row.data, derivedId) : minimalTrajectoryMetadataBlob(derivedId);
24282
- if (!blob)
24283
- throw new Error("Invalid native trajectory metadata");
24284
- target2.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(blob);
24285
- if (retained !== void 0 && retained < count5) {
24286
- const boundary = target2.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
24287
- const cutoff = retained === 0 ? 0 : Number(boundary?.idx);
24288
- target2.prepare("DELETE FROM steps WHERE idx >= ?").run(cutoff);
24289
- for (const table of [
24290
- "gen_metadata",
24291
- "executor_metadata",
24292
- "parent_references",
24293
- "battle_mode_infos"
24294
- ]) {
24295
- if (target2.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table))
24296
- target2.prepare(`DELETE FROM ${table} WHERE idx >= ?`).run(cutoff);
24318
+ function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
24319
+ const chunks = [];
24320
+ let offset = 0;
24321
+ let wroteCascadeId = false;
24322
+ let hasProjectId = false;
24323
+ while (offset < blob.length) {
24324
+ const fieldStart = offset;
24325
+ const tagParsed = decodeVarint(blob, offset);
24326
+ if (!tagParsed)
24327
+ return null;
24328
+ const [tag, afterTag] = tagParsed;
24329
+ if (tag < 8n || tag > 0xffffffffn)
24330
+ return null;
24331
+ const fieldNumber = Number(tag >> 3n);
24332
+ const wireType = Number(tag & 7n);
24333
+ if (fieldNumber === 6 && wireType !== 2)
24334
+ return null;
24335
+ offset = afterTag;
24336
+ if (wireType === 0) {
24337
+ const valParsed = decodeVarint(blob, offset);
24338
+ if (!valParsed)
24339
+ return null;
24340
+ offset = valParsed[1];
24341
+ } else if (wireType === 1) {
24342
+ if (offset + 8 > blob.length)
24343
+ return null;
24344
+ offset += 8;
24345
+ } else if (wireType === 2) {
24346
+ const lenParsed = decodeVarint(blob, offset);
24347
+ if (!lenParsed)
24348
+ return null;
24349
+ const [length, afterLen] = lenParsed;
24350
+ if (length > BigInt(blob.length - afterLen))
24351
+ return null;
24352
+ offset = afterLen + Number(length);
24353
+ if (fieldNumber === 6) {
24354
+ if (!wroteCascadeId) {
24355
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
24356
+ wroteCascadeId = true;
24297
24357
  }
24358
+ continue;
24298
24359
  }
24299
- target2.exec("COMMIT");
24300
- } finally {
24301
- target2.close();
24360
+ if (fieldNumber === 18)
24361
+ hasProjectId = true;
24362
+ } else if (wireType === 5) {
24363
+ if (offset + 4 > blob.length)
24364
+ return null;
24365
+ offset += 4;
24366
+ } else {
24367
+ return null;
24302
24368
  }
24303
- await registerDerivedSummary(sourceId, derivedId, home);
24304
- return true;
24305
- } catch (error51) {
24306
- if (owned)
24307
- await removeDerivedDb(derivedId, home);
24308
- throw error51;
24309
- } finally {
24310
- source.close();
24369
+ chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
24311
24370
  }
24312
- }
24313
- async function registerDerivedSummary(sourceId, derivedId, home) {
24314
- const summaryPath = nativeConversationSummariesDbPath(home);
24315
- try {
24316
- await access2(summaryPath);
24317
- } catch (error51) {
24318
- if (error51.code === "ENOENT")
24319
- return;
24320
- throw error51;
24371
+ if (!wroteCascadeId) {
24372
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
24321
24373
  }
24322
- const { DatabaseSync } = await import("node:sqlite");
24323
- const summaries = new DatabaseSync(summaryPath);
24324
- try {
24325
- const template = summaries.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?").get(sourceId);
24326
- if (!template)
24327
- return;
24328
- const derived = new DatabaseSync(nativeConversationDbPath(derivedId, home), { readOnly: true });
24329
- let row;
24330
- try {
24331
- const metadata = derived.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get()?.data;
24332
- const trajectoryId = derived.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get()?.trajectory_id;
24333
- row = {
24334
- ...template,
24335
- conversation_id: derivedId,
24336
- status: "CASCADE_RUN_STATUS_IDLE",
24337
- step_count: Number(derived.prepare("SELECT count(*) AS n FROM steps").get()?.n),
24338
- last_user_input_step_index: Number(derived.prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = 14").get()?.idx ?? -1),
24339
- not_fully_idle: 0,
24340
- killed: 0,
24341
- last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
24342
- raw_summary: minimalRawSummaryBlob(String(trajectoryId), Buffer.from(metadata))
24343
- };
24344
- } finally {
24345
- derived.close();
24346
- }
24347
- const columns = Object.keys(template);
24348
- summaries.prepare(`INSERT INTO conversation_summaries (${columns.map((name) => `"${name.replaceAll('"', '""')}"`).join(",")}) VALUES (${columns.map(() => "?").join(",")})`).run(...columns.map((name) => row[name] ?? null));
24349
- } finally {
24350
- summaries.close();
24374
+ if (!hasProjectId) {
24375
+ chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
24351
24376
  }
24377
+ return Buffer.concat(chunks);
24352
24378
  }
24353
- async function removeDerivedSummary(id, home) {
24354
- try {
24355
- await access2(nativeConversationSummariesDbPath(home));
24356
- } catch (error51) {
24357
- if (error51.code === "ENOENT")
24358
- return;
24359
- throw error51;
24360
- }
24379
+
24380
+ // dist/native-turn-boundaries.js
24381
+ import { access } from "node:fs/promises";
24382
+ async function readNativeTurnCount(dbPath) {
24383
+ await access(dbPath);
24361
24384
  const { DatabaseSync } = await import("node:sqlite");
24362
- const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
24385
+ const db = new DatabaseSync(dbPath, { readOnly: true });
24363
24386
  try {
24364
- db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
24387
+ const row = db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get();
24388
+ return Number(row?.n ?? 0);
24365
24389
  } finally {
24366
24390
  db.close();
24367
24391
  }
24368
24392
  }
24369
- async function removeDerivedDb(id, home) {
24370
- const file2 = nativeConversationDbPath(id, home);
24371
- await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
24372
- }
24373
- async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedir()) {
24374
- try {
24375
- await access2(nativeBrainDirPath(sourceId, home));
24376
- } catch (error51) {
24377
- if (error51.code === "ENOENT")
24378
- return false;
24379
- throw error51;
24380
- }
24381
- await cp(nativeBrainDirPath(sourceId, home), nativeBrainDirPath(derivedId, home), {
24382
- recursive: true,
24383
- errorOnExist: true,
24384
- force: false,
24385
- filter: (source) => path9.basename(source) !== ".system_generated"
24386
- });
24387
- return true;
24388
- }
24389
- async function openDerivedAntigravitySession(options, input, sourceRef, retained) {
24390
- const environment = { ...options.adapterEnvironment, ...input.environment };
24391
- const home = antigravityHome(environment);
24392
- const derivedId = randomUUID();
24393
- let cloned = false;
24394
- try {
24395
- await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home);
24396
- cloned = true;
24397
- await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
24398
- const result = await options.openSession({
24399
- ...input,
24400
- environment,
24401
- nativeRef: { ...sourceRef, nativeSessionId: derivedId }
24402
- });
24403
- if (result.ok)
24404
- return result;
24405
- const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24406
- return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
24407
- } catch (error51) {
24408
- const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24409
- return {
24410
- ok: false,
24411
- error: {
24412
- ...nativeHistoryError(error51),
24413
- ...cleanupFailure ? { diagnostic: cleanupFailure } : {}
24414
- }
24415
- };
24416
- }
24417
- async function cleanup() {
24418
- if (!cloned)
24419
- return;
24420
- await Promise.all([
24421
- removeDerivedDb(derivedId, home),
24422
- rm2(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
24423
- removeDerivedSummary(derivedId, home)
24424
- ]);
24425
- }
24426
- }
24427
- async function forkAntigravitySession(options) {
24428
- const { input, harnessId: harnessId2 } = options;
24429
- if (!validNativeSessionRef(input.sourceRef, harnessId2))
24430
- return {
24431
- ok: false,
24432
- error: {
24433
- code: "invalidRequest",
24434
- message: "Invalid Antigravity source Native Session",
24435
- retryable: false
24436
- }
24437
- };
24438
- const checkpoint = nativeCheckpointRefSchema.safeParse(input.checkpoint);
24439
- if (!checkpoint.success || checkpoint.data.harnessId !== harnessId2 || checkpoint.data.nativeSessionId !== input.sourceRef.nativeSessionId)
24440
- return checkpointError();
24441
- if (options.sourceSession?.isActive)
24442
- return {
24443
- ok: false,
24444
- error: {
24445
- code: "sessionBusy",
24446
- message: "Source Session is busy",
24447
- retryable: true
24448
- }
24449
- };
24450
- const match = /^turn-(0|[1-9]\d*)$/u.exec(checkpoint.data.checkpointId);
24451
- if (!match)
24452
- return checkpointError();
24453
- try {
24454
- const count5 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
24455
- const index = Number(match[1]);
24456
- if (!Number.isSafeInteger(index) || index >= count5)
24457
- return checkpointError();
24458
- return openDerivedAntigravitySession(options, {
24459
- kind: "resume",
24460
- nativeRef: input.sourceRef,
24461
- cwd: input.cwd,
24462
- ...input.environment ? { environment: input.environment } : {}
24463
- }, input.sourceRef, index + 1);
24464
- } catch (error51) {
24465
- return { ok: false, error: nativeHistoryError(error51) };
24466
- }
24467
- }
24468
- function checkpointError() {
24393
+ function nativeHistoryError(error51) {
24394
+ const missing = error51?.code === "ENOENT";
24469
24395
  return {
24470
- ok: false,
24471
- error: {
24472
- code: "checkpointNotFound",
24473
- message: "Antigravity native Turn checkpoint not found",
24474
- retryable: false
24475
- }
24396
+ code: missing ? "sessionNotFound" : "nativeFailure",
24397
+ message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
24398
+ retryable: false
24476
24399
  };
24477
24400
  }
24478
24401
 
24479
- // dist/native-replay.js
24480
- async function readNativeReplaySize(sessionId, home) {
24481
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
24482
- throw new AntigravityTransportError("protocolError", "Invalid native Session ID");
24483
- const { DatabaseSync } = await import("node:sqlite");
24484
- const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
24485
- const size = { users: 0, text: 0, thought: 0, tools: 0 };
24486
- try {
24487
- for (const row of db.prepare("SELECT step_type, step_payload FROM steps WHERE step_type IN (14, 15) ORDER BY idx").iterate()) {
24488
- if (row.step_type === 14) {
24489
- size.users++;
24490
- continue;
24491
- }
24492
- const planner = row.step_payload instanceof Uint8Array ? readProtoFields(row.step_payload)?.find((field3) => field3.number === 20)?.value : void 0;
24493
- const fields = planner instanceof Uint8Array ? readProtoFields(planner) : null;
24494
- if (!fields)
24495
- throw new AntigravityTransportError("protocolError", "Cannot verify Antigravity history replay");
24496
- for (const field3 of fields) {
24497
- if (!(field3.value instanceof Uint8Array))
24498
- continue;
24499
- if (field3.number === 1)
24500
- size.text += Buffer.from(field3.value).toString("utf8").length;
24501
- if (field3.number === 3)
24502
- size.thought += Buffer.from(field3.value).toString("utf8").length;
24503
- if (field3.number === 7)
24504
- size.tools++;
24505
- }
24506
- }
24507
- return size;
24508
- } finally {
24509
- db.close();
24402
+ // dist/usage-statistics.js
24403
+ import { lstat, opendir } from "node:fs/promises";
24404
+ import os2 from "node:os";
24405
+ import path8 from "node:path";
24406
+
24407
+ // ../../harness-adapter/dist/usage-statistics.js
24408
+ import { createReadStream as createReadStream2 } from "node:fs";
24409
+ import { createInterface as createInterface2 } from "node:readline";
24410
+ var HarnessUsageSourceChangedError = class extends Error {
24411
+ code = "HARNESS_USAGE_SOURCE_CHANGED";
24412
+ /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
24413
+ static is(error51) {
24414
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
24415
+ }
24416
+ };
24417
+ var MAX_SESSION_ID_LENGTH = 512;
24418
+ var MAX_CWD_LENGTH = 4096;
24419
+ var MAX_SESSION_TITLE_LENGTH = 200;
24420
+ function usageSessionTitle(value) {
24421
+ if (typeof value !== "string")
24422
+ return void 0;
24423
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
24424
+ if (!normalized)
24425
+ return void 0;
24426
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
24427
+ return normalized;
24428
+ let title = "";
24429
+ for (const character of normalized) {
24430
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
24431
+ break;
24432
+ title += character;
24510
24433
  }
24434
+ return `${title.trimEnd()}…`;
24435
+ }
24436
+ function sessionIdOk(value) {
24437
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
24438
+ }
24439
+ function cwdOk(value) {
24440
+ 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("\\\\"));
24511
24441
  }
24512
- function nativeReplayCompletion(expected) {
24513
- const received = {
24514
- users: 0,
24515
- text: 0,
24516
- thought: 0,
24517
- tools: 0,
24518
- usage: false,
24519
- sessionInfo: false
24442
+ function withUsageSession(entry, session) {
24443
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
24444
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
24445
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
24446
+ if (sessionId === void 0 && cwd === void 0)
24447
+ return entry;
24448
+ return {
24449
+ ...entry,
24450
+ ...sessionId !== void 0 ? { sessionId } : {},
24451
+ ...cwd !== void 0 ? { cwd } : {},
24452
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
24520
24453
  };
24521
- let resolve;
24522
- const complete = new Promise((done) => {
24523
- resolve = done;
24454
+ }
24455
+ async function* jsonlRecords(file2, marker, signal) {
24456
+ const lines = createInterface2({
24457
+ input: createReadStream2(file2, { encoding: "utf8", signal }),
24458
+ crlfDelay: Infinity
24524
24459
  });
24525
- const check2 = () => {
24526
- if (received.users === expected.users && received.text === expected.text && received.thought === expected.thought && received.tools === expected.tools && received.usage && received.sessionInfo)
24527
- resolve();
24528
- };
24529
- check2();
24530
- return {
24531
- complete,
24532
- observe(event) {
24533
- if (event.type === "user.text")
24534
- received.users++;
24535
- if (event.type === "agent.text")
24536
- received.text += event.text.length;
24537
- if (event.type === "agent.thought")
24538
- received.thought += event.text.length;
24539
- if (event.type === "tool.call")
24540
- received.tools++;
24541
- if (event.type === "usage.context")
24542
- received.usage = true;
24543
- if (event.type === "session.info")
24544
- received.sessionInfo = true;
24545
- check2();
24460
+ for await (const line of lines) {
24461
+ if (!line.includes(marker))
24462
+ continue;
24463
+ let value;
24464
+ try {
24465
+ value = JSON.parse(line);
24466
+ } catch {
24467
+ continue;
24546
24468
  }
24547
- };
24469
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
24470
+ yield value;
24471
+ }
24472
+ }
24473
+ }
24474
+ function nativeTimeMs(value) {
24475
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
24476
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
24548
24477
  }
24549
24478
 
24550
- // dist/acp-transport.js
24551
- var AntigravityAcpTransport = class {
24552
- options;
24553
- skipPermissions;
24554
- #child = null;
24555
- #connection = null;
24556
- #initializing = null;
24557
- #sessionId = null;
24558
- #sessionHandler = null;
24559
- #active = null;
24560
- #callbacks = /* @__PURE__ */ new Set();
24561
- #acceptCallbacks = false;
24562
- #promptInterrupted = null;
24563
- #opening = null;
24564
- #observeReplay = null;
24565
- #pendingEvents = [];
24566
- #closed = false;
24567
- #closing = null;
24568
- #stderrRaw = "";
24569
- get #stderr() {
24570
- return sanitizeDiagnosticTail(this.#stderrRaw);
24571
- }
24572
- #faultSignal = new AbortController();
24573
- constructor(options) {
24574
- this.options = options;
24575
- this.skipPermissions = options.skipPermissions === true;
24576
- }
24577
- get sessionId() {
24578
- return this.#sessionId;
24479
+ // dist/usage-statistics.js
24480
+ function count4(value) {
24481
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
24482
+ }
24483
+ function antigravityHome(environment) {
24484
+ return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
24485
+ }
24486
+ function transcriptPath(brainRoot, conversationId) {
24487
+ return path8.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
24488
+ }
24489
+ function isMissing(error51) {
24490
+ const code = error51?.code;
24491
+ return code === "ENOENT" || code === "ENOTDIR";
24492
+ }
24493
+ async function lstatIfPresent(target2) {
24494
+ try {
24495
+ return await lstat(target2);
24496
+ } catch (error51) {
24497
+ if (isMissing(error51))
24498
+ return null;
24499
+ throw error51;
24579
24500
  }
24580
- get isClosed() {
24581
- return this.#closed;
24501
+ }
24502
+ async function transcriptFingerprint(file2) {
24503
+ const logs = path8.dirname(file2);
24504
+ for (const directory of [path8.dirname(logs), logs]) {
24505
+ if (!(await lstatIfPresent(directory))?.isDirectory())
24506
+ return null;
24582
24507
  }
24583
- setSessionEventHandler(handler) {
24584
- this.#sessionHandler = handler;
24585
- if (handler)
24586
- for (const event of this.#pendingEvents.splice(0))
24587
- handler(event);
24508
+ const info = await lstatIfPresent(file2);
24509
+ return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
24510
+ }
24511
+ async function listTranscripts(brainRoot, signal) {
24512
+ signal.throwIfAborted();
24513
+ const conversations = await opendir(brainRoot).catch((error51) => {
24514
+ if (error51.code === "ENOENT")
24515
+ return null;
24516
+ throw error51;
24517
+ });
24518
+ if (!conversations)
24519
+ return [];
24520
+ const sources = [];
24521
+ for await (const entry of conversations) {
24522
+ signal.throwIfAborted();
24523
+ if (!entry.isDirectory())
24524
+ continue;
24525
+ const file2 = transcriptPath(brainRoot, entry.name);
24526
+ const fingerprint = await transcriptFingerprint(file2);
24527
+ if (fingerprint)
24528
+ sources.push({ id: file2, fingerprint });
24588
24529
  }
24589
- initialize() {
24590
- if (this.#closed)
24591
- return Promise.reject(new AntigravityTransportError("unavailable", "Antigravity ACP is closed"));
24592
- return this.#initializing ??= this.#start();
24530
+ return sources;
24531
+ }
24532
+ async function readAntigravityUsage(file2, signal) {
24533
+ const sessionId = path8.basename(path8.resolve(file2, "..", "..", ".."));
24534
+ const requests = /* @__PURE__ */ new Map();
24535
+ for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
24536
+ if (record4.type !== "PLANNER_RESPONSE")
24537
+ continue;
24538
+ const step = count4(record4.step_index);
24539
+ const input = count4(record4.input_tokens);
24540
+ const output = count4(record4.output_tokens);
24541
+ const cached2 = count4(record4.cache_read_tokens);
24542
+ const at = nativeTimeMs(record4.created_at);
24543
+ if (step === null || input === null || output === null || at === null)
24544
+ continue;
24545
+ const identity2 = normalizeAntigravityUsageModel(record4.model);
24546
+ requests.set(step, withUsageSession({
24547
+ id: `${String(record4.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
24548
+ occurredAtMs: at,
24549
+ ...identity2,
24550
+ inputTokens: input + (cached2 ?? 0),
24551
+ ...cached2 !== null ? {
24552
+ cachedInputTokens: cached2,
24553
+ ...hasImplicitZeroCacheWrite(identity2) ? { cacheWriteInputTokens: 0 } : {}
24554
+ } : {},
24555
+ outputTokens: output
24556
+ }, { sessionId }));
24593
24557
  }
24594
- async #start() {
24595
- try {
24596
- const executable = resolveAntigravityExecutable(this.options);
24597
- if (!executable)
24598
- throw new AntigravityTransportError("notInstalled", "Antigravity CLI was not found");
24599
- const invocation = commandInvocation(executable, this.skipPermissions ? ["acp", "--dangerously-skip-permissions"] : ["acp"], this.options.environment ?? process.env);
24600
- const child = spawn(invocation.command, invocation.arguments, {
24601
- cwd: this.options.cwd,
24602
- env: this.options.environment ?? process.env,
24603
- stdio: ["pipe", "pipe", "pipe"],
24604
- windowsHide: true,
24605
- windowsVerbatimArguments: invocation.windowsVerbatimArguments
24606
- });
24607
- this.#child = child;
24608
- child.stderr.on("data", (chunk) => {
24609
- this.#stderrRaw = (this.#stderrRaw + chunk.toString()).slice(-32e3);
24610
- });
24611
- child.on("error", (error51) => this.#fault(new AntigravityTransportError(error51.code === "ENOENT" ? "notInstalled" : "unavailable", error51.message, { diagnostic: this.#stderr })));
24612
- child.on("exit", (code, signal) => this.#fault(new AntigravityTransportError("processExited", `Antigravity ACP exited (code ${code}, signal ${signal})`, { diagnostic: this.#stderr })));
24613
- child.stdin.on("error", (error51) => this.#fault(this.#error(error51)));
24614
- const stream = ndJsonStream2(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
24615
- const nativeMethods = /* @__PURE__ */ new Set(["session/request_permission", "elicitation/create"]);
24616
- stream.readable = stream.readable.pipeThrough(new TransformStream({
24617
- transform: (message2, controller) => {
24618
- if ("method" in message2 && message2.method === "session/update") {
24619
- const params = message2.params;
24620
- this.#update(params.sessionId, params.update);
24621
- return;
24622
- }
24623
- if ("method" in message2 && nativeMethods.has(message2.method))
24624
- message2.method = `_antigravity/${message2.method}`;
24625
- controller.enqueue(message2);
24626
- }
24627
- }));
24628
- const onElicitation = (request) => this.#callback("sessionId" in request ? request.sessionId : void 0, (handler) => handler.onElicitation(request), { action: "cancel" });
24629
- const client2 = {
24630
- sessionUpdate: ({ sessionId, update }) => this.#update(sessionId, update),
24631
- requestPermission: (request) => this.#callback(request.sessionId, (handler) => handler.onPermission(request), {
24632
- outcome: { outcome: "cancelled" }
24633
- }),
24634
- unstable_createElicitation: onElicitation,
24635
- extMethod: async (method, params) => {
24636
- if (method === "_antigravity/session/request_permission")
24637
- return await client2.requestPermission(params);
24638
- if (method === "_antigravity/elicitation/create")
24639
- return await onElicitation(params);
24640
- throw new AntigravityTransportError("unsupported", `Unsupported ACP client method: ${method}`);
24558
+ return [...requests.values()];
24559
+ }
24560
+ function createAntigravityUsageStatistics(environment) {
24561
+ const brainRoot = nativeBrainRoot(antigravityHome(environment));
24562
+ let listed = /* @__PURE__ */ new Map();
24563
+ return Object.freeze({
24564
+ async listSources(signal) {
24565
+ const sources = await listTranscripts(brainRoot, signal);
24566
+ listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
24567
+ return sources;
24568
+ },
24569
+ async readSource(id, signal) {
24570
+ const expected = listed.get(id);
24571
+ let entries;
24572
+ try {
24573
+ entries = await readAntigravityUsage(id, signal);
24574
+ } catch (error51) {
24575
+ if (expected !== void 0 && isMissing(error51)) {
24576
+ throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
24641
24577
  }
24642
- };
24643
- const connection = new ClientSideConnection(() => client2, stream);
24644
- this.#connection = connection;
24645
- connection.signal.addEventListener("abort", () => this.#fault(new AntigravityTransportError("processExited", "Antigravity ACP connection closed", {
24646
- diagnostic: this.#stderr
24647
- })), { once: true });
24648
- const response = await this.#request(connection.initialize({
24649
- protocolVersion: 1,
24650
- clientCapabilities: { elicitation: { form: {} } }
24651
- }), "initialize");
24652
- if (response.protocolVersion !== 1)
24653
- throw new AntigravityTransportError("protocolError", `Unsupported ACP version ${response.protocolVersion}`);
24654
- return response;
24655
- } catch (error51) {
24656
- await this.close();
24657
- throw this.#error(error51);
24658
- }
24659
- }
24660
- async openSession(input) {
24661
- await this.initialize();
24662
- if (this.#closed || !this.#connection || this.#active || this.#opening || this.#sessionId)
24663
- throw new AntigravityTransportError("unavailable", "Close the current ACP session before opening another");
24664
- const connection = this.#connection;
24665
- const buffered = [];
24666
- this.#opening = buffered;
24667
- this.#pendingEvents = [];
24668
- const params = {
24669
- cwd: input.cwd,
24670
- mcpServers: [],
24671
- ...input.additionalDirectories?.length ? { additionalDirectories: input.additionalDirectories } : {},
24672
- ...input.systemPromptAppend ? { _meta: { antigravity: { systemPrompt: { append: input.systemPromptAppend } } } } : {}
24673
- };
24674
- try {
24675
- const replay = input.kind === "load" && input.sessionId ? nativeReplayCompletion(await readNativeReplaySize(input.sessionId, antigravityHome(this.options.environment ?? process.env))) : void 0;
24676
- this.#observeReplay = replay ? (sessionId2, event) => {
24677
- if (sessionId2 === input.sessionId)
24678
- replay.observe(event);
24679
- } : null;
24680
- let request;
24681
- if (input.kind === "create")
24682
- request = connection.newSession(params);
24683
- else {
24684
- if (!input.sessionId)
24685
- throw new AntigravityTransportError("protocolError", "Session ID required for resume/load");
24686
- const target2 = { ...params, sessionId: input.sessionId };
24687
- request = input.kind === "resume" ? connection.resumeSession(target2) : connection.loadSession(target2);
24578
+ throw error51;
24579
+ }
24580
+ if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
24581
+ throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
24688
24582
  }
24689
- const result = await this.#request(request, `session/${input.kind === "create" ? "new" : input.kind}`);
24690
- const raw = result;
24691
- const sessionId = raw.sessionId ?? input.sessionId;
24692
- if (!sessionId)
24693
- throw new AntigravityTransportError("protocolError", "Antigravity session/new returned no sessionId");
24694
- this.#sessionId = sessionId;
24695
- if (replay)
24696
- await this.#request(replay.complete, "session/load replay");
24697
- const events = buffered.filter((entry) => entry.sessionId === sessionId).map(({ event }) => event);
24698
- if (input.kind !== "load")
24699
- for (const event of events)
24700
- this.#dispatch(event);
24701
- return {
24702
- opened: {
24703
- sessionId,
24704
- ...raw.models ? { models: raw.models } : {},
24705
- ...raw.modes ? { modes: raw.modes } : {},
24706
- ...raw.configOptions ? { configOptions: raw.configOptions } : {},
24707
- ...raw._meta?.antigravity?.tier ? { tier: raw._meta.antigravity.tier } : {}
24708
- },
24709
- replayedEvents: input.kind === "load" ? events : []
24710
- };
24711
- } finally {
24712
- this.#opening = null;
24713
- this.#observeReplay = null;
24583
+ return entries;
24714
24584
  }
24715
- }
24716
- async setMode(modeId) {
24717
- const { connection, sessionId } = this.#session();
24718
- await this.#request(connection.setSessionMode({ sessionId, modeId }), "session/set_mode");
24719
- }
24720
- async setConfigOption(configId, value) {
24721
- const { connection, sessionId } = this.#session();
24722
- const response = await this.#request(connection.setSessionConfigOption({ sessionId, configId, value }), "session/set_config_option");
24723
- return response.configOptions;
24724
- }
24725
- async prompt(parts, handler) {
24726
- const { connection, sessionId } = this.#session();
24727
- if (this.#active)
24728
- throw new AntigravityTransportError("unavailable", "An ACP prompt is already active");
24729
- this.#active = handler;
24730
- this.#acceptCallbacks = true;
24731
- const interrupted = new AbortController();
24732
- this.#promptInterrupted = interrupted;
24585
+ });
24586
+ }
24587
+
24588
+ // dist/fork.js
24589
+ function nativeConversationDbPath(id, home = os3.homedir()) {
24590
+ return path9.join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
24591
+ }
24592
+ function nativeConversationSummariesDbPath(home = os3.homedir()) {
24593
+ return path9.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
24594
+ }
24595
+ function nativeBrainRoot(home = os3.homedir()) {
24596
+ return path9.join(home, ".gemini", "antigravity-cli", "brain");
24597
+ }
24598
+ function nativeBrainDirPath(id, home = os3.homedir()) {
24599
+ return path9.join(nativeBrainRoot(home), id);
24600
+ }
24601
+ function validNativeSessionRef(ref, harnessId2) {
24602
+ return nativeSessionRefSchema.safeParse(ref).success && ref.harnessId === harnessId2 && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(ref.nativeSessionId);
24603
+ }
24604
+ async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os3.homedir()) {
24605
+ if (![sourceId, derivedId].every((id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id)))
24606
+ throw new Error("Invalid native conversation ID");
24607
+ const home = typeof retainedTurnsCountOrHome === "string" ? retainedTurnsCountOrHome : homeOption;
24608
+ const retained = typeof retainedTurnsCountOrHome === "number" ? retainedTurnsCountOrHome : void 0;
24609
+ const sourcePath = nativeConversationDbPath(sourceId, home);
24610
+ const targetPath2 = nativeConversationDbPath(derivedId, home);
24611
+ await access2(sourcePath);
24612
+ const { DatabaseSync, backup } = await import("node:sqlite");
24613
+ const source = new DatabaseSync(sourcePath, { readOnly: true });
24614
+ let owned = false;
24615
+ try {
24616
+ source.exec("BEGIN");
24617
+ const count5 = Number(source.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
24618
+ if (retained !== void 0 && (!Number.isSafeInteger(retained) || retained < 0 || retained > count5))
24619
+ throw new Error("Invalid retained native Turn count");
24620
+ await mkdir(path9.dirname(targetPath2), { recursive: true });
24621
+ const reservation = await open(targetPath2, "wx");
24622
+ owned = true;
24623
+ await reservation.close();
24624
+ await backup(source, targetPath2);
24625
+ const target2 = new DatabaseSync(targetPath2);
24733
24626
  try {
24734
- return await this.#request(connection.prompt({ sessionId, prompt: [...parts] }), "session/prompt", null, interrupted.signal);
24627
+ target2.exec("BEGIN IMMEDIATE");
24628
+ target2.prepare("UPDATE trajectory_meta SET cascade_id = ?").run(derivedId);
24629
+ const row = target2.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get();
24630
+ const blob = row?.data instanceof Uint8Array ? rewriteTrajectoryMetadataCascadeId(row.data, derivedId) : minimalTrajectoryMetadataBlob(derivedId);
24631
+ if (!blob)
24632
+ throw new Error("Invalid native trajectory metadata");
24633
+ target2.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(blob);
24634
+ if (retained !== void 0 && retained < count5) {
24635
+ const boundary = target2.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
24636
+ const cutoff = retained === 0 ? 0 : Number(boundary?.idx);
24637
+ target2.prepare("DELETE FROM steps WHERE idx >= ?").run(cutoff);
24638
+ for (const table of [
24639
+ "gen_metadata",
24640
+ "executor_metadata",
24641
+ "parent_references",
24642
+ "battle_mode_infos"
24643
+ ]) {
24644
+ if (target2.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table))
24645
+ target2.prepare(`DELETE FROM ${table} WHERE idx >= ?`).run(cutoff);
24646
+ }
24647
+ }
24648
+ target2.exec("COMMIT");
24735
24649
  } finally {
24736
- this.#clearCallbacks();
24737
- this.#acceptCallbacks = false;
24738
- this.#active = null;
24739
- this.#promptInterrupted = null;
24650
+ target2.close();
24740
24651
  }
24652
+ await registerDerivedSummary(sourceId, derivedId, home);
24653
+ return true;
24654
+ } catch (error51) {
24655
+ if (owned)
24656
+ await removeDerivedDb(derivedId, home);
24657
+ throw error51;
24658
+ } finally {
24659
+ source.close();
24741
24660
  }
24742
- async cancel() {
24743
- const { connection, sessionId } = this.#session();
24744
- this.#acceptCallbacks = false;
24745
- this.#clearCallbacks();
24746
- await this.#request(connection.cancel({ sessionId }), "session/cancel");
24747
- }
24748
- async closeSession() {
24749
- const sessionId = this.#sessionId;
24750
- this.#sessionId = null;
24751
- this.#acceptCallbacks = false;
24752
- this.#promptInterrupted?.abort(new AntigravityTransportError("unavailable", "ACP session closed"));
24753
- this.#active = null;
24754
- this.#pendingEvents = [];
24755
- this.#clearCallbacks();
24756
- if (sessionId && this.#connection)
24757
- await this.#request(this.#connection.closeSession({ sessionId }), "session/close", this.options.closeTimeoutMs ?? 2e3);
24758
- }
24759
- close() {
24760
- if (this.#closing)
24761
- return this.#closing;
24762
- this.#closed = true;
24763
- return this.#closing = this.#shutdown();
24661
+ }
24662
+ async function registerDerivedSummary(sourceId, derivedId, home) {
24663
+ const summaryPath = nativeConversationSummariesDbPath(home);
24664
+ try {
24665
+ await access2(summaryPath);
24666
+ } catch (error51) {
24667
+ if (error51.code === "ENOENT")
24668
+ return;
24669
+ throw error51;
24764
24670
  }
24765
- async #shutdown() {
24671
+ const { DatabaseSync } = await import("node:sqlite");
24672
+ const summaries = new DatabaseSync(summaryPath);
24673
+ try {
24674
+ const template = summaries.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?").get(sourceId);
24675
+ if (!template)
24676
+ return;
24677
+ const derived = new DatabaseSync(nativeConversationDbPath(derivedId, home), { readOnly: true });
24678
+ let row;
24766
24679
  try {
24767
- await this.closeSession();
24768
- } catch (error51) {
24769
- this.#stderrRaw = `${this.#stderrRaw}
24770
- ${this.#error(error51).message}`.slice(-32e3);
24771
- }
24772
- this.#faultSignal.abort(new AntigravityTransportError("unavailable", "Antigravity ACP closed"));
24773
- this.#opening = null;
24774
- this.#sessionHandler = null;
24775
- const child = this.#child;
24776
- if (child && child.exitCode === null && child.signalCode === null && child.pid) {
24777
- const exited = new Promise((resolve) => child.once("exit", () => resolve()));
24778
- const timeout = this.options.closeTimeoutMs ?? 2e3;
24779
- const term = setTimeout(() => child.kill("SIGTERM"), Math.max(1, timeout / 2));
24780
- const kill = setTimeout(() => child.kill("SIGKILL"), Math.max(2, timeout));
24781
- child.stdin.end();
24782
- try {
24783
- await exited;
24784
- } finally {
24785
- clearTimeout(term);
24786
- clearTimeout(kill);
24787
- }
24680
+ const metadata = derived.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get()?.data;
24681
+ const trajectoryId = derived.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get()?.trajectory_id;
24682
+ row = {
24683
+ ...template,
24684
+ conversation_id: derivedId,
24685
+ status: "CASCADE_RUN_STATUS_IDLE",
24686
+ step_count: Number(derived.prepare("SELECT count(*) AS n FROM steps").get()?.n),
24687
+ last_user_input_step_index: Number(derived.prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = 14").get()?.idx ?? -1),
24688
+ not_fully_idle: 0,
24689
+ killed: 0,
24690
+ last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
24691
+ raw_summary: minimalRawSummaryBlob(String(trajectoryId), Buffer.from(metadata))
24692
+ };
24693
+ } finally {
24694
+ derived.close();
24788
24695
  }
24789
- this.#connection = null;
24790
- this.#child = null;
24791
- }
24792
- #session() {
24793
- if (this.#closed || !this.#connection || !this.#sessionId)
24794
- throw new AntigravityTransportError("unavailable", "Antigravity ACP session is unavailable");
24795
- return { connection: this.#connection, sessionId: this.#sessionId };
24696
+ const columns = Object.keys(template);
24697
+ summaries.prepare(`INSERT INTO conversation_summaries (${columns.map((name) => `"${name.replaceAll('"', '""')}"`).join(",")}) VALUES (${columns.map(() => "?").join(",")})`).run(...columns.map((name) => row[name] ?? null));
24698
+ } finally {
24699
+ summaries.close();
24796
24700
  }
24797
- #update(sessionId, raw) {
24798
- if (this.#closed)
24799
- return;
24800
- const event = projectAcpSessionUpdate(raw);
24801
- if (!event)
24802
- return;
24803
- if (this.#opening) {
24804
- this.#opening.push({ sessionId, event });
24805
- this.#observeReplay?.(sessionId, event);
24701
+ }
24702
+ async function removeDerivedSummary(id, home) {
24703
+ try {
24704
+ await access2(nativeConversationSummariesDbPath(home));
24705
+ } catch (error51) {
24706
+ if (error51.code === "ENOENT")
24806
24707
  return;
24807
- }
24808
- if (sessionId === this.#sessionId)
24809
- this.#dispatch(event);
24810
- }
24811
- #dispatch(event) {
24812
- if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type)) {
24813
- if (this.#sessionHandler)
24814
- this.#sessionHandler(event);
24815
- else
24816
- this.#pendingEvents.push(event);
24817
- } else
24818
- this.#active?.onEvent(event);
24708
+ throw error51;
24819
24709
  }
24820
- async #callback(sessionId, invoke, cancelled) {
24821
- const active = this.#active;
24822
- if (!active || !this.#acceptCallbacks || sessionId !== this.#sessionId || this.#closed)
24823
- return cancelled;
24824
- let cancel;
24825
- const cancellation = new Promise((resolve) => {
24826
- cancel = () => resolve(cancelled);
24827
- });
24828
- this.#callbacks.add(cancel);
24829
- try {
24830
- return await Promise.race([invoke(active), cancellation]);
24831
- } finally {
24832
- this.#callbacks.delete(cancel);
24833
- }
24710
+ const { DatabaseSync } = await import("node:sqlite");
24711
+ const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
24712
+ try {
24713
+ db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
24714
+ } finally {
24715
+ db.close();
24834
24716
  }
24835
- #clearCallbacks() {
24836
- for (const cancel of this.#callbacks)
24837
- cancel();
24838
- this.#callbacks.clear();
24717
+ }
24718
+ async function removeDerivedDb(id, home) {
24719
+ const file2 = nativeConversationDbPath(id, home);
24720
+ await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
24721
+ }
24722
+ async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedir()) {
24723
+ try {
24724
+ await access2(nativeBrainDirPath(sourceId, home));
24725
+ } catch (error51) {
24726
+ if (error51.code === "ENOENT")
24727
+ return false;
24728
+ throw error51;
24839
24729
  }
24840
- async #request(promise2, operation, timeoutMs = this.options.commandTimeoutMs ?? 3e4, signal) {
24841
- let timer;
24842
- let abort;
24843
- const signals = [this.#faultSignal.signal, ...signal ? [signal] : []];
24844
- const interrupted = new Promise((_, reject) => {
24845
- abort = () => reject(signal?.aborted ? signal.reason : this.#faultSignal.signal.reason);
24846
- if (signals.some((candidate) => candidate.aborted))
24847
- abort();
24848
- else
24849
- for (const candidate of signals)
24850
- candidate.addEventListener("abort", abort, { once: true });
24851
- if (timeoutMs !== null)
24852
- timer = setTimeout(() => reject(new AntigravityTransportError("unavailable", `${operation} timed out after ${timeoutMs}ms`, { diagnostic: this.#stderr })), timeoutMs);
24730
+ await cp(nativeBrainDirPath(sourceId, home), nativeBrainDirPath(derivedId, home), {
24731
+ recursive: true,
24732
+ errorOnExist: true,
24733
+ force: false,
24734
+ filter: (source) => path9.basename(source) !== ".system_generated"
24735
+ });
24736
+ return true;
24737
+ }
24738
+ async function openDerivedAntigravitySession(options, input, sourceRef, retained) {
24739
+ const environment = { ...options.adapterEnvironment, ...input.environment };
24740
+ const home = antigravityHome(environment);
24741
+ const derivedId = randomUUID();
24742
+ let cloned = false;
24743
+ try {
24744
+ await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home);
24745
+ cloned = true;
24746
+ await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
24747
+ const result = await options.openSession({
24748
+ ...input,
24749
+ environment,
24750
+ nativeRef: { ...sourceRef, nativeSessionId: derivedId }
24853
24751
  });
24854
- try {
24855
- return await Promise.race([promise2, interrupted]);
24856
- } catch (error51) {
24857
- const normalized = this.#error(error51);
24858
- if (normalized.kind === "unavailable" && normalized.message.includes("timed out"))
24859
- void this.close();
24860
- throw normalized;
24861
- } finally {
24862
- clearTimeout(timer);
24863
- for (const candidate of signals)
24864
- candidate.removeEventListener("abort", abort);
24865
- }
24866
- }
24867
- #error(error51) {
24868
- if (error51 instanceof AntigravityTransportError)
24869
- return error51;
24870
- const message2 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
24871
- const code = error51?.code;
24872
- return new AntigravityTransportError(code === -32e3 || /auth|login|sign[ -]?in|unauthenticated/iu.test(message2) ? "authenticationRequired" : "unavailable", message2, { cause: error51, diagnostic: this.#stderr });
24752
+ if (result.ok)
24753
+ return result;
24754
+ const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24755
+ return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
24756
+ } catch (error51) {
24757
+ const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24758
+ return {
24759
+ ok: false,
24760
+ error: {
24761
+ ...nativeHistoryError(error51),
24762
+ ...cleanupFailure ? { diagnostic: cleanupFailure } : {}
24763
+ }
24764
+ };
24873
24765
  }
24874
- #fault(error51) {
24875
- if (this.#closed || this.#faultSignal.signal.aborted)
24766
+ async function cleanup() {
24767
+ if (!cloned)
24876
24768
  return;
24877
- this.#faultSignal.abort(error51);
24878
- this.#clearCallbacks();
24879
- void this.close();
24880
- this.options.onFault?.(error51);
24769
+ await Promise.all([
24770
+ removeDerivedDb(derivedId, home),
24771
+ rm2(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
24772
+ removeDerivedSummary(derivedId, home)
24773
+ ]);
24881
24774
  }
24882
- };
24883
-
24884
- // dist/delegation.js
24885
- var DELEGATION_ENVIRONMENT_KEYS = [
24886
- "CODEXHOST_CLI_PATH",
24887
- "CODEXHOST_RUNTIME_ENDPOINT",
24888
- "CODEXHOST_RUNTIME_TOKEN",
24889
- "CODEXHOST_THREAD_ID"
24890
- ];
24891
- var ANTIGRAVITY_DELEGATION_INSTRUCTIONS = `This Antigravity Session runs inside codexhost.
24892
- When the user requests cross-Harness delegation, use the executable specified by the CODEXHOST_CLI_PATH environment variable through your native shell tool. Start with --help and harness list, then use delegate start and thread send/read/wait/cancel as documented. Use --format compact for results. Keep the inherited CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID environment variables for every call; they identify this Runtime and parent Thread. Never print their values, substitute another executable, or delegate without user authorization. Native Antigravity subagents are separate from cross-Harness delegation.`;
24893
- function antigravityDelegationInstructions(environment) {
24894
- return DELEGATION_ENVIRONMENT_KEYS.every((key) => environment[key]) ? ANTIGRAVITY_DELEGATION_INSTRUCTIONS : void 0;
24775
+ }
24776
+ async function forkAntigravitySession(options) {
24777
+ const { input, harnessId: harnessId2 } = options;
24778
+ if (!validNativeSessionRef(input.sourceRef, harnessId2))
24779
+ return {
24780
+ ok: false,
24781
+ error: {
24782
+ code: "invalidRequest",
24783
+ message: "Invalid Antigravity source Native Session",
24784
+ retryable: false
24785
+ }
24786
+ };
24787
+ const checkpoint = nativeCheckpointRefSchema.safeParse(input.checkpoint);
24788
+ if (!checkpoint.success || checkpoint.data.harnessId !== harnessId2 || checkpoint.data.nativeSessionId !== input.sourceRef.nativeSessionId)
24789
+ return checkpointError();
24790
+ if (options.sourceSession?.isActive)
24791
+ return {
24792
+ ok: false,
24793
+ error: {
24794
+ code: "sessionBusy",
24795
+ message: "Source Session is busy",
24796
+ retryable: true
24797
+ }
24798
+ };
24799
+ const match = /^turn-(0|[1-9]\d*)$/u.exec(checkpoint.data.checkpointId);
24800
+ if (!match)
24801
+ return checkpointError();
24802
+ try {
24803
+ const count5 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
24804
+ const index = Number(match[1]);
24805
+ if (!Number.isSafeInteger(index) || index >= count5)
24806
+ return checkpointError();
24807
+ return openDerivedAntigravitySession(options, {
24808
+ kind: "resume",
24809
+ nativeRef: input.sourceRef,
24810
+ cwd: input.cwd,
24811
+ ...input.environment ? { environment: input.environment } : {}
24812
+ }, input.sourceRef, index + 1);
24813
+ } catch (error51) {
24814
+ return { ok: false, error: nativeHistoryError(error51) };
24815
+ }
24816
+ }
24817
+ function checkpointError() {
24818
+ return {
24819
+ ok: false,
24820
+ error: {
24821
+ code: "checkpointNotFound",
24822
+ message: "Antigravity native Turn checkpoint not found",
24823
+ retryable: false
24824
+ }
24825
+ };
24895
24826
  }
24896
24827
 
24897
24828
  // dist/model-catalog.js
@@ -25050,6 +24981,128 @@ function splitAntigravityModelAndEffort(rawModelId) {
25050
24981
  return { modelRef: harnessModelRefSchema.parse({ id: rawModelId.trim() }) };
25051
24982
  }
25052
24983
 
24984
+ // dist/native-replay.js
24985
+ var USER_INPUT = 14;
24986
+ var PLANNER_RESPONSE = 15;
24987
+ var ERROR_MESSAGE = 17;
24988
+ var GENERIC_TOOL = 132;
24989
+ var DONE = 3;
24990
+ var ERROR = 7;
24991
+ var IN_FLIGHT = /* @__PURE__ */ new Set([1, 2, 8, 9, 11]);
24992
+ function message2(payload) {
24993
+ const fields = payload instanceof Uint8Array ? readProtoFields(payload) : null;
24994
+ if (!fields)
24995
+ throw new Error("Invalid Antigravity history protobuf");
24996
+ return fields;
24997
+ }
24998
+ function messageField(fields, number4) {
24999
+ const field3 = fields.find((entry) => entry.number === number4 && entry.wire === 2);
25000
+ return field3?.value instanceof Uint8Array ? field3.value : void 0;
25001
+ }
25002
+ function nested(fields, number4) {
25003
+ const payload = messageField(fields, number4);
25004
+ return payload ? message2(payload) : [];
25005
+ }
25006
+ function textField(fields, number4) {
25007
+ const bytes = messageField(fields, number4);
25008
+ return bytes ? Buffer.from(bytes).toString("utf8") : "";
25009
+ }
25010
+ function argsValue(raw) {
25011
+ if (!raw)
25012
+ return void 0;
25013
+ try {
25014
+ return JSON.parse(raw);
25015
+ } catch {
25016
+ return raw;
25017
+ }
25018
+ }
25019
+ async function readNativeHistory(sessionId, home) {
25020
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
25021
+ throw new Error("Invalid native Session ID");
25022
+ const { DatabaseSync } = await import("node:sqlite");
25023
+ const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
25024
+ const events = [];
25025
+ const pendingCalls = /* @__PURE__ */ new Set();
25026
+ let turnCount = 0;
25027
+ const append = (type, text2) => {
25028
+ if (text2)
25029
+ events.push({ type, text: events.at(-1)?.type === type ? `
25030
+
25031
+ ${text2}` : text2 });
25032
+ };
25033
+ try {
25034
+ db.exec("BEGIN");
25035
+ if (db.prepare("PRAGMA user_version").get()?.user_version !== 1)
25036
+ throw new Error("Unsupported Antigravity history database version");
25037
+ for (const row of db.prepare(`SELECT step_type, status, step_payload FROM steps
25038
+ WHERE step_type IN (${USER_INPUT}, ${PLANNER_RESPONSE}, ${ERROR_MESSAGE}, ${GENERIC_TOOL})
25039
+ ORDER BY idx`).iterate()) {
25040
+ if (row.step_type === USER_INPUT)
25041
+ turnCount++;
25042
+ if (IN_FLIGHT.has(Number(row.status)))
25043
+ continue;
25044
+ const step = message2(row.step_payload);
25045
+ const number4 = row.step_type === USER_INPUT ? 19 : row.step_type === PLANNER_RESPONSE ? 20 : row.step_type === ERROR_MESSAGE ? 24 : 140;
25046
+ const body = message2(messageField(step, number4));
25047
+ switch (row.step_type) {
25048
+ case USER_INPUT: {
25049
+ const items = body.flatMap((field3) => field3.number === 3 && field3.wire === 2 ? [textField(message2(field3.value), 1)] : []);
25050
+ const text2 = items.join("") || textField(body, 2) || textField(body, 1);
25051
+ pendingCalls.clear();
25052
+ if (text2)
25053
+ events.push({ type: "user.text", text: text2 });
25054
+ break;
25055
+ }
25056
+ case PLANNER_RESPONSE: {
25057
+ append("agent.thought", textField(body, 3));
25058
+ append("agent.text", textField(body, 1));
25059
+ for (const field3 of body) {
25060
+ if (field3.number !== 7 || field3.wire !== 2)
25061
+ continue;
25062
+ const call = message2(field3.value);
25063
+ const toolCallId = textField(call, 1);
25064
+ const name = textField(call, 2);
25065
+ if (!toolCallId || !name)
25066
+ continue;
25067
+ pendingCalls.add(toolCallId);
25068
+ events.push({
25069
+ type: "tool.call",
25070
+ toolCallId,
25071
+ name,
25072
+ args: argsValue(textField(call, 3))
25073
+ });
25074
+ }
25075
+ break;
25076
+ }
25077
+ case ERROR_MESSAGE: {
25078
+ const warning = textField(nested(body, 3), 2);
25079
+ if (warning)
25080
+ append("agent.text", `⚠ ${warning}`);
25081
+ break;
25082
+ }
25083
+ case GENERIC_TOOL: {
25084
+ const toolCallId = textField(nested(nested(step, 5), 4), 1);
25085
+ if (!pendingCalls.delete(toolCallId))
25086
+ break;
25087
+ const error51 = nested(step, 31);
25088
+ const output = textField(nested(body, 2), 1) || textField(error51, 3) || textField(error51, 2) || textField(error51, 1);
25089
+ const status = row.status === DONE ? "completed" : row.status === ERROR ? "failed" : "cancelled";
25090
+ events.push({
25091
+ type: "tool.update",
25092
+ toolCallId,
25093
+ status,
25094
+ ...output ? { rawOutput: output } : {}
25095
+ });
25096
+ break;
25097
+ }
25098
+ }
25099
+ }
25100
+ return { events, turnCount };
25101
+ } finally {
25102
+ db.close();
25103
+ }
25104
+ }
25105
+
25053
25106
  // dist/permission-modes.js
25054
25107
  var ANTIGRAVITY_ACP_SESSION_MODES = ["default", "accept-edits", "auto", "plan"];
25055
25108
  var ANTIGRAVITY_DEFAULT_PERMISSION_MODE_ID = harnessPermissionModeIdSchema.parse("default");
@@ -25359,8 +25412,8 @@ import { fileURLToPath } from "node:url";
25359
25412
  // ../../harness-adapter/dist/session-import.js
25360
25413
  import { lstat as lstat2 } from "node:fs/promises";
25361
25414
  var SessionImportChangedError = class extends Error {
25362
- constructor(message2 = "Native Session changed during discovery; refresh and retry") {
25363
- super(message2);
25415
+ constructor(message3 = "Native Session changed during discovery; refresh and retry") {
25416
+ super(message3);
25364
25417
  this.name = "SessionImportChangedError";
25365
25418
  }
25366
25419
  };
@@ -25633,144 +25686,6 @@ var AntigravitySessionImport = class {
25633
25686
  }
25634
25687
  };
25635
25688
 
25636
- // dist/snapshot-reader-pool.js
25637
- var THREAD_SCOPED_ENV_KEYS = /* @__PURE__ */ new Set(["CODEXHOST_THREAD_ID"]);
25638
- function sanitizeReaderEnvironment(environment) {
25639
- const sanitized = {};
25640
- for (const [key, value] of Object.entries(environment)) {
25641
- if (value !== void 0 && !THREAD_SCOPED_ENV_KEYS.has(key)) {
25642
- sanitized[key] = value;
25643
- }
25644
- }
25645
- return sanitized;
25646
- }
25647
- function readerScopeKey(command, skipPermissions, environment) {
25648
- const entries = Object.entries(environment).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
25649
- return JSON.stringify([command ?? "", skipPermissions, entries]);
25650
- }
25651
- var AntigravitySnapshotReaderPool = class {
25652
- adapterOptions;
25653
- #lanes = /* @__PURE__ */ new Map();
25654
- #retiring = /* @__PURE__ */ new Set();
25655
- #retired = /* @__PURE__ */ new WeakSet();
25656
- #closed = false;
25657
- #closing;
25658
- constructor(adapterOptions) {
25659
- this.adapterOptions = adapterOptions;
25660
- }
25661
- loadSession(input) {
25662
- if (this.#closed || input.signal?.aborted) {
25663
- return Promise.reject(new AntigravityTransportError("unavailable", "Snapshot reader is closed"));
25664
- }
25665
- const environment = sanitizeReaderEnvironment(input.environment);
25666
- const key = readerScopeKey(this.adapterOptions.command, input.skipPermissions, environment);
25667
- let lane = this.#lanes.get(key);
25668
- if (!lane) {
25669
- lane = { transport: void 0, initialized: false, tail: Promise.resolve() };
25670
- this.#lanes.set(key, lane);
25671
- }
25672
- const currentLane = lane;
25673
- const run = currentLane.tail.then(() => this.#loadInLane(currentLane, input, environment));
25674
- currentLane.tail = run.then(() => void 0, () => void 0);
25675
- return run;
25676
- }
25677
- close() {
25678
- return this.#closing ??= this.#close().catch((error51) => {
25679
- this.#closing = void 0;
25680
- throw error51;
25681
- });
25682
- }
25683
- async #close() {
25684
- this.#closed = true;
25685
- for (const lane of this.#lanes.values()) {
25686
- if (lane.transport)
25687
- this.#retire(lane, lane.transport);
25688
- }
25689
- this.#lanes.clear();
25690
- await Promise.all(this.#retiring);
25691
- }
25692
- async #loadInLane(lane, input, environment) {
25693
- if (this.#closed || input.signal?.aborted) {
25694
- throw new AntigravityTransportError("unavailable", "Snapshot reader is closed");
25695
- }
25696
- let transport = lane.transport;
25697
- if (!transport || transport.isClosed) {
25698
- transport = this.#createTransport(lane, input.cwd, environment, input.skipPermissions);
25699
- lane.transport = transport;
25700
- lane.initialized = false;
25701
- }
25702
- if (!lane.initialized) {
25703
- try {
25704
- await transport.initialize();
25705
- lane.initialized = true;
25706
- } catch (error51) {
25707
- this.#retire(lane, transport);
25708
- throw error51;
25709
- }
25710
- }
25711
- if (this.#closed || transport.isClosed) {
25712
- this.#retire(lane, transport);
25713
- throw new AntigravityTransportError("unavailable", "Snapshot reader is closed");
25714
- }
25715
- if (input.signal?.aborted) {
25716
- throw new AntigravityTransportError("unavailable", "Snapshot read aborted");
25717
- }
25718
- try {
25719
- const { opened, replayedEvents } = await transport.openSession({
25720
- kind: "load",
25721
- sessionId: input.sessionId,
25722
- cwd: input.cwd
25723
- });
25724
- if (opened.sessionId !== input.sessionId) {
25725
- throw new AntigravityTransportError("protocolError", "Snapshot loaded a different Session");
25726
- }
25727
- await transport.closeSession();
25728
- if (this.#closed || transport.isClosed) {
25729
- this.#retire(lane, transport);
25730
- }
25731
- return { opened, replayedEvents };
25732
- } catch (error51) {
25733
- this.#retire(lane, transport);
25734
- throw error51;
25735
- }
25736
- }
25737
- #createTransport(lane, cwd, environment, skipPermissions) {
25738
- const options = {
25739
- cwd,
25740
- ...this.adapterOptions.command ? { command: this.adapterOptions.command } : {},
25741
- environment,
25742
- skipPermissions,
25743
- ...this.adapterOptions.commandTimeoutMs !== void 0 ? { commandTimeoutMs: this.adapterOptions.commandTimeoutMs } : {},
25744
- ...this.adapterOptions.closeTimeoutMs !== void 0 ? { closeTimeoutMs: this.adapterOptions.closeTimeoutMs } : {},
25745
- onFault: () => {
25746
- this.#retire(lane, transport);
25747
- }
25748
- };
25749
- const transport = this.adapterOptions.createTransport?.(options) ?? new AntigravityAcpTransport(options);
25750
- return transport;
25751
- }
25752
- #retire(lane, transport) {
25753
- if (lane.transport === transport) {
25754
- lane.transport = void 0;
25755
- lane.initialized = false;
25756
- }
25757
- if (this.#retired.has(transport))
25758
- return;
25759
- this.#retired.add(transport);
25760
- let raw;
25761
- try {
25762
- raw = transport.close();
25763
- } catch (error51) {
25764
- raw = Promise.reject(error51);
25765
- }
25766
- const tracked = raw.then(() => {
25767
- this.#retiring.delete(tracked);
25768
- });
25769
- this.#retiring.add(tracked);
25770
- void tracked.catch(() => void 0);
25771
- }
25772
- };
25773
-
25774
25689
  // dist/subagent-transcript.js
25775
25690
  import { open as open2, realpath } from "node:fs/promises";
25776
25691
  import path11 from "node:path";
@@ -26123,8 +26038,8 @@ var antigravitySessionCapabilities = {
26123
26038
  function ok(value) {
26124
26039
  return { ok: true, value };
26125
26040
  }
26126
- function err(code, message2, retryable = false) {
26127
- return { ok: false, error: { code, message: message2, retryable } };
26041
+ function err(code, message3, retryable = false) {
26042
+ return { ok: false, error: { code, message: message3, retryable } };
26128
26043
  }
26129
26044
  function normalizeAntigravityError(error51) {
26130
26045
  if (error51 instanceof AntigravityTransportError)
@@ -26134,11 +26049,11 @@ function normalizeAntigravityError(error51) {
26134
26049
  retryable: error51.retryable,
26135
26050
  ...error51.diagnostic ? { diagnostic: sanitizeDiagnosticTail(error51.diagnostic) } : {}
26136
26051
  };
26137
- const message2 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
26052
+ const message3 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
26138
26053
  const code = error51?.code;
26139
26054
  return {
26140
- code: code === "ENOENT" ? "notInstalled" : /authenticat|sign.?in|login|credential/iu.test(message2) ? "authenticationRequired" : "nativeFailure",
26141
- message: message2,
26055
+ code: code === "ENOENT" ? "notInstalled" : /authenticat|sign.?in|login|credential/iu.test(message3) ? "authenticationRequired" : "nativeFailure",
26056
+ message: message3,
26142
26057
  retryable: false
26143
26058
  };
26144
26059
  }
@@ -26339,7 +26254,7 @@ var AntigravitySession = class {
26339
26254
  return;
26340
26255
  }
26341
26256
  const ref = this.nativeRef ?? this.#options.nativeRef;
26342
- const { opened, replayedEvents } = await transport.openSession({
26257
+ const { opened } = await transport.openSession({
26343
26258
  kind: ref ? "resume" : "create",
26344
26259
  ...ref ? { sessionId: ref.nativeSessionId } : {},
26345
26260
  cwd: this.#options.cwd,
@@ -26354,17 +26269,8 @@ var AntigravitySession = class {
26354
26269
  if (!validNativeSessionRef({ harnessId, nativeSessionId: opened.sessionId, formatVersion: 1 }, harnessId))
26355
26270
  throw new AntigravityTransportError("protocolError", "Antigravity returned an invalid native Session ID");
26356
26271
  this.#applyOpened(opened, skip);
26357
- try {
26358
- this.#turnCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment)));
26359
- } catch {
26360
- this.#turnCount = Math.max(this.#turnCount, projectReplayedEventsToTurns({
26361
- nativeSessionId: opened.sessionId,
26362
- cwd: this.#options.cwd,
26363
- events: replayedEvents,
26364
- ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {}
26365
- }).length);
26366
- }
26367
- this.#initializeUsage(opened.sessionId, replayedEvents);
26272
+ this.#turnCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment))).catch(() => this.#turnCount);
26273
+ this.#initializeUsage(opened.sessionId);
26368
26274
  transport.setSessionEventHandler((event) => {
26369
26275
  if (this.#transport === transport && !this.#closed && !this.#faulted)
26370
26276
  this.#sessionEvent(event);
@@ -26394,15 +26300,13 @@ var AntigravitySession = class {
26394
26300
  throw error51;
26395
26301
  }
26396
26302
  }
26397
- #initializeUsage(nativeSessionId, events) {
26303
+ #initializeUsage(nativeSessionId) {
26398
26304
  if (this.#usage)
26399
26305
  return;
26400
- const context = events.findLast((event) => event.type === "usage.context");
26401
26306
  this.#usage = new AntigravitySessionUsageTracker({
26402
26307
  nativeSessionId,
26403
26308
  homedir: antigravityHome(this.#options.environment),
26404
- expectedInitialTurns: this.#turnCount,
26405
- ...context ? { initialContextUsedTokens: context.used, initialContextWindowTokens: context.size } : {}
26309
+ expectedInitialTurns: this.#turnCount
26406
26310
  });
26407
26311
  this.#usageWork = this.#replayUsage();
26408
26312
  }
@@ -26594,38 +26498,30 @@ var AntigravitySession = class {
26594
26498
  async readSnapshot() {
26595
26499
  if (this.#closed || this.#faulted)
26596
26500
  return err("invalidState", "Session is closed");
26597
- if (!this.nativeRef)
26501
+ const nativeRef = this.nativeRef;
26502
+ if (!nativeRef)
26598
26503
  return ok({ turns: [], state: { ...this.#state } });
26599
- const skip = this.#transport?.skipPermissions ?? (this.#options.unattended || this.#requested.permissionModeId === SKIP);
26504
+ const { nativeSessionId } = nativeRef;
26600
26505
  try {
26601
- const { opened, replayedEvents } = await this.#options.readerPool.loadSession({
26602
- sessionId: this.nativeRef.nativeSessionId,
26603
- cwd: this.#options.cwd,
26604
- environment: this.#options.environment,
26605
- skipPermissions: skip,
26606
- signal: this.#abort.signal
26607
- });
26506
+ const { events, turnCount } = await readNativeHistory(nativeSessionId, antigravityHome(this.#options.environment));
26608
26507
  if (this.#closed || this.#faulted)
26609
26508
  return err("invalidState", "Session is closed");
26610
26509
  const turns = projectReplayedEventsToTurns({
26611
- nativeSessionId: opened.sessionId,
26510
+ nativeSessionId,
26612
26511
  cwd: this.#options.cwd,
26613
- events: replayedEvents,
26512
+ events,
26614
26513
  ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {},
26615
26514
  ...this.#options.adapter.toolOutputLimit !== void 0 ? { outputLimit: this.#options.adapter.toolOutputLimit } : {}
26616
26515
  });
26617
- const turnCount = this.#transport ? this.#turnCount : await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment))).catch(() => turns.length);
26618
- if (this.#closed || this.#faulted)
26619
- return err("invalidState", "Session is closed");
26620
26516
  if (!this.#transport) {
26621
26517
  this.#turnCount = turnCount;
26622
- this.#initializeUsage(opened.sessionId, replayedEvents);
26518
+ this.#initializeUsage(nativeSessionId);
26623
26519
  }
26624
26520
  return ok({ turns, ...this.#transport ? { state: { ...this.#state } } : {} });
26625
- } catch (error51) {
26521
+ } catch {
26626
26522
  if (this.#closed || this.#faulted)
26627
26523
  return err("invalidState", "Session is closed");
26628
- return { ok: false, error: normalizeAntigravityError(error51) };
26524
+ return err("nativeFailure", "Antigravity history unavailable");
26629
26525
  }
26630
26526
  }
26631
26527
  async execute(command) {
@@ -27083,7 +26979,6 @@ var AntigravityAdapter = class {
27083
26979
  usageStatistics;
27084
26980
  #environment;
27085
26981
  #sessions = /* @__PURE__ */ new Set();
27086
- #readerPool;
27087
26982
  #cache = /* @__PURE__ */ new Map();
27088
26983
  #inflight = /* @__PURE__ */ new Map();
27089
26984
  #abort = new AbortController();
@@ -27094,7 +26989,6 @@ var AntigravityAdapter = class {
27094
26989
  constructor(options = {}) {
27095
26990
  this.options = options;
27096
26991
  this.#environment = options.environment ?? process.env;
27097
- this.#readerPool = new AntigravitySnapshotReaderPool(this.options);
27098
26992
  this.sessionImport = new AntigravitySessionImport(this.#environment);
27099
26993
  this.usageStatistics = createAntigravityUsageStatistics(this.#environment);
27100
26994
  }
@@ -27237,7 +27131,6 @@ var AntigravityAdapter = class {
27237
27131
  ...input.kind === "resume" ? { nativeRef: input.nativeRef, knownTurnRefs: input.knownTurnRefs } : {},
27238
27132
  unattended,
27239
27133
  adapter: this.options,
27240
- readerPool: this.#readerPool,
27241
27134
  onClosed: (closed) => this.#sessions.delete(closed)
27242
27135
  });
27243
27136
  this.#sessions.add(session);
@@ -27312,10 +27205,7 @@ var AntigravityAdapter = class {
27312
27205
  this.#cache.clear();
27313
27206
  this.#inflight.clear();
27314
27207
  this.#quota = null;
27315
- await Promise.all([
27316
- ...[...this.#sessions].map((session) => session.close()),
27317
- this.#readerPool.close()
27318
- ]);
27208
+ await Promise.all([...this.#sessions].map((session) => session.close()));
27319
27209
  this.#sessions.clear();
27320
27210
  }
27321
27211
  };