@codexhost/cli-linux-arm64 0.21.0 → 0.22.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 (42) 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 +1 -0
  5. package/app/desktop-controller.mjs +4 -1
  6. package/app/host-runtime.mjs +86 -21
  7. package/app/plugins/antigravity/plugin.mjs +1144 -1254
  8. package/app/plugins/claude-code/plugin.mjs +389 -84
  9. package/app/plugins/codebuddy/plugin.mjs +1 -0
  10. package/app/plugins/codex-usage/plugin.mjs +1 -0
  11. package/app/plugins/copilot/plugin.mjs +1 -0
  12. package/app/plugins/cursor-cli/plugin.mjs +1 -0
  13. package/app/plugins/deepseek-harness/plugin.mjs +1 -0
  14. package/app/plugins/devin/plugin.mjs +1 -0
  15. package/app/plugins/grok/plugin.mjs +192 -177
  16. package/app/plugins/hermes/plugin.mjs +1 -0
  17. package/app/plugins/kimi-code/plugin.mjs +1 -0
  18. package/app/plugins/kiro-cli/plugin.mjs +1 -0
  19. package/app/plugins/omp/plugin.mjs +108 -22
  20. package/app/plugins/opencode/plugin.mjs +1 -0
  21. package/app/plugins/pi/plugin.mjs +119 -23
  22. package/app/plugins/qoder/plugin.mjs +1 -0
  23. package/app/plugins/qoder-cn/plugin.mjs +1 -0
  24. package/app/plugins/qwen-code/plugin.mjs +1 -0
  25. package/app/plugins/workbuddy/plugin.mjs +1 -0
  26. package/app/plugins/zcode/plugin.mjs +1 -0
  27. package/app/renderer-extension.js +1 -0
  28. package/app/web/assets/index-CN4a4sj0.js +201 -0
  29. package/app/web/codexhost-settings.js +1 -0
  30. package/app/web/index.html +1 -1
  31. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  32. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +6 -6
  33. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +69 -69
  34. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +2 -2
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +1 -1
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +1 -1
  37. package/app/web-modules/server.mjs +130 -74
  38. package/bin/codexhost +0 -0
  39. package/libexec/codexhost-shim +0 -0
  40. package/libexec/codexhost-updater +0 -0
  41. package/package.json +1 -1
  42. package/app/web/assets/index-BdmZfTRW.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
  }
@@ -16909,6 +16909,7 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16909
16909
  message: "A history continuation requires its connection epoch"
16910
16910
  }).optional()
16911
16911
  }),
16912
+ external_exports.strictObject({ kind: external_exports.literal("usage"), ...thread, epoch: identity }),
16912
16913
  external_exports.strictObject({
16913
16914
  kind: external_exports.literal("configure"),
16914
16915
  ...thread,
@@ -17040,16 +17041,16 @@ var webUiExtensionRemoveSchema = external_exports.object({ id: webUiExtensionIdS
17040
17041
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
17041
17042
 
17042
17043
  // ../../harness-adapter/dist/approval.js
17043
- function invalidRequest(message2) {
17044
- return { code: "invalidRequest", message: message2, retryable: false };
17044
+ function invalidRequest(message3) {
17045
+ return { code: "invalidRequest", message: message3, retryable: false };
17045
17046
  }
17046
17047
  function validateHostApprovalResponse(interaction, response) {
17047
17048
  return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17048
17049
  }
17049
17050
 
17050
17051
  // ../../harness-adapter/dist/question.js
17051
- function invalidRequest2(message2) {
17052
- return { code: "invalidRequest", message: message2, retryable: false };
17052
+ function invalidRequest2(message3) {
17053
+ return { code: "invalidRequest", message: message3, retryable: false };
17053
17054
  }
17054
17055
  function validateHostQuestionResponse(interaction, response) {
17055
17056
  const questionIds = new Set(interaction.questions.map(({ id }) => id));
@@ -19262,8 +19263,8 @@ var Handled = {
19262
19263
  /**
19263
19264
  * Leaves a message unhandled so later handlers can process it.
19264
19265
  */
19265
- no(message2, retry = false) {
19266
- return { handled: false, message: message2, retry };
19266
+ no(message3, retry = false) {
19267
+ return { handled: false, message: message3, retry };
19267
19268
  }
19268
19269
  };
19269
19270
  function rejectedPromise(error51) {
@@ -19510,8 +19511,8 @@ var Connection = class {
19510
19511
  addDynamicHandler(handler) {
19511
19512
  this.dynamicHandlers.add(handler);
19512
19513
  if (this.retryQueue.length > 0) {
19513
- for (const message2 of this.retryQueue.splice(0)) {
19514
- void this.processIncomingMessage(message2).catch((error51) => this.close(error51));
19514
+ for (const message3 of this.retryQueue.splice(0)) {
19515
+ void this.processIncomingMessage(message3).catch((error51) => this.close(error51));
19515
19516
  }
19516
19517
  }
19517
19518
  return new HandlerRegistration(() => {
@@ -19690,12 +19691,12 @@ var Connection = class {
19690
19691
  }
19691
19692
  legacyHandler(requestHandler, notificationHandler) {
19692
19693
  return {
19693
- handleMessage: async (message2, cx) => {
19694
- if (message2.kind === "request") {
19695
- const result = await requestHandler(message2.method, message2.params, cx);
19696
- await message2.responder.respond(result);
19694
+ handleMessage: async (message3, cx) => {
19695
+ if (message3.kind === "request") {
19696
+ const result = await requestHandler(message3.method, message3.params, cx);
19697
+ await message3.responder.respond(result);
19697
19698
  } else {
19698
- await notificationHandler(message2.method, message2.params, cx);
19699
+ await notificationHandler(message3.method, message3.params, cx);
19699
19700
  }
19700
19701
  return Handled.yes();
19701
19702
  }
@@ -19708,17 +19709,17 @@ var Connection = class {
19708
19709
  this.receiveReader = reader;
19709
19710
  try {
19710
19711
  while (!this.abortController.signal.aborted) {
19711
- const { value: message2, done } = await reader.read();
19712
+ const { value: message3, done } = await reader.read();
19712
19713
  if (this.abortController.signal.aborted) {
19713
19714
  break;
19714
19715
  }
19715
19716
  if (done) {
19716
19717
  break;
19717
19718
  }
19718
- if (!message2) {
19719
+ if (!message3) {
19719
19720
  continue;
19720
19721
  }
19721
- this.receiveWireMessage(message2);
19722
+ this.receiveWireMessage(message3);
19722
19723
  }
19723
19724
  } finally {
19724
19725
  if (this.receiveReader === reader) {
@@ -19732,20 +19733,20 @@ var Connection = class {
19732
19733
  this.close(closeError);
19733
19734
  }
19734
19735
  }
19735
- receiveWireMessage(message2) {
19736
- if (Array.isArray(message2)) {
19736
+ receiveWireMessage(message3) {
19737
+ if (Array.isArray(message3)) {
19737
19738
  if (!this.allowBatches) {
19738
19739
  this.close(new TypeError("JSON-RPC batches are not supported on this connection"));
19739
19740
  return;
19740
19741
  }
19741
- this.receiveBatch(message2);
19742
+ this.receiveBatch(message3);
19742
19743
  return;
19743
19744
  }
19744
- if (!isRecord2(message2)) {
19745
- console.error("Invalid message", { message: message2 });
19745
+ if (!isRecord2(message3)) {
19746
+ console.error("Invalid message", { message: message3 });
19746
19747
  return;
19747
19748
  }
19748
- this.receiveMessage(message2);
19749
+ this.receiveMessage(message3);
19749
19750
  }
19750
19751
  receiveBatch(batch) {
19751
19752
  if (batch.length === 0) {
@@ -19758,9 +19759,9 @@ var Connection = class {
19758
19759
  return;
19759
19760
  }
19760
19761
  const responseBatch = isResponseBatch(batch);
19761
- const responseCount = responseBatch ? 0 : batch.reduce((count4, message2) => count4 + (isNotificationMessage(message2) ? 0 : 1), 0);
19762
+ const responseCount = responseBatch ? 0 : batch.reduce((count4, message3) => count4 + (isNotificationMessage(message3) ? 0 : 1), 0);
19762
19763
  let remaining = responseCount;
19763
- let remainingNotifications = batch.reduce((count4, message2) => count4 + (isNotificationMessage(message2) ? 1 : 0), 0);
19764
+ let remainingNotifications = batch.reduce((count4, message3) => count4 + (isNotificationMessage(message3) ? 1 : 0), 0);
19764
19765
  let responseSent = false;
19765
19766
  const responses = [];
19766
19767
  const sendResponsesIfReady = async () => {
@@ -19775,24 +19776,24 @@ var Connection = class {
19775
19776
  remaining -= 1;
19776
19777
  await sendResponsesIfReady();
19777
19778
  };
19778
- for (const message2 of batch) {
19779
+ for (const message3 of batch) {
19779
19780
  if (responseBatch) {
19780
- if (isResponseShapedMessage(message2)) {
19781
- this.receiveMessage(message2);
19781
+ if (isResponseShapedMessage(message3)) {
19782
+ this.receiveMessage(message3);
19782
19783
  }
19783
19784
  continue;
19784
19785
  }
19785
- if (!isRequestMessage(message2) && !isNotificationMessage(message2)) {
19786
+ if (!isRequestMessage(message3) && !isNotificationMessage(message3)) {
19786
19787
  void collectResponse({
19787
19788
  jsonrpc: "2.0",
19788
19789
  id: null,
19789
- error: RequestError.invalidRequest(message2).toErrorResponse()
19790
+ error: RequestError.invalidRequest(message3).toErrorResponse()
19790
19791
  }).catch(() => {
19791
19792
  });
19792
19793
  continue;
19793
19794
  }
19794
- const processing = this.receiveMessage(message2, isRequestMessage(message2) ? collectResponse : void 0);
19795
- if (isNotificationMessage(message2)) {
19795
+ const processing = this.receiveMessage(message3, isRequestMessage(message3) ? collectResponse : void 0);
19796
+ if (isNotificationMessage(message3)) {
19796
19797
  void processing.finally(() => {
19797
19798
  remainingNotifications -= 1;
19798
19799
  void sendResponsesIfReady().catch((error51) => this.close(error51));
@@ -19800,31 +19801,31 @@ var Connection = class {
19800
19801
  }
19801
19802
  }
19802
19803
  }
19803
- receiveMessage(message2, sendResponse) {
19804
+ receiveMessage(message3, sendResponse) {
19804
19805
  if (this.abortController.signal.aborted) {
19805
19806
  return Promise.resolve();
19806
19807
  }
19807
- if (!isRecord2(message2)) {
19808
- console.error("Invalid message", { message: message2 });
19808
+ if (!isRecord2(message3)) {
19809
+ console.error("Invalid message", { message: message3 });
19809
19810
  return Promise.resolve();
19810
19811
  }
19811
- if ("method" in message2) {
19812
- if (!("id" in message2)) {
19813
- this.handleProtocolNotification(message2);
19812
+ if ("method" in message3) {
19813
+ if (!("id" in message3)) {
19814
+ this.handleProtocolNotification(message3);
19814
19815
  }
19815
- return this.processIncomingMessage(this.toIncomingMessage(message2, sendResponse)).catch((error51) => this.close(error51));
19816
- } else if ("id" in message2) {
19817
- this.handleResponse(message2);
19816
+ return this.processIncomingMessage(this.toIncomingMessage(message3, sendResponse)).catch((error51) => this.close(error51));
19817
+ } else if ("id" in message3) {
19818
+ this.handleResponse(message3);
19818
19819
  } else {
19819
- console.error("Invalid message", { message: message2 });
19820
+ console.error("Invalid message", { message: message3 });
19820
19821
  }
19821
19822
  return Promise.resolve();
19822
19823
  }
19823
- async processIncomingMessage(message2) {
19824
+ async processIncomingMessage(message3) {
19824
19825
  if (this.abortController.signal.aborted) {
19825
19826
  return;
19826
19827
  }
19827
- let current = message2;
19828
+ let current = message3;
19828
19829
  let retry = false;
19829
19830
  try {
19830
19831
  for (const handler of [
@@ -19857,30 +19858,30 @@ var Connection = class {
19857
19858
  } else {
19858
19859
  const response = errorToResult(error51);
19859
19860
  if ("error" in response) {
19860
- console.error("Error handling notification", message2.raw, response.error);
19861
+ console.error("Error handling notification", message3.raw, response.error);
19861
19862
  }
19862
19863
  }
19863
19864
  }
19864
19865
  }
19865
- toIncomingMessage(message2, sendResponse) {
19866
- if ("id" in message2) {
19866
+ toIncomingMessage(message3, sendResponse) {
19867
+ if ("id" in message3) {
19867
19868
  const abortController = new AbortController();
19868
- this.incomingRequests.set(message2.id, abortController);
19869
+ this.incomingRequests.set(message3.id, abortController);
19869
19870
  const finishRequest = () => {
19870
- if (this.incomingRequests.get(message2.id) === abortController) {
19871
- this.incomingRequests.delete(message2.id);
19871
+ if (this.incomingRequests.get(message3.id) === abortController) {
19872
+ this.incomingRequests.delete(message3.id);
19872
19873
  }
19873
19874
  };
19874
19875
  return {
19875
19876
  kind: "request",
19876
- method: message2.method,
19877
- params: message2.params,
19878
- raw: message2,
19877
+ method: message3.method,
19878
+ params: message3.params,
19879
+ raw: message3,
19879
19880
  signal: abortController.signal,
19880
- responder: new RequestResponder(message2.id, (result) => {
19881
+ responder: new RequestResponder(message3.id, (result) => {
19881
19882
  const response = {
19882
19883
  jsonrpc: "2.0",
19883
- id: message2.id,
19884
+ id: message3.id,
19884
19885
  ...result
19885
19886
  };
19886
19887
  return sendResponse ? sendResponse(response) : this.sendWireMessage(response);
@@ -19889,9 +19890,9 @@ var Connection = class {
19889
19890
  }
19890
19891
  return {
19891
19892
  kind: "notification",
19892
- method: message2.method,
19893
- params: message2.params,
19894
- raw: message2
19893
+ method: message3.method,
19894
+ params: message3.params,
19895
+ raw: message3
19895
19896
  };
19896
19897
  }
19897
19898
  handleResponse(response) {
@@ -19904,18 +19905,18 @@ var Connection = class {
19904
19905
  } else if ("result" in response) {
19905
19906
  pendingResponse.resolve(response.result);
19906
19907
  } else {
19907
- const { code, message: message2, data } = response.error;
19908
- pendingResponse.reject(new RequestError(code, message2, data));
19908
+ const { code, message: message3, data } = response.error;
19909
+ pendingResponse.reject(new RequestError(code, message3, data));
19909
19910
  }
19910
19911
  } else {
19911
19912
  console.error("Got response to unknown request", response.id);
19912
19913
  }
19913
19914
  }
19914
- handleProtocolNotification(message2) {
19915
- if (message2.method !== CANCEL_REQUEST_METHOD) {
19915
+ handleProtocolNotification(message3) {
19916
+ if (message3.method !== CANCEL_REQUEST_METHOD) {
19916
19917
  return;
19917
19918
  }
19918
- const requestId = cancelRequestId(message2.params);
19919
+ const requestId = cancelRequestId(message3.params);
19919
19920
  if (requestId === void 0) {
19920
19921
  return;
19921
19922
  }
@@ -19928,7 +19929,7 @@ var Connection = class {
19928
19929
  closedReason() {
19929
19930
  return this.abortController.signal.reason ?? new Error("ACP connection closed");
19930
19931
  }
19931
- async sendWireMessage(message2) {
19932
+ async sendWireMessage(message3) {
19932
19933
  if (this.abortController.signal.aborted) {
19933
19934
  return rejectedPromise(this.closedReason());
19934
19935
  }
@@ -19938,7 +19939,7 @@ var Connection = class {
19938
19939
  }
19939
19940
  const writer = this.stream.writable.getWriter();
19940
19941
  try {
19941
- await writer.write(message2);
19942
+ await writer.write(message3);
19942
19943
  } finally {
19943
19944
  writer.releaseLock();
19944
19945
  }
@@ -19974,7 +19975,7 @@ var ConnectionBuilder = class {
19974
19975
  */
19975
19976
  onReceiveMessage(handler) {
19976
19977
  return this.withHandler({
19977
- handleMessage: async (message2, cx) => await handler(message2, cx) ?? Handled.no(message2),
19978
+ handleMessage: async (message3, cx) => await handler(message3, cx) ?? Handled.no(message3),
19978
19979
  describe: () => this.connectionName ?? "onReceiveMessage"
19979
19980
  });
19980
19981
  }
@@ -19983,12 +19984,12 @@ var ConnectionBuilder = class {
19983
19984
  */
19984
19985
  onReceiveRequest(method, parse3, handler) {
19985
19986
  return this.withHandler({
19986
- handleMessage: async (message2, cx) => {
19987
- if (message2.kind !== "request" || message2.method !== method) {
19988
- return Handled.no(message2);
19987
+ handleMessage: async (message3, cx) => {
19988
+ if (message3.kind !== "request" || message3.method !== method) {
19989
+ return Handled.no(message3);
19989
19990
  }
19990
- const request = parse3(message2.params);
19991
- return await handler(request, message2.responder, cx) ?? Handled.yes();
19991
+ const request = parse3(message3.params);
19992
+ return await handler(request, message3.responder, cx) ?? Handled.yes();
19992
19993
  },
19993
19994
  describe: () => `${this.connectionName ?? "request"}:${method}`
19994
19995
  });
@@ -19998,11 +19999,11 @@ var ConnectionBuilder = class {
19998
19999
  */
19999
20000
  onReceiveNotification(method, parse3, handler) {
20000
20001
  return this.withHandler({
20001
- handleMessage: async (message2, cx) => {
20002
- if (message2.kind !== "notification" || message2.method !== method) {
20003
- return Handled.no(message2);
20002
+ handleMessage: async (message3, cx) => {
20003
+ if (message3.kind !== "notification" || message3.method !== method) {
20004
+ return Handled.no(message3);
20004
20005
  }
20005
- const notification = parse3(message2.params);
20006
+ const notification = parse3(message3.params);
20006
20007
  return await handler(notification, cx) ?? Handled.yes();
20007
20008
  },
20008
20009
  describe: () => `${this.connectionName ?? "notification"}:${method}`
@@ -20027,8 +20028,8 @@ var RequestError = class _RequestError extends Error {
20027
20028
  * Additional JSON-RPC error data.
20028
20029
  */
20029
20030
  data;
20030
- constructor(code, message2, data) {
20031
- super(message2);
20031
+ constructor(code, message3, data) {
20032
+ super(message3);
20032
20033
  this.code = code;
20033
20034
  this.name = "RequestError";
20034
20035
  this.data = data;
@@ -20173,9 +20174,9 @@ function ndJsonStream(output, input) {
20173
20174
  const trimmedLine = textDecoder.decode(lineBytes).trim();
20174
20175
  if (trimmedLine) {
20175
20176
  try {
20176
- const message2 = JSON.parse(trimmedLine);
20177
- if (isRecord2(message2) || Array.isArray(message2)) {
20178
- controller.enqueue(message2);
20177
+ const message3 = JSON.parse(trimmedLine);
20178
+ if (isRecord2(message3) || Array.isArray(message3)) {
20179
+ controller.enqueue(message3);
20179
20180
  } else {
20180
20181
  console.warn("Skipping JSON line that is not an object:", trimmedLine);
20181
20182
  }
@@ -20235,8 +20236,8 @@ function ndJsonStream(output, input) {
20235
20236
  }
20236
20237
  });
20237
20238
  const writable = new WritableStream({
20238
- async write(message2) {
20239
- const content = JSON.stringify(message2) + "\n";
20239
+ async write(message3) {
20240
+ const content = JSON.stringify(message3) + "\n";
20240
20241
  const writer = output.getWriter();
20241
20242
  try {
20242
20243
  await writer.write(textEncoder.encode(content));
@@ -20723,11 +20724,11 @@ var ActiveSession = class _ActiveSession {
20723
20724
  async readText() {
20724
20725
  let output = "";
20725
20726
  for (; ; ) {
20726
- const message2 = await this.nextUpdate();
20727
- if (message2.kind === "stop") {
20727
+ const message3 = await this.nextUpdate();
20728
+ if (message3.kind === "stop") {
20728
20729
  return output;
20729
20730
  }
20730
- const { update } = message2;
20731
+ const { update } = message3;
20731
20732
  if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
20732
20733
  output += update.content.text;
20733
20734
  }
@@ -20875,11 +20876,11 @@ function clientNotificationContext(params, agent, signal) {
20875
20876
  }
20876
20877
  var SessionUpdateRouter = class {
20877
20878
  activeSessions = /* @__PURE__ */ new Map();
20878
- handleMessage(message2) {
20879
- if (message2.kind !== "notification" || message2.method !== CLIENT_METHODS.session_update) {
20880
- return Handled.no(message2);
20879
+ handleMessage(message3) {
20880
+ if (message3.kind !== "notification" || message3.method !== CLIENT_METHODS.session_update) {
20881
+ return Handled.no(message3);
20881
20882
  }
20882
- const notification = zSessionNotification.parse(message2.params);
20883
+ const notification = zSessionNotification.parse(message3.params);
20883
20884
  const update = {
20884
20885
  kind: "session_update",
20885
20886
  notification,
@@ -20891,7 +20892,7 @@ var SessionUpdateRouter = class {
20891
20892
  session.enqueue(update);
20892
20893
  }
20893
20894
  }
20894
- return Handled.no(message2);
20895
+ return Handled.no(message3);
20895
20896
  }
20896
20897
  attach(response, updates) {
20897
20898
  const sessions = this.activeSessions.get(response.sessionId) ?? /* @__PURE__ */ new Set();
@@ -21036,7 +21037,7 @@ var ClientApp = class {
21036
21037
  this.builder.name(options.name);
21037
21038
  }
21038
21039
  this.builder.withHandler({
21039
- handleMessage: (message2, cx) => sessionUpdateRouter(cx).handleMessage(message2),
21040
+ handleMessage: (message3, cx) => sessionUpdateRouter(cx).handleMessage(message3),
21040
21041
  describe: () => "client-session-update-router"
21041
21042
  });
21042
21043
  }
@@ -21179,11 +21180,11 @@ function legacyClientApp(implementation) {
21179
21180
  }
21180
21181
  if (implementation.extMethod) {
21181
21182
  app[appBuilder]().withHandler({
21182
- handleMessage: async (message2) => {
21183
- if (message2.kind !== "request" || legacyClientRequestMethods.has(message2.method)) {
21184
- return Handled.no(message2);
21183
+ handleMessage: async (message3) => {
21184
+ if (message3.kind !== "request" || legacyClientRequestMethods.has(message3.method)) {
21185
+ return Handled.no(message3);
21185
21186
  }
21186
- await message2.responder.respond(await implementation.extMethod(message2.method, message2.params));
21187
+ await message3.responder.respond(await implementation.extMethod(message3.method, message3.params));
21187
21188
  return Handled.yes();
21188
21189
  },
21189
21190
  describe: () => "legacy-client-extension-request"
@@ -21191,11 +21192,11 @@ function legacyClientApp(implementation) {
21191
21192
  }
21192
21193
  if (implementation.extNotification) {
21193
21194
  app[appBuilder]().withHandler({
21194
- handleMessage: async (message2) => {
21195
- if (message2.kind !== "notification" || legacyClientNotificationMethods.has(message2.method)) {
21196
- return Handled.no(message2);
21195
+ handleMessage: async (message3) => {
21196
+ if (message3.kind !== "notification" || legacyClientNotificationMethods.has(message3.method)) {
21197
+ return Handled.no(message3);
21197
21198
  }
21198
- await implementation.extNotification(message2.method, message2.params);
21199
+ await implementation.extNotification(message3.method, message3.params);
21199
21200
  return Handled.yes();
21200
21201
  },
21201
21202
  describe: () => "legacy-client-extension-notification"
@@ -22250,9 +22251,9 @@ function extractString(record4, keys) {
22250
22251
  }
22251
22252
  for (const wrapper of ["input", "arguments", "params", "parameters"]) {
22252
22253
  if (isRecord3(record4[wrapper])) {
22253
- const nested = extractString(record4[wrapper], keys);
22254
- if (nested !== void 0)
22255
- return nested;
22254
+ const nested2 = extractString(record4[wrapper], keys);
22255
+ if (nested2 !== void 0)
22256
+ return nested2;
22256
22257
  }
22257
22258
  }
22258
22259
  return void 0;
@@ -22725,6 +22726,7 @@ var AntigravityToolTracker = class {
22725
22726
  };
22726
22727
  function projectReplayedEventsToTurns(params) {
22727
22728
  const turns = [];
22729
+ const usedTurnKeys = new Set(params.knownTurnRefs?.map(({ nativeTurnKey }) => nativeTurnKey));
22728
22730
  let active;
22729
22731
  let userRun = false;
22730
22732
  let textItem;
@@ -22732,15 +22734,23 @@ function projectReplayedEventsToTurns(params) {
22732
22734
  const begin = () => {
22733
22735
  active?.tracker.finishPending({
22734
22736
  status: "cancelled",
22735
- reason: "No terminal tool status in ACP replay"
22737
+ reason: "No terminal tool status in native history"
22736
22738
  });
22737
22739
  const index = turns.length;
22738
22740
  const turnId = hostTurnIdSchema.parse(`turn-${index}`);
22741
+ let nativeTurnKey = params.knownTurnRefs?.[index]?.nativeTurnKey;
22742
+ if (nativeTurnKey === void 0) {
22743
+ let n = index;
22744
+ nativeTurnKey = `turn-${n}`;
22745
+ while (usedTurnKeys.has(nativeTurnKey))
22746
+ nativeTurnKey = `turn-${++n}`;
22747
+ usedTurnKeys.add(nativeTurnKey);
22748
+ }
22739
22749
  const turn = {
22740
22750
  nativeTurnRef: nativeTurnRefSchema.parse({
22741
22751
  harnessId: "antigravity",
22742
22752
  nativeSessionId: params.nativeSessionId,
22743
- nativeTurnKey: params.knownTurnRefs?.[index]?.nativeTurnKey ?? `turn-${index}`,
22753
+ nativeTurnKey,
22744
22754
  formatVersion: 1
22745
22755
  }),
22746
22756
  checkpoint: nativeCheckpointRefSchema.parse({
@@ -22751,7 +22761,7 @@ function projectReplayedEventsToTurns(params) {
22751
22761
  }),
22752
22762
  input: [],
22753
22763
  items: [],
22754
- outcome: { status: "unknown", reason: "ACP replay does not include prompt stop reasons" }
22764
+ outcome: { status: "unknown", reason: "Native history does not include prompt stop reasons" }
22755
22765
  };
22756
22766
  turns.push(turn);
22757
22767
  sequence = 0;
@@ -22811,7 +22821,7 @@ function projectReplayedEventsToTurns(params) {
22811
22821
  }
22812
22822
  active?.tracker.finishPending({
22813
22823
  status: "cancelled",
22814
- reason: "No terminal tool status in ACP replay"
22824
+ reason: "No terminal tool status in native history"
22815
22825
  });
22816
22826
  return turns;
22817
22827
  }
@@ -22849,8 +22859,8 @@ var AntigravityTransportError = class extends Error {
22849
22859
  kind;
22850
22860
  diagnostic;
22851
22861
  retryable;
22852
- constructor(kind, message2, options) {
22853
- super(message2, options);
22862
+ constructor(kind, message3, options) {
22863
+ super(message3, options);
22854
22864
  this.kind = kind;
22855
22865
  this.name = "AntigravityTransportError";
22856
22866
  this.diagnostic = options?.diagnostic;
@@ -22874,264 +22884,393 @@ var AntigravityTransportError = class extends Error {
22874
22884
  }
22875
22885
  };
22876
22886
 
22877
- // dist/fork.js
22878
- import { randomUUID } from "node:crypto";
22879
- import { access as access2, cp, mkdir, open, rm as rm2 } from "node:fs/promises";
22880
- import os3 from "node:os";
22881
- import path9 from "node:path";
22882
-
22883
- // dist/native-protobuf.js
22884
- function decodeVarint(buffer, start) {
22885
- let value = 0n;
22886
- for (let index = 0; index < 10; index++) {
22887
- const byte = buffer[start + index];
22888
- if (byte === void 0 || index === 9 && byte > 1)
22889
- return null;
22890
- value |= BigInt(byte & 127) << BigInt(index * 7);
22891
- if ((byte & 128) === 0)
22892
- return [value, start + index + 1];
22887
+ // dist/acp-transport.js
22888
+ var AntigravityAcpTransport = class {
22889
+ options;
22890
+ skipPermissions;
22891
+ #child = null;
22892
+ #connection = null;
22893
+ #initializing = null;
22894
+ #sessionId = null;
22895
+ #sessionHandler = null;
22896
+ #active = null;
22897
+ #callbacks = /* @__PURE__ */ new Set();
22898
+ #acceptCallbacks = false;
22899
+ #promptInterrupted = null;
22900
+ #opening = null;
22901
+ #pendingEvents = [];
22902
+ #closed = false;
22903
+ #closing = null;
22904
+ #stderrRaw = "";
22905
+ get #stderr() {
22906
+ return sanitizeDiagnosticTail(this.#stderrRaw);
22893
22907
  }
22894
- return null;
22895
- }
22896
- function readProtoFields(blob) {
22897
- const fields = [];
22898
- let offset = 0;
22899
- while (offset < blob.length) {
22900
- if (fields.length >= 1e4)
22901
- return null;
22902
- const tag = decodeVarint(blob, offset);
22903
- if (!tag || tag[0] < 8n || tag[0] > 0xffffffffn)
22904
- return null;
22905
- offset = tag[1];
22906
- const number4 = Number(tag[0] >> 3n);
22907
- const wire = Number(tag[0] & 7n);
22908
- if (wire === 0) {
22909
- const value = decodeVarint(blob, offset);
22910
- if (!value)
22911
- return null;
22912
- fields.push({ number: number4, wire, value: value[0] });
22913
- offset = value[1];
22914
- } else if (wire === 1 || wire === 5) {
22915
- const length = wire === 1 ? 8 : 4;
22916
- if (offset + length > blob.length)
22917
- return null;
22918
- fields.push({ number: number4, wire, value: blob.subarray(offset, offset + length) });
22919
- offset += length;
22920
- } else if (wire === 2) {
22921
- const length = decodeVarint(blob, offset);
22922
- if (!length || length[0] > BigInt(blob.length - length[1]))
22923
- return null;
22924
- offset = length[1];
22925
- const end = offset + Number(length[0]);
22926
- fields.push({ number: number4, wire, value: blob.subarray(offset, end) });
22927
- offset = end;
22928
- } else
22929
- return null;
22908
+ #faultSignal = new AbortController();
22909
+ constructor(options) {
22910
+ this.options = options;
22911
+ this.skipPermissions = options.skipPermissions === true;
22930
22912
  }
22931
- return fields;
22932
- }
22933
-
22934
- // dist/native-trajectory-metadata.js
22935
- var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
22936
- function encodeVarint(value) {
22937
- const bytes = [];
22938
- let remaining = value >>> 0;
22939
- while (remaining >= 128) {
22940
- bytes.push(remaining & 127 | 128);
22941
- remaining >>>= 7;
22913
+ get sessionId() {
22914
+ return this.#sessionId;
22942
22915
  }
22943
- bytes.push(remaining);
22944
- return Buffer.from(bytes);
22945
- }
22946
- function encodeLengthDelimited(fieldNumber, payload) {
22947
- return Buffer.concat([
22948
- encodeVarint(fieldNumber << 3 | 2),
22949
- encodeVarint(payload.length),
22950
- Buffer.from(payload)
22951
- ]);
22952
- }
22953
- function minimalTrajectoryMetadataBlob(cascadeId, projectId = DEFAULT_CLI_PROJECT_ID) {
22954
- return Buffer.concat([
22955
- encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")),
22956
- encodeLengthDelimited(18, Buffer.from(projectId, "utf8"))
22957
- ]);
22958
- }
22959
- function minimalRawSummaryBlob(trajectoryId, metadataBlob) {
22960
- return Buffer.concat([
22961
- encodeLengthDelimited(4, Buffer.from(trajectoryId, "utf8")),
22962
- Buffer.from([40, 1]),
22963
- encodeLengthDelimited(17, metadataBlob),
22964
- Buffer.from([176, 1, 4])
22965
- ]);
22966
- }
22967
- function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
22968
- const chunks = [];
22969
- let offset = 0;
22970
- let wroteCascadeId = false;
22971
- let hasProjectId = false;
22972
- while (offset < blob.length) {
22973
- const fieldStart = offset;
22974
- const tagParsed = decodeVarint(blob, offset);
22975
- if (!tagParsed)
22976
- return null;
22977
- const [tag, afterTag] = tagParsed;
22978
- if (tag < 8n || tag > 0xffffffffn)
22979
- return null;
22980
- const fieldNumber = Number(tag >> 3n);
22981
- const wireType = Number(tag & 7n);
22982
- if (fieldNumber === 6 && wireType !== 2)
22983
- return null;
22984
- offset = afterTag;
22985
- if (wireType === 0) {
22986
- const valParsed = decodeVarint(blob, offset);
22987
- if (!valParsed)
22988
- return null;
22989
- offset = valParsed[1];
22990
- } else if (wireType === 1) {
22991
- if (offset + 8 > blob.length)
22992
- return null;
22993
- offset += 8;
22994
- } else if (wireType === 2) {
22995
- const lenParsed = decodeVarint(blob, offset);
22996
- if (!lenParsed)
22997
- return null;
22998
- const [length, afterLen] = lenParsed;
22999
- if (length > BigInt(blob.length - afterLen))
23000
- return null;
23001
- offset = afterLen + Number(length);
23002
- if (fieldNumber === 6) {
23003
- if (!wroteCascadeId) {
23004
- chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23005
- wroteCascadeId = true;
23006
- }
23007
- continue;
23008
- }
23009
- if (fieldNumber === 18)
23010
- hasProjectId = true;
23011
- } else if (wireType === 5) {
23012
- if (offset + 4 > blob.length)
23013
- return null;
23014
- offset += 4;
23015
- } else {
23016
- return null;
23017
- }
23018
- chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
22916
+ get isClosed() {
22917
+ return this.#closed;
23019
22918
  }
23020
- if (!wroteCascadeId) {
23021
- chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
22919
+ setSessionEventHandler(handler) {
22920
+ this.#sessionHandler = handler;
22921
+ if (handler)
22922
+ for (const event of this.#pendingEvents.splice(0))
22923
+ handler(event);
23022
22924
  }
23023
- if (!hasProjectId) {
23024
- chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
22925
+ initialize() {
22926
+ if (this.#closed)
22927
+ return Promise.reject(new AntigravityTransportError("unavailable", "Antigravity ACP is closed"));
22928
+ return this.#initializing ??= this.#start();
23025
22929
  }
23026
- return Buffer.concat(chunks);
23027
- }
23028
-
23029
- // dist/native-turn-boundaries.js
23030
- import { access } from "node:fs/promises";
23031
- async function readNativeTurnCount(dbPath) {
23032
- await access(dbPath);
23033
- const { DatabaseSync } = await import("node:sqlite");
23034
- const db = new DatabaseSync(dbPath, { readOnly: true });
23035
- try {
23036
- const row = db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get();
23037
- return Number(row?.n ?? 0);
23038
- } finally {
23039
- db.close();
22930
+ async #start() {
22931
+ try {
22932
+ const executable = resolveAntigravityExecutable(this.options);
22933
+ if (!executable)
22934
+ throw new AntigravityTransportError("notInstalled", "Antigravity CLI was not found");
22935
+ const invocation = commandInvocation(executable, this.skipPermissions ? ["acp", "--dangerously-skip-permissions"] : ["acp"], this.options.environment ?? process.env);
22936
+ const child = spawn(invocation.command, invocation.arguments, {
22937
+ cwd: this.options.cwd,
22938
+ env: this.options.environment ?? process.env,
22939
+ stdio: ["pipe", "pipe", "pipe"],
22940
+ windowsHide: true,
22941
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
22942
+ });
22943
+ this.#child = child;
22944
+ child.stderr.on("data", (chunk) => {
22945
+ this.#stderrRaw = (this.#stderrRaw + chunk.toString()).slice(-32e3);
22946
+ });
22947
+ child.on("error", (error51) => this.#fault(new AntigravityTransportError(error51.code === "ENOENT" ? "notInstalled" : "unavailable", error51.message, { diagnostic: this.#stderr })));
22948
+ child.on("exit", (code, signal) => this.#fault(new AntigravityTransportError("processExited", `Antigravity ACP exited (code ${code}, signal ${signal})`, { diagnostic: this.#stderr })));
22949
+ child.stdin.on("error", (error51) => this.#fault(this.#error(error51)));
22950
+ const stream = ndJsonStream2(
22951
+ Writable.toWeb(child.stdin),
22952
+ // Keep draining ACP stdout even when the consumer is slow.
22953
+ Readable.toWeb(child.stdout, {
22954
+ strategy: { highWaterMark: Infinity }
22955
+ })
22956
+ );
22957
+ const nativeMethods = /* @__PURE__ */ new Set(["session/request_permission", "elicitation/create"]);
22958
+ stream.readable = stream.readable.pipeThrough(new TransformStream({
22959
+ transform: (message3, controller) => {
22960
+ if ("method" in message3 && message3.method === "session/update") {
22961
+ const params = message3.params;
22962
+ this.#update(params.sessionId, params.update);
22963
+ return;
22964
+ }
22965
+ if ("method" in message3 && nativeMethods.has(message3.method))
22966
+ message3.method = `_antigravity/${message3.method}`;
22967
+ controller.enqueue(message3);
22968
+ }
22969
+ }));
22970
+ const onElicitation = (request) => this.#callback("sessionId" in request ? request.sessionId : void 0, (handler) => handler.onElicitation(request), { action: "cancel" });
22971
+ const client2 = {
22972
+ sessionUpdate: ({ sessionId, update }) => this.#update(sessionId, update),
22973
+ requestPermission: (request) => this.#callback(request.sessionId, (handler) => handler.onPermission(request), {
22974
+ outcome: { outcome: "cancelled" }
22975
+ }),
22976
+ unstable_createElicitation: onElicitation,
22977
+ extMethod: async (method, params) => {
22978
+ if (method === "_antigravity/session/request_permission")
22979
+ return await client2.requestPermission(params);
22980
+ if (method === "_antigravity/elicitation/create")
22981
+ return await onElicitation(params);
22982
+ throw new AntigravityTransportError("unsupported", `Unsupported ACP client method: ${method}`);
22983
+ }
22984
+ };
22985
+ const connection = new ClientSideConnection(() => client2, stream);
22986
+ this.#connection = connection;
22987
+ connection.signal.addEventListener("abort", () => this.#fault(new AntigravityTransportError("processExited", "Antigravity ACP connection closed", {
22988
+ diagnostic: this.#stderr
22989
+ })), { once: true });
22990
+ const response = await this.#request(connection.initialize({
22991
+ protocolVersion: 1,
22992
+ clientCapabilities: { elicitation: { form: {} } }
22993
+ }), "initialize");
22994
+ if (response.protocolVersion !== 1)
22995
+ throw new AntigravityTransportError("protocolError", `Unsupported ACP version ${response.protocolVersion}`);
22996
+ return response;
22997
+ } catch (error51) {
22998
+ await this.close();
22999
+ throw this.#error(error51);
23000
+ }
23040
23001
  }
23041
- }
23042
- function nativeHistoryError(error51) {
23043
- const missing = error51?.code === "ENOENT";
23044
- return {
23045
- code: missing ? "sessionNotFound" : "nativeFailure",
23046
- message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
23047
- retryable: false
23048
- };
23049
- }
23050
-
23051
- // dist/usage-statistics.js
23052
- import { lstat, opendir } from "node:fs/promises";
23053
- import os2 from "node:os";
23054
- import path8 from "node:path";
23055
-
23056
- // ../../harness-adapter/dist/usage-statistics.js
23057
- import { createReadStream } from "node:fs";
23058
- import { createInterface } from "node:readline";
23059
- var HarnessUsageSourceChangedError = class extends Error {
23060
- code = "HARNESS_USAGE_SOURCE_CHANGED";
23061
- /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
23062
- static is(error51) {
23063
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
23002
+ async openSession(input) {
23003
+ await this.initialize();
23004
+ if (this.#closed || !this.#connection || this.#active || this.#opening || this.#sessionId)
23005
+ throw new AntigravityTransportError("unavailable", "Close the current ACP session before opening another");
23006
+ const connection = this.#connection;
23007
+ const buffered = [];
23008
+ this.#opening = buffered;
23009
+ this.#pendingEvents = [];
23010
+ const params = {
23011
+ cwd: input.cwd,
23012
+ mcpServers: [],
23013
+ ...input.additionalDirectories?.length ? { additionalDirectories: input.additionalDirectories } : {},
23014
+ ...input.systemPromptAppend ? { _meta: { antigravity: { systemPrompt: { append: input.systemPromptAppend } } } } : {}
23015
+ };
23016
+ try {
23017
+ let request;
23018
+ if (input.kind === "create")
23019
+ request = connection.newSession(params);
23020
+ else {
23021
+ if (!input.sessionId)
23022
+ throw new AntigravityTransportError("protocolError", "Session ID required for resume");
23023
+ request = connection.resumeSession({ ...params, sessionId: input.sessionId });
23024
+ }
23025
+ const result = await this.#request(request, `session/${input.kind === "create" ? "new" : input.kind}`);
23026
+ const raw = result;
23027
+ const sessionId = raw.sessionId ?? input.sessionId;
23028
+ if (!sessionId)
23029
+ throw new AntigravityTransportError("protocolError", "Antigravity session/new returned no sessionId");
23030
+ this.#sessionId = sessionId;
23031
+ for (const entry of buffered)
23032
+ if (entry.sessionId === sessionId)
23033
+ this.#dispatch(entry.event);
23034
+ return {
23035
+ opened: {
23036
+ sessionId,
23037
+ ...raw.models ? { models: raw.models } : {},
23038
+ ...raw.modes ? { modes: raw.modes } : {},
23039
+ ...raw.configOptions ? { configOptions: raw.configOptions } : {},
23040
+ ...raw._meta?.antigravity?.tier ? { tier: raw._meta.antigravity.tier } : {}
23041
+ }
23042
+ };
23043
+ } finally {
23044
+ this.#opening = null;
23045
+ }
23064
23046
  }
23065
- };
23066
- var MAX_SESSION_ID_LENGTH = 512;
23067
- var MAX_CWD_LENGTH = 4096;
23068
- var MAX_SESSION_TITLE_LENGTH = 200;
23069
- function usageSessionTitle(value) {
23070
- if (typeof value !== "string")
23071
- return void 0;
23072
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
23073
- if (!normalized)
23074
- return void 0;
23075
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
23076
- return normalized;
23077
- let title = "";
23078
- for (const character of normalized) {
23079
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
23080
- break;
23081
- title += character;
23047
+ async setMode(modeId) {
23048
+ const { connection, sessionId } = this.#session();
23049
+ await this.#request(connection.setSessionMode({ sessionId, modeId }), "session/set_mode");
23082
23050
  }
23083
- return `${title.trimEnd()}…`;
23084
- }
23085
- function sessionIdOk(value) {
23086
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
23087
- }
23088
- function cwdOk(value) {
23089
- 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("\\\\"));
23090
- }
23091
- function withUsageSession(entry, session) {
23092
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
23093
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
23094
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
23095
- if (sessionId === void 0 && cwd === void 0)
23096
- return entry;
23097
- return {
23098
- ...entry,
23099
- ...sessionId !== void 0 ? { sessionId } : {},
23100
- ...cwd !== void 0 ? { cwd } : {},
23101
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
23102
- };
23103
- }
23104
- async function* jsonlRecords(file2, marker, signal) {
23105
- const lines = createInterface({
23106
- input: createReadStream(file2, { encoding: "utf8", signal }),
23107
- crlfDelay: Infinity
23108
- });
23109
- for await (const line of lines) {
23110
- if (!line.includes(marker))
23111
- continue;
23112
- let value;
23051
+ async setConfigOption(configId, value) {
23052
+ const { connection, sessionId } = this.#session();
23053
+ const response = await this.#request(connection.setSessionConfigOption({ sessionId, configId, value }), "session/set_config_option");
23054
+ return response.configOptions;
23055
+ }
23056
+ async prompt(parts, handler) {
23057
+ const { connection, sessionId } = this.#session();
23058
+ if (this.#active)
23059
+ throw new AntigravityTransportError("unavailable", "An ACP prompt is already active");
23060
+ this.#active = handler;
23061
+ this.#acceptCallbacks = true;
23062
+ const interrupted = new AbortController();
23063
+ this.#promptInterrupted = interrupted;
23113
23064
  try {
23114
- value = JSON.parse(line);
23115
- } catch {
23116
- continue;
23065
+ return await this.#request(connection.prompt({ sessionId, prompt: [...parts] }), "session/prompt", null, interrupted.signal);
23066
+ } finally {
23067
+ this.#clearCallbacks();
23068
+ this.#acceptCallbacks = false;
23069
+ this.#active = null;
23070
+ this.#promptInterrupted = null;
23117
23071
  }
23118
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
23119
- yield value;
23072
+ }
23073
+ async cancel() {
23074
+ const { connection, sessionId } = this.#session();
23075
+ this.#acceptCallbacks = false;
23076
+ this.#clearCallbacks();
23077
+ await this.#request(connection.cancel({ sessionId }), "session/cancel");
23078
+ }
23079
+ async closeSession() {
23080
+ const sessionId = this.#sessionId;
23081
+ this.#sessionId = null;
23082
+ this.#acceptCallbacks = false;
23083
+ this.#promptInterrupted?.abort(new AntigravityTransportError("unavailable", "ACP session closed"));
23084
+ this.#active = null;
23085
+ this.#pendingEvents = [];
23086
+ this.#clearCallbacks();
23087
+ if (sessionId && this.#connection)
23088
+ await this.#request(this.#connection.closeSession({ sessionId }), "session/close", this.options.closeTimeoutMs ?? 2e3);
23089
+ }
23090
+ close() {
23091
+ if (this.#closing)
23092
+ return this.#closing;
23093
+ this.#closed = true;
23094
+ return this.#closing = this.#shutdown();
23095
+ }
23096
+ async #shutdown() {
23097
+ try {
23098
+ await this.closeSession();
23099
+ } catch (error51) {
23100
+ this.#stderrRaw = `${this.#stderrRaw}
23101
+ ${this.#error(error51).message}`.slice(-32e3);
23102
+ }
23103
+ this.#faultSignal.abort(new AntigravityTransportError("unavailable", "Antigravity ACP closed"));
23104
+ this.#opening = null;
23105
+ this.#sessionHandler = null;
23106
+ const child = this.#child;
23107
+ if (child && child.exitCode === null && child.signalCode === null && child.pid) {
23108
+ const exited = new Promise((resolve) => child.once("exit", () => resolve()));
23109
+ const timeout = this.options.closeTimeoutMs ?? 2e3;
23110
+ const term = setTimeout(() => child.kill("SIGTERM"), Math.max(1, timeout / 2));
23111
+ const kill = setTimeout(() => child.kill("SIGKILL"), Math.max(2, timeout));
23112
+ child.stdin.end();
23113
+ try {
23114
+ await exited;
23115
+ } finally {
23116
+ clearTimeout(term);
23117
+ clearTimeout(kill);
23118
+ }
23119
+ }
23120
+ this.#connection = null;
23121
+ this.#child = null;
23122
+ }
23123
+ #session() {
23124
+ if (this.#closed || !this.#connection || !this.#sessionId)
23125
+ throw new AntigravityTransportError("unavailable", "Antigravity ACP session is unavailable");
23126
+ return { connection: this.#connection, sessionId: this.#sessionId };
23127
+ }
23128
+ #update(sessionId, raw) {
23129
+ if (this.#closed)
23130
+ return;
23131
+ const event = projectAcpSessionUpdate(raw);
23132
+ if (!event)
23133
+ return;
23134
+ if (this.#opening) {
23135
+ this.#opening.push({ sessionId, event });
23136
+ return;
23137
+ }
23138
+ if (sessionId === this.#sessionId)
23139
+ this.#dispatch(event);
23140
+ }
23141
+ #dispatch(event) {
23142
+ if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type)) {
23143
+ if (this.#sessionHandler)
23144
+ this.#sessionHandler(event);
23145
+ else
23146
+ this.#pendingEvents.push(event);
23147
+ } else
23148
+ this.#active?.onEvent(event);
23149
+ }
23150
+ async #callback(sessionId, invoke, cancelled) {
23151
+ const active = this.#active;
23152
+ if (!active || !this.#acceptCallbacks || sessionId !== this.#sessionId || this.#closed)
23153
+ return cancelled;
23154
+ let cancel;
23155
+ const cancellation = new Promise((resolve) => {
23156
+ cancel = () => resolve(cancelled);
23157
+ });
23158
+ this.#callbacks.add(cancel);
23159
+ try {
23160
+ return await Promise.race([invoke(active), cancellation]);
23161
+ } finally {
23162
+ this.#callbacks.delete(cancel);
23163
+ }
23164
+ }
23165
+ #clearCallbacks() {
23166
+ for (const cancel of this.#callbacks)
23167
+ cancel();
23168
+ this.#callbacks.clear();
23169
+ }
23170
+ async #request(promise2, operation, timeoutMs = this.options.commandTimeoutMs ?? 3e4, signal) {
23171
+ let timer;
23172
+ let abort;
23173
+ const signals = [this.#faultSignal.signal, ...signal ? [signal] : []];
23174
+ const interrupted = new Promise((_, reject) => {
23175
+ abort = () => reject(signal?.aborted ? signal.reason : this.#faultSignal.signal.reason);
23176
+ if (signals.some((candidate) => candidate.aborted))
23177
+ abort();
23178
+ else
23179
+ for (const candidate of signals)
23180
+ candidate.addEventListener("abort", abort, { once: true });
23181
+ if (timeoutMs !== null)
23182
+ timer = setTimeout(() => reject(new AntigravityTransportError("unavailable", `${operation} timed out after ${timeoutMs}ms`, { diagnostic: this.#stderr })), timeoutMs);
23183
+ });
23184
+ try {
23185
+ return await Promise.race([promise2, interrupted]);
23186
+ } catch (error51) {
23187
+ const normalized = this.#error(error51);
23188
+ if (normalized.kind === "unavailable" && normalized.message.includes("timed out"))
23189
+ void this.close();
23190
+ throw normalized;
23191
+ } finally {
23192
+ clearTimeout(timer);
23193
+ for (const candidate of signals)
23194
+ candidate.removeEventListener("abort", abort);
23120
23195
  }
23121
23196
  }
23197
+ #error(error51) {
23198
+ if (error51 instanceof AntigravityTransportError)
23199
+ return error51;
23200
+ const message3 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
23201
+ const code = error51?.code;
23202
+ return new AntigravityTransportError(code === -32e3 || /auth|login|sign[ -]?in|unauthenticated/iu.test(message3) ? "authenticationRequired" : "unavailable", message3, { cause: error51, diagnostic: this.#stderr });
23203
+ }
23204
+ #fault(error51) {
23205
+ if (this.#closed || this.#faultSignal.signal.aborted)
23206
+ return;
23207
+ this.#faultSignal.abort(error51);
23208
+ this.#clearCallbacks();
23209
+ void this.close();
23210
+ this.options.onFault?.(error51);
23211
+ }
23212
+ };
23213
+
23214
+ // dist/acp-usage.js
23215
+ import { createReadStream } from "node:fs";
23216
+ import path7 from "node:path";
23217
+ import { createInterface } from "node:readline";
23218
+
23219
+ // dist/native-request-timing.js
23220
+ import path6 from "node:path";
23221
+
23222
+ // dist/native-protobuf.js
23223
+ function decodeVarint(buffer, start) {
23224
+ let value = 0n;
23225
+ for (let index = 0; index < 10; index++) {
23226
+ const byte = buffer[start + index];
23227
+ if (byte === void 0 || index === 9 && byte > 1)
23228
+ return null;
23229
+ value |= BigInt(byte & 127) << BigInt(index * 7);
23230
+ if ((byte & 128) === 0)
23231
+ return [value, start + index + 1];
23232
+ }
23233
+ return null;
23234
+ }
23235
+ function readProtoFields(blob) {
23236
+ const fields = [];
23237
+ let offset = 0;
23238
+ while (offset < blob.length) {
23239
+ if (fields.length >= 1e4)
23240
+ return null;
23241
+ const tag = decodeVarint(blob, offset);
23242
+ if (!tag || tag[0] < 8n || tag[0] > 0xffffffffn)
23243
+ return null;
23244
+ offset = tag[1];
23245
+ const number4 = Number(tag[0] >> 3n);
23246
+ const wire = Number(tag[0] & 7n);
23247
+ if (wire === 0) {
23248
+ const value = decodeVarint(blob, offset);
23249
+ if (!value)
23250
+ return null;
23251
+ fields.push({ number: number4, wire, value: value[0] });
23252
+ offset = value[1];
23253
+ } else if (wire === 1 || wire === 5) {
23254
+ const length = wire === 1 ? 8 : 4;
23255
+ if (offset + length > blob.length)
23256
+ return null;
23257
+ fields.push({ number: number4, wire, value: blob.subarray(offset, offset + length) });
23258
+ offset += length;
23259
+ } else if (wire === 2) {
23260
+ const length = decodeVarint(blob, offset);
23261
+ if (!length || length[0] > BigInt(blob.length - length[1]))
23262
+ return null;
23263
+ offset = length[1];
23264
+ const end = offset + Number(length[0]);
23265
+ fields.push({ number: number4, wire, value: blob.subarray(offset, end) });
23266
+ offset = end;
23267
+ } else
23268
+ return null;
23269
+ }
23270
+ return fields;
23122
23271
  }
23123
- function nativeTimeMs(value) {
23124
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
23125
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
23126
- }
23127
-
23128
- // dist/acp-usage.js
23129
- import { createReadStream as createReadStream2 } from "node:fs";
23130
- import path7 from "node:path";
23131
- import { createInterface as createInterface2 } from "node:readline";
23132
23272
 
23133
23273
  // dist/native-request-timing.js
23134
- import path6 from "node:path";
23135
23274
  var MAX_METADATA_BYTES = 8 * 1024 * 1024;
23136
23275
  var NANOSECONDS_PER_MS = 1000000n;
23137
23276
  var MAX_MS = BigInt(Number.MAX_SAFE_INTEGER);
@@ -23388,9 +23527,6 @@ var AntigravitySessionUsageTracker = class {
23388
23527
  this.#home = options.homedir;
23389
23528
  this.#expectedInitialTurns = options.expectedInitialTurns ?? 0;
23390
23529
  this.#file = path7.join(options.homedir, ".gemini", "antigravity-cli", "brain", options.nativeSessionId, ".system_generated", "logs", "transcript.jsonl");
23391
- if (options.initialContextUsedTokens !== void 0 && options.initialContextWindowTokens !== void 0) {
23392
- this.recordContextWindow(options.initialContextUsedTokens, options.initialContextWindowTokens);
23393
- }
23394
23530
  }
23395
23531
  currentUsage() {
23396
23532
  const recorded = [...this.#requests].sort(([left], [right]) => left - right).map(([, request]) => request);
@@ -23558,8 +23694,8 @@ var AntigravitySessionUsageTracker = class {
23558
23694
  }
23559
23695
  async #read(signal, withTimings = true) {
23560
23696
  signal?.throwIfAborted();
23561
- const stream = createReadStream2(this.#file, { encoding: "utf8", signal });
23562
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
23697
+ const stream = createReadStream(this.#file, { encoding: "utf8", signal });
23698
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
23563
23699
  const result = {
23564
23700
  steps: /* @__PURE__ */ new Map(),
23565
23701
  toolCallSteps: /* @__PURE__ */ new Set(),
@@ -23626,771 +23762,566 @@ var AntigravitySessionUsageTracker = class {
23626
23762
  }
23627
23763
  };
23628
23764
 
23629
- // dist/usage-statistics.js
23630
- function count3(value) {
23631
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
23632
- }
23633
- function antigravityHome(environment) {
23634
- return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
23635
- }
23636
- function transcriptPath(brainRoot, conversationId) {
23637
- return path8.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
23638
- }
23639
- function isMissing(error51) {
23640
- const code = error51?.code;
23641
- return code === "ENOENT" || code === "ENOTDIR";
23642
- }
23643
- async function lstatIfPresent(target2) {
23644
- try {
23645
- return await lstat(target2);
23646
- } catch (error51) {
23647
- if (isMissing(error51))
23648
- return null;
23649
- throw error51;
23650
- }
23651
- }
23652
- async function transcriptFingerprint(file2) {
23653
- const logs = path8.dirname(file2);
23654
- for (const directory of [path8.dirname(logs), logs]) {
23655
- if (!(await lstatIfPresent(directory))?.isDirectory())
23656
- return null;
23657
- }
23658
- const info = await lstatIfPresent(file2);
23659
- return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
23660
- }
23661
- async function listTranscripts(brainRoot, signal) {
23662
- signal.throwIfAborted();
23663
- const conversations = await opendir(brainRoot).catch((error51) => {
23664
- if (error51.code === "ENOENT")
23665
- return null;
23666
- throw error51;
23667
- });
23668
- if (!conversations)
23669
- return [];
23670
- const sources = [];
23671
- for await (const entry of conversations) {
23672
- signal.throwIfAborted();
23673
- if (!entry.isDirectory())
23674
- continue;
23675
- const file2 = transcriptPath(brainRoot, entry.name);
23676
- const fingerprint = await transcriptFingerprint(file2);
23677
- if (fingerprint)
23678
- sources.push({ id: file2, fingerprint });
23679
- }
23680
- return sources;
23681
- }
23682
- async function readAntigravityUsage(file2, signal) {
23683
- const sessionId = path8.basename(path8.resolve(file2, "..", "..", ".."));
23684
- const requests = /* @__PURE__ */ new Map();
23685
- for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
23686
- if (record4.type !== "PLANNER_RESPONSE")
23687
- continue;
23688
- const step = count3(record4.step_index);
23689
- const input = count3(record4.input_tokens);
23690
- const output = count3(record4.output_tokens);
23691
- const cached2 = count3(record4.cache_read_tokens);
23692
- const at = nativeTimeMs(record4.created_at);
23693
- if (step === null || input === null || output === null || at === null)
23694
- continue;
23695
- const identity2 = normalizeAntigravityUsageModel(record4.model);
23696
- requests.set(step, withUsageSession({
23697
- id: `${String(record4.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
23698
- occurredAtMs: at,
23699
- ...identity2,
23700
- inputTokens: input + (cached2 ?? 0),
23701
- ...cached2 !== null ? {
23702
- cachedInputTokens: cached2,
23703
- ...hasImplicitZeroCacheWrite(identity2) ? { cacheWriteInputTokens: 0 } : {}
23704
- } : {},
23705
- outputTokens: output
23706
- }, { sessionId }));
23707
- }
23708
- return [...requests.values()];
23709
- }
23710
- function createAntigravityUsageStatistics(environment) {
23711
- const brainRoot = nativeBrainRoot(antigravityHome(environment));
23712
- let listed = /* @__PURE__ */ new Map();
23713
- return Object.freeze({
23714
- async listSources(signal) {
23715
- const sources = await listTranscripts(brainRoot, signal);
23716
- listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
23717
- return sources;
23718
- },
23719
- async readSource(id, signal) {
23720
- const expected = listed.get(id);
23721
- let entries;
23722
- try {
23723
- entries = await readAntigravityUsage(id, signal);
23724
- } catch (error51) {
23725
- if (expected !== void 0 && isMissing(error51)) {
23726
- throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
23727
- }
23728
- throw error51;
23729
- }
23730
- if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
23731
- throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
23732
- }
23733
- return entries;
23734
- }
23735
- });
23765
+ // dist/delegation.js
23766
+ var DELEGATION_ENVIRONMENT_KEYS = [
23767
+ "CODEXHOST_CLI_PATH",
23768
+ "CODEXHOST_RUNTIME_ENDPOINT",
23769
+ "CODEXHOST_RUNTIME_TOKEN",
23770
+ "CODEXHOST_THREAD_ID"
23771
+ ];
23772
+ var ANTIGRAVITY_DELEGATION_INSTRUCTIONS = `This Antigravity Session runs inside codexhost.
23773
+ When the user requests cross-Harness delegation, use the executable specified by the CODEXHOST_CLI_PATH environment variable through your native shell tool. Start with --help and harness list, then use delegate start and thread send/read/wait/cancel as documented. Use --format compact for results. Keep the inherited CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID environment variables for every call; they identify this Runtime and parent Thread. Never print their values, substitute another executable, or delegate without user authorization. Native Antigravity subagents are separate from cross-Harness delegation.`;
23774
+ function antigravityDelegationInstructions(environment) {
23775
+ return DELEGATION_ENVIRONMENT_KEYS.every((key) => environment[key]) ? ANTIGRAVITY_DELEGATION_INSTRUCTIONS : void 0;
23736
23776
  }
23737
23777
 
23738
23778
  // dist/fork.js
23739
- function nativeConversationDbPath(id, home = os3.homedir()) {
23740
- return path9.join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
23741
- }
23742
- function nativeConversationSummariesDbPath(home = os3.homedir()) {
23743
- return path9.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
23779
+ import { randomUUID } from "node:crypto";
23780
+ import { access as access2, cp, mkdir, open, rm as rm2 } from "node:fs/promises";
23781
+ import os3 from "node:os";
23782
+ import path9 from "node:path";
23783
+
23784
+ // dist/native-trajectory-metadata.js
23785
+ var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
23786
+ function encodeVarint(value) {
23787
+ const bytes = [];
23788
+ let remaining = value >>> 0;
23789
+ while (remaining >= 128) {
23790
+ bytes.push(remaining & 127 | 128);
23791
+ remaining >>>= 7;
23792
+ }
23793
+ bytes.push(remaining);
23794
+ return Buffer.from(bytes);
23744
23795
  }
23745
- function nativeBrainRoot(home = os3.homedir()) {
23746
- return path9.join(home, ".gemini", "antigravity-cli", "brain");
23796
+ function encodeLengthDelimited(fieldNumber, payload) {
23797
+ return Buffer.concat([
23798
+ encodeVarint(fieldNumber << 3 | 2),
23799
+ encodeVarint(payload.length),
23800
+ Buffer.from(payload)
23801
+ ]);
23747
23802
  }
23748
- function nativeBrainDirPath(id, home = os3.homedir()) {
23749
- return path9.join(nativeBrainRoot(home), id);
23803
+ function minimalTrajectoryMetadataBlob(cascadeId, projectId = DEFAULT_CLI_PROJECT_ID) {
23804
+ return Buffer.concat([
23805
+ encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")),
23806
+ encodeLengthDelimited(18, Buffer.from(projectId, "utf8"))
23807
+ ]);
23750
23808
  }
23751
- function validNativeSessionRef(ref, harnessId2) {
23752
- return nativeSessionRefSchema.safeParse(ref).success && ref.harnessId === harnessId2 && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(ref.nativeSessionId);
23809
+ function minimalRawSummaryBlob(trajectoryId, metadataBlob) {
23810
+ return Buffer.concat([
23811
+ encodeLengthDelimited(4, Buffer.from(trajectoryId, "utf8")),
23812
+ Buffer.from([40, 1]),
23813
+ encodeLengthDelimited(17, metadataBlob),
23814
+ Buffer.from([176, 1, 4])
23815
+ ]);
23753
23816
  }
23754
- async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os3.homedir()) {
23755
- if (![sourceId, derivedId].every((id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id)))
23756
- throw new Error("Invalid native conversation ID");
23757
- const home = typeof retainedTurnsCountOrHome === "string" ? retainedTurnsCountOrHome : homeOption;
23758
- const retained = typeof retainedTurnsCountOrHome === "number" ? retainedTurnsCountOrHome : void 0;
23759
- const sourcePath = nativeConversationDbPath(sourceId, home);
23760
- const targetPath2 = nativeConversationDbPath(derivedId, home);
23761
- await access2(sourcePath);
23762
- const { DatabaseSync, backup } = await import("node:sqlite");
23763
- const source = new DatabaseSync(sourcePath, { readOnly: true });
23764
- let owned = false;
23765
- try {
23766
- source.exec("BEGIN");
23767
- const count4 = Number(source.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
23768
- if (retained !== void 0 && (!Number.isSafeInteger(retained) || retained < 0 || retained > count4))
23769
- throw new Error("Invalid retained native Turn count");
23770
- await mkdir(path9.dirname(targetPath2), { recursive: true });
23771
- const reservation = await open(targetPath2, "wx");
23772
- owned = true;
23773
- await reservation.close();
23774
- await backup(source, targetPath2);
23775
- const target2 = new DatabaseSync(targetPath2);
23776
- try {
23777
- target2.exec("BEGIN IMMEDIATE");
23778
- target2.prepare("UPDATE trajectory_meta SET cascade_id = ?").run(derivedId);
23779
- const row = target2.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get();
23780
- const blob = row?.data instanceof Uint8Array ? rewriteTrajectoryMetadataCascadeId(row.data, derivedId) : minimalTrajectoryMetadataBlob(derivedId);
23781
- if (!blob)
23782
- throw new Error("Invalid native trajectory metadata");
23783
- target2.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(blob);
23784
- if (retained !== void 0 && retained < count4) {
23785
- const boundary = target2.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
23786
- const cutoff = retained === 0 ? 0 : Number(boundary?.idx);
23787
- target2.prepare("DELETE FROM steps WHERE idx >= ?").run(cutoff);
23788
- for (const table of [
23789
- "gen_metadata",
23790
- "executor_metadata",
23791
- "parent_references",
23792
- "battle_mode_infos"
23793
- ]) {
23794
- if (target2.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table))
23795
- target2.prepare(`DELETE FROM ${table} WHERE idx >= ?`).run(cutoff);
23817
+ function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
23818
+ const chunks = [];
23819
+ let offset = 0;
23820
+ let wroteCascadeId = false;
23821
+ let hasProjectId = false;
23822
+ while (offset < blob.length) {
23823
+ const fieldStart = offset;
23824
+ const tagParsed = decodeVarint(blob, offset);
23825
+ if (!tagParsed)
23826
+ return null;
23827
+ const [tag, afterTag] = tagParsed;
23828
+ if (tag < 8n || tag > 0xffffffffn)
23829
+ return null;
23830
+ const fieldNumber = Number(tag >> 3n);
23831
+ const wireType = Number(tag & 7n);
23832
+ if (fieldNumber === 6 && wireType !== 2)
23833
+ return null;
23834
+ offset = afterTag;
23835
+ if (wireType === 0) {
23836
+ const valParsed = decodeVarint(blob, offset);
23837
+ if (!valParsed)
23838
+ return null;
23839
+ offset = valParsed[1];
23840
+ } else if (wireType === 1) {
23841
+ if (offset + 8 > blob.length)
23842
+ return null;
23843
+ offset += 8;
23844
+ } else if (wireType === 2) {
23845
+ const lenParsed = decodeVarint(blob, offset);
23846
+ if (!lenParsed)
23847
+ return null;
23848
+ const [length, afterLen] = lenParsed;
23849
+ if (length > BigInt(blob.length - afterLen))
23850
+ return null;
23851
+ offset = afterLen + Number(length);
23852
+ if (fieldNumber === 6) {
23853
+ if (!wroteCascadeId) {
23854
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23855
+ wroteCascadeId = true;
23796
23856
  }
23857
+ continue;
23797
23858
  }
23798
- target2.exec("COMMIT");
23799
- } finally {
23800
- target2.close();
23859
+ if (fieldNumber === 18)
23860
+ hasProjectId = true;
23861
+ } else if (wireType === 5) {
23862
+ if (offset + 4 > blob.length)
23863
+ return null;
23864
+ offset += 4;
23865
+ } else {
23866
+ return null;
23801
23867
  }
23802
- await registerDerivedSummary(sourceId, derivedId, home);
23803
- return true;
23804
- } catch (error51) {
23805
- if (owned)
23806
- await removeDerivedDb(derivedId, home);
23807
- throw error51;
23808
- } finally {
23809
- source.close();
23868
+ chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
23810
23869
  }
23811
- }
23812
- async function registerDerivedSummary(sourceId, derivedId, home) {
23813
- const summaryPath = nativeConversationSummariesDbPath(home);
23814
- try {
23815
- await access2(summaryPath);
23816
- } catch (error51) {
23817
- if (error51.code === "ENOENT")
23818
- return;
23819
- throw error51;
23870
+ if (!wroteCascadeId) {
23871
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23820
23872
  }
23821
- const { DatabaseSync } = await import("node:sqlite");
23822
- const summaries = new DatabaseSync(summaryPath);
23823
- try {
23824
- const template = summaries.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?").get(sourceId);
23825
- if (!template)
23826
- return;
23827
- const derived = new DatabaseSync(nativeConversationDbPath(derivedId, home), { readOnly: true });
23828
- let row;
23829
- try {
23830
- const metadata = derived.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get()?.data;
23831
- const trajectoryId = derived.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get()?.trajectory_id;
23832
- row = {
23833
- ...template,
23834
- conversation_id: derivedId,
23835
- status: "CASCADE_RUN_STATUS_IDLE",
23836
- step_count: Number(derived.prepare("SELECT count(*) AS n FROM steps").get()?.n),
23837
- last_user_input_step_index: Number(derived.prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = 14").get()?.idx ?? -1),
23838
- not_fully_idle: 0,
23839
- killed: 0,
23840
- last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
23841
- raw_summary: minimalRawSummaryBlob(String(trajectoryId), Buffer.from(metadata))
23842
- };
23843
- } finally {
23844
- derived.close();
23845
- }
23846
- const columns = Object.keys(template);
23847
- summaries.prepare(`INSERT INTO conversation_summaries (${columns.map((name) => `"${name.replaceAll('"', '""')}"`).join(",")}) VALUES (${columns.map(() => "?").join(",")})`).run(...columns.map((name) => row[name] ?? null));
23848
- } finally {
23849
- summaries.close();
23873
+ if (!hasProjectId) {
23874
+ chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
23850
23875
  }
23876
+ return Buffer.concat(chunks);
23851
23877
  }
23852
- async function removeDerivedSummary(id, home) {
23853
- try {
23854
- await access2(nativeConversationSummariesDbPath(home));
23855
- } catch (error51) {
23856
- if (error51.code === "ENOENT")
23857
- return;
23858
- throw error51;
23859
- }
23878
+
23879
+ // dist/native-turn-boundaries.js
23880
+ import { access } from "node:fs/promises";
23881
+ async function readNativeTurnCount(dbPath) {
23882
+ await access(dbPath);
23860
23883
  const { DatabaseSync } = await import("node:sqlite");
23861
- const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
23884
+ const db = new DatabaseSync(dbPath, { readOnly: true });
23862
23885
  try {
23863
- db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
23886
+ const row = db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get();
23887
+ return Number(row?.n ?? 0);
23864
23888
  } finally {
23865
23889
  db.close();
23866
23890
  }
23867
23891
  }
23868
- async function removeDerivedDb(id, home) {
23869
- const file2 = nativeConversationDbPath(id, home);
23870
- await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
23871
- }
23872
- async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedir()) {
23873
- try {
23874
- await access2(nativeBrainDirPath(sourceId, home));
23875
- } catch (error51) {
23876
- if (error51.code === "ENOENT")
23877
- return false;
23878
- throw error51;
23879
- }
23880
- await cp(nativeBrainDirPath(sourceId, home), nativeBrainDirPath(derivedId, home), {
23881
- recursive: true,
23882
- errorOnExist: true,
23883
- force: false,
23884
- filter: (source) => path9.basename(source) !== ".system_generated"
23885
- });
23886
- return true;
23887
- }
23888
- async function openDerivedAntigravitySession(options, input, sourceRef, retained) {
23889
- const environment = { ...options.adapterEnvironment, ...input.environment };
23890
- const home = antigravityHome(environment);
23891
- const derivedId = randomUUID();
23892
- let cloned = false;
23893
- try {
23894
- await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home);
23895
- cloned = true;
23896
- await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
23897
- const result = await options.openSession({
23898
- ...input,
23899
- environment,
23900
- nativeRef: { ...sourceRef, nativeSessionId: derivedId }
23901
- });
23902
- if (result.ok)
23903
- return result;
23904
- const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
23905
- return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
23906
- } catch (error51) {
23907
- const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
23908
- return {
23909
- ok: false,
23910
- error: {
23911
- ...nativeHistoryError(error51),
23912
- ...cleanupFailure ? { diagnostic: cleanupFailure } : {}
23913
- }
23914
- };
23915
- }
23916
- async function cleanup() {
23917
- if (!cloned)
23918
- return;
23919
- await Promise.all([
23920
- removeDerivedDb(derivedId, home),
23921
- rm2(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
23922
- removeDerivedSummary(derivedId, home)
23923
- ]);
23924
- }
23925
- }
23926
- async function forkAntigravitySession(options) {
23927
- const { input, harnessId: harnessId2 } = options;
23928
- if (!validNativeSessionRef(input.sourceRef, harnessId2))
23929
- return {
23930
- ok: false,
23931
- error: {
23932
- code: "invalidRequest",
23933
- message: "Invalid Antigravity source Native Session",
23934
- retryable: false
23935
- }
23936
- };
23937
- const checkpoint = nativeCheckpointRefSchema.safeParse(input.checkpoint);
23938
- if (!checkpoint.success || checkpoint.data.harnessId !== harnessId2 || checkpoint.data.nativeSessionId !== input.sourceRef.nativeSessionId)
23939
- return checkpointError();
23940
- if (options.sourceSession?.isActive)
23941
- return {
23942
- ok: false,
23943
- error: {
23944
- code: "sessionBusy",
23945
- message: "Source Session is busy",
23946
- retryable: true
23947
- }
23948
- };
23949
- const match = /^turn-(0|[1-9]\d*)$/u.exec(checkpoint.data.checkpointId);
23950
- if (!match)
23951
- return checkpointError();
23952
- try {
23953
- const count4 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
23954
- const index = Number(match[1]);
23955
- if (!Number.isSafeInteger(index) || index >= count4)
23956
- return checkpointError();
23957
- return openDerivedAntigravitySession(options, {
23958
- kind: "resume",
23959
- nativeRef: input.sourceRef,
23960
- cwd: input.cwd,
23961
- ...input.environment ? { environment: input.environment } : {}
23962
- }, input.sourceRef, index + 1);
23963
- } catch (error51) {
23964
- return { ok: false, error: nativeHistoryError(error51) };
23965
- }
23966
- }
23967
- function checkpointError() {
23892
+ function nativeHistoryError(error51) {
23893
+ const missing = error51?.code === "ENOENT";
23968
23894
  return {
23969
- ok: false,
23970
- error: {
23971
- code: "checkpointNotFound",
23972
- message: "Antigravity native Turn checkpoint not found",
23973
- retryable: false
23974
- }
23895
+ code: missing ? "sessionNotFound" : "nativeFailure",
23896
+ message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
23897
+ retryable: false
23975
23898
  };
23976
23899
  }
23977
23900
 
23978
- // dist/native-replay.js
23979
- async function readNativeReplaySize(sessionId, home) {
23980
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
23981
- throw new AntigravityTransportError("protocolError", "Invalid native Session ID");
23982
- const { DatabaseSync } = await import("node:sqlite");
23983
- const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
23984
- const size = { users: 0, text: 0, thought: 0, tools: 0 };
23985
- try {
23986
- for (const row of db.prepare("SELECT step_type, step_payload FROM steps WHERE step_type IN (14, 15) ORDER BY idx").iterate()) {
23987
- if (row.step_type === 14) {
23988
- size.users++;
23989
- continue;
23990
- }
23991
- const planner = row.step_payload instanceof Uint8Array ? readProtoFields(row.step_payload)?.find((field3) => field3.number === 20)?.value : void 0;
23992
- const fields = planner instanceof Uint8Array ? readProtoFields(planner) : null;
23993
- if (!fields)
23994
- throw new AntigravityTransportError("protocolError", "Cannot verify Antigravity history replay");
23995
- for (const field3 of fields) {
23996
- if (!(field3.value instanceof Uint8Array))
23997
- continue;
23998
- if (field3.number === 1)
23999
- size.text += Buffer.from(field3.value).toString("utf8").length;
24000
- if (field3.number === 3)
24001
- size.thought += Buffer.from(field3.value).toString("utf8").length;
24002
- if (field3.number === 7)
24003
- size.tools++;
24004
- }
24005
- }
24006
- return size;
24007
- } finally {
24008
- db.close();
23901
+ // dist/usage-statistics.js
23902
+ import { lstat, opendir } from "node:fs/promises";
23903
+ import os2 from "node:os";
23904
+ import path8 from "node:path";
23905
+
23906
+ // ../../harness-adapter/dist/usage-statistics.js
23907
+ import { createReadStream as createReadStream2 } from "node:fs";
23908
+ import { createInterface as createInterface2 } from "node:readline";
23909
+ var HarnessUsageSourceChangedError = class extends Error {
23910
+ code = "HARNESS_USAGE_SOURCE_CHANGED";
23911
+ /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
23912
+ static is(error51) {
23913
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
23914
+ }
23915
+ };
23916
+ var MAX_SESSION_ID_LENGTH = 512;
23917
+ var MAX_CWD_LENGTH = 4096;
23918
+ var MAX_SESSION_TITLE_LENGTH = 200;
23919
+ function usageSessionTitle(value) {
23920
+ if (typeof value !== "string")
23921
+ return void 0;
23922
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
23923
+ if (!normalized)
23924
+ return void 0;
23925
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
23926
+ return normalized;
23927
+ let title = "";
23928
+ for (const character of normalized) {
23929
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
23930
+ break;
23931
+ title += character;
24009
23932
  }
23933
+ return `${title.trimEnd()}…`;
23934
+ }
23935
+ function sessionIdOk(value) {
23936
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
23937
+ }
23938
+ function cwdOk(value) {
23939
+ 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("\\\\"));
24010
23940
  }
24011
- function nativeReplayCompletion(expected) {
24012
- const received = {
24013
- users: 0,
24014
- text: 0,
24015
- thought: 0,
24016
- tools: 0,
24017
- usage: false,
24018
- sessionInfo: false
23941
+ function withUsageSession(entry, session) {
23942
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
23943
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
23944
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
23945
+ if (sessionId === void 0 && cwd === void 0)
23946
+ return entry;
23947
+ return {
23948
+ ...entry,
23949
+ ...sessionId !== void 0 ? { sessionId } : {},
23950
+ ...cwd !== void 0 ? { cwd } : {},
23951
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
24019
23952
  };
24020
- let resolve;
24021
- const complete = new Promise((done) => {
24022
- resolve = done;
23953
+ }
23954
+ async function* jsonlRecords(file2, marker, signal) {
23955
+ const lines = createInterface2({
23956
+ input: createReadStream2(file2, { encoding: "utf8", signal }),
23957
+ crlfDelay: Infinity
24023
23958
  });
24024
- const check2 = () => {
24025
- if (received.users === expected.users && received.text === expected.text && received.thought === expected.thought && received.tools === expected.tools && received.usage && received.sessionInfo)
24026
- resolve();
24027
- };
24028
- check2();
24029
- return {
24030
- complete,
24031
- observe(event) {
24032
- if (event.type === "user.text")
24033
- received.users++;
24034
- if (event.type === "agent.text")
24035
- received.text += event.text.length;
24036
- if (event.type === "agent.thought")
24037
- received.thought += event.text.length;
24038
- if (event.type === "tool.call")
24039
- received.tools++;
24040
- if (event.type === "usage.context")
24041
- received.usage = true;
24042
- if (event.type === "session.info")
24043
- received.sessionInfo = true;
24044
- check2();
23959
+ for await (const line of lines) {
23960
+ if (!line.includes(marker))
23961
+ continue;
23962
+ let value;
23963
+ try {
23964
+ value = JSON.parse(line);
23965
+ } catch {
23966
+ continue;
24045
23967
  }
24046
- };
23968
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
23969
+ yield value;
23970
+ }
23971
+ }
23972
+ }
23973
+ function nativeTimeMs(value) {
23974
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
23975
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
24047
23976
  }
24048
23977
 
24049
- // dist/acp-transport.js
24050
- var AntigravityAcpTransport = class {
24051
- options;
24052
- skipPermissions;
24053
- #child = null;
24054
- #connection = null;
24055
- #initializing = null;
24056
- #sessionId = null;
24057
- #sessionHandler = null;
24058
- #active = null;
24059
- #callbacks = /* @__PURE__ */ new Set();
24060
- #acceptCallbacks = false;
24061
- #promptInterrupted = null;
24062
- #opening = null;
24063
- #observeReplay = null;
24064
- #pendingEvents = [];
24065
- #closed = false;
24066
- #closing = null;
24067
- #stderrRaw = "";
24068
- get #stderr() {
24069
- return sanitizeDiagnosticTail(this.#stderrRaw);
24070
- }
24071
- #faultSignal = new AbortController();
24072
- constructor(options) {
24073
- this.options = options;
24074
- this.skipPermissions = options.skipPermissions === true;
24075
- }
24076
- get sessionId() {
24077
- return this.#sessionId;
23978
+ // dist/usage-statistics.js
23979
+ function count3(value) {
23980
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
23981
+ }
23982
+ function antigravityHome(environment) {
23983
+ return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
23984
+ }
23985
+ function transcriptPath(brainRoot, conversationId) {
23986
+ return path8.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
23987
+ }
23988
+ function isMissing(error51) {
23989
+ const code = error51?.code;
23990
+ return code === "ENOENT" || code === "ENOTDIR";
23991
+ }
23992
+ async function lstatIfPresent(target2) {
23993
+ try {
23994
+ return await lstat(target2);
23995
+ } catch (error51) {
23996
+ if (isMissing(error51))
23997
+ return null;
23998
+ throw error51;
24078
23999
  }
24079
- get isClosed() {
24080
- return this.#closed;
24000
+ }
24001
+ async function transcriptFingerprint(file2) {
24002
+ const logs = path8.dirname(file2);
24003
+ for (const directory of [path8.dirname(logs), logs]) {
24004
+ if (!(await lstatIfPresent(directory))?.isDirectory())
24005
+ return null;
24081
24006
  }
24082
- setSessionEventHandler(handler) {
24083
- this.#sessionHandler = handler;
24084
- if (handler)
24085
- for (const event of this.#pendingEvents.splice(0))
24086
- handler(event);
24007
+ const info = await lstatIfPresent(file2);
24008
+ return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
24009
+ }
24010
+ async function listTranscripts(brainRoot, signal) {
24011
+ signal.throwIfAborted();
24012
+ const conversations = await opendir(brainRoot).catch((error51) => {
24013
+ if (error51.code === "ENOENT")
24014
+ return null;
24015
+ throw error51;
24016
+ });
24017
+ if (!conversations)
24018
+ return [];
24019
+ const sources = [];
24020
+ for await (const entry of conversations) {
24021
+ signal.throwIfAborted();
24022
+ if (!entry.isDirectory())
24023
+ continue;
24024
+ const file2 = transcriptPath(brainRoot, entry.name);
24025
+ const fingerprint = await transcriptFingerprint(file2);
24026
+ if (fingerprint)
24027
+ sources.push({ id: file2, fingerprint });
24087
24028
  }
24088
- initialize() {
24089
- if (this.#closed)
24090
- return Promise.reject(new AntigravityTransportError("unavailable", "Antigravity ACP is closed"));
24091
- return this.#initializing ??= this.#start();
24029
+ return sources;
24030
+ }
24031
+ async function readAntigravityUsage(file2, signal) {
24032
+ const sessionId = path8.basename(path8.resolve(file2, "..", "..", ".."));
24033
+ const requests = /* @__PURE__ */ new Map();
24034
+ for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
24035
+ if (record4.type !== "PLANNER_RESPONSE")
24036
+ continue;
24037
+ const step = count3(record4.step_index);
24038
+ const input = count3(record4.input_tokens);
24039
+ const output = count3(record4.output_tokens);
24040
+ const cached2 = count3(record4.cache_read_tokens);
24041
+ const at = nativeTimeMs(record4.created_at);
24042
+ if (step === null || input === null || output === null || at === null)
24043
+ continue;
24044
+ const identity2 = normalizeAntigravityUsageModel(record4.model);
24045
+ requests.set(step, withUsageSession({
24046
+ id: `${String(record4.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
24047
+ occurredAtMs: at,
24048
+ ...identity2,
24049
+ inputTokens: input + (cached2 ?? 0),
24050
+ ...cached2 !== null ? {
24051
+ cachedInputTokens: cached2,
24052
+ ...hasImplicitZeroCacheWrite(identity2) ? { cacheWriteInputTokens: 0 } : {}
24053
+ } : {},
24054
+ outputTokens: output
24055
+ }, { sessionId }));
24092
24056
  }
24093
- async #start() {
24094
- try {
24095
- const executable = resolveAntigravityExecutable(this.options);
24096
- if (!executable)
24097
- throw new AntigravityTransportError("notInstalled", "Antigravity CLI was not found");
24098
- const invocation = commandInvocation(executable, this.skipPermissions ? ["acp", "--dangerously-skip-permissions"] : ["acp"], this.options.environment ?? process.env);
24099
- const child = spawn(invocation.command, invocation.arguments, {
24100
- cwd: this.options.cwd,
24101
- env: this.options.environment ?? process.env,
24102
- stdio: ["pipe", "pipe", "pipe"],
24103
- windowsHide: true,
24104
- windowsVerbatimArguments: invocation.windowsVerbatimArguments
24105
- });
24106
- this.#child = child;
24107
- child.stderr.on("data", (chunk) => {
24108
- this.#stderrRaw = (this.#stderrRaw + chunk.toString()).slice(-32e3);
24109
- });
24110
- child.on("error", (error51) => this.#fault(new AntigravityTransportError(error51.code === "ENOENT" ? "notInstalled" : "unavailable", error51.message, { diagnostic: this.#stderr })));
24111
- child.on("exit", (code, signal) => this.#fault(new AntigravityTransportError("processExited", `Antigravity ACP exited (code ${code}, signal ${signal})`, { diagnostic: this.#stderr })));
24112
- child.stdin.on("error", (error51) => this.#fault(this.#error(error51)));
24113
- const stream = ndJsonStream2(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
24114
- const nativeMethods = /* @__PURE__ */ new Set(["session/request_permission", "elicitation/create"]);
24115
- stream.readable = stream.readable.pipeThrough(new TransformStream({
24116
- transform: (message2, controller) => {
24117
- if ("method" in message2 && message2.method === "session/update") {
24118
- const params = message2.params;
24119
- this.#update(params.sessionId, params.update);
24120
- return;
24121
- }
24122
- if ("method" in message2 && nativeMethods.has(message2.method))
24123
- message2.method = `_antigravity/${message2.method}`;
24124
- controller.enqueue(message2);
24125
- }
24126
- }));
24127
- const onElicitation = (request) => this.#callback("sessionId" in request ? request.sessionId : void 0, (handler) => handler.onElicitation(request), { action: "cancel" });
24128
- const client2 = {
24129
- sessionUpdate: ({ sessionId, update }) => this.#update(sessionId, update),
24130
- requestPermission: (request) => this.#callback(request.sessionId, (handler) => handler.onPermission(request), {
24131
- outcome: { outcome: "cancelled" }
24132
- }),
24133
- unstable_createElicitation: onElicitation,
24134
- extMethod: async (method, params) => {
24135
- if (method === "_antigravity/session/request_permission")
24136
- return await client2.requestPermission(params);
24137
- if (method === "_antigravity/elicitation/create")
24138
- return await onElicitation(params);
24139
- throw new AntigravityTransportError("unsupported", `Unsupported ACP client method: ${method}`);
24057
+ return [...requests.values()];
24058
+ }
24059
+ function createAntigravityUsageStatistics(environment) {
24060
+ const brainRoot = nativeBrainRoot(antigravityHome(environment));
24061
+ let listed = /* @__PURE__ */ new Map();
24062
+ return Object.freeze({
24063
+ async listSources(signal) {
24064
+ const sources = await listTranscripts(brainRoot, signal);
24065
+ listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
24066
+ return sources;
24067
+ },
24068
+ async readSource(id, signal) {
24069
+ const expected = listed.get(id);
24070
+ let entries;
24071
+ try {
24072
+ entries = await readAntigravityUsage(id, signal);
24073
+ } catch (error51) {
24074
+ if (expected !== void 0 && isMissing(error51)) {
24075
+ throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
24140
24076
  }
24141
- };
24142
- const connection = new ClientSideConnection(() => client2, stream);
24143
- this.#connection = connection;
24144
- connection.signal.addEventListener("abort", () => this.#fault(new AntigravityTransportError("processExited", "Antigravity ACP connection closed", {
24145
- diagnostic: this.#stderr
24146
- })), { once: true });
24147
- const response = await this.#request(connection.initialize({
24148
- protocolVersion: 1,
24149
- clientCapabilities: { elicitation: { form: {} } }
24150
- }), "initialize");
24151
- if (response.protocolVersion !== 1)
24152
- throw new AntigravityTransportError("protocolError", `Unsupported ACP version ${response.protocolVersion}`);
24153
- return response;
24154
- } catch (error51) {
24155
- await this.close();
24156
- throw this.#error(error51);
24157
- }
24158
- }
24159
- async openSession(input) {
24160
- await this.initialize();
24161
- if (this.#closed || !this.#connection || this.#active || this.#opening || this.#sessionId)
24162
- throw new AntigravityTransportError("unavailable", "Close the current ACP session before opening another");
24163
- const connection = this.#connection;
24164
- const buffered = [];
24165
- this.#opening = buffered;
24166
- this.#pendingEvents = [];
24167
- const params = {
24168
- cwd: input.cwd,
24169
- mcpServers: [],
24170
- ...input.additionalDirectories?.length ? { additionalDirectories: input.additionalDirectories } : {},
24171
- ...input.systemPromptAppend ? { _meta: { antigravity: { systemPrompt: { append: input.systemPromptAppend } } } } : {}
24172
- };
24173
- try {
24174
- const replay = input.kind === "load" && input.sessionId ? nativeReplayCompletion(await readNativeReplaySize(input.sessionId, antigravityHome(this.options.environment ?? process.env))) : void 0;
24175
- this.#observeReplay = replay ? (sessionId2, event) => {
24176
- if (sessionId2 === input.sessionId)
24177
- replay.observe(event);
24178
- } : null;
24179
- let request;
24180
- if (input.kind === "create")
24181
- request = connection.newSession(params);
24182
- else {
24183
- if (!input.sessionId)
24184
- throw new AntigravityTransportError("protocolError", "Session ID required for resume/load");
24185
- const target2 = { ...params, sessionId: input.sessionId };
24186
- request = input.kind === "resume" ? connection.resumeSession(target2) : connection.loadSession(target2);
24077
+ throw error51;
24078
+ }
24079
+ if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
24080
+ throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
24187
24081
  }
24188
- const result = await this.#request(request, `session/${input.kind === "create" ? "new" : input.kind}`);
24189
- const raw = result;
24190
- const sessionId = raw.sessionId ?? input.sessionId;
24191
- if (!sessionId)
24192
- throw new AntigravityTransportError("protocolError", "Antigravity session/new returned no sessionId");
24193
- this.#sessionId = sessionId;
24194
- if (replay)
24195
- await this.#request(replay.complete, "session/load replay");
24196
- const events = buffered.filter((entry) => entry.sessionId === sessionId).map(({ event }) => event);
24197
- if (input.kind !== "load")
24198
- for (const event of events)
24199
- this.#dispatch(event);
24200
- return {
24201
- opened: {
24202
- sessionId,
24203
- ...raw.models ? { models: raw.models } : {},
24204
- ...raw.modes ? { modes: raw.modes } : {},
24205
- ...raw.configOptions ? { configOptions: raw.configOptions } : {},
24206
- ...raw._meta?.antigravity?.tier ? { tier: raw._meta.antigravity.tier } : {}
24207
- },
24208
- replayedEvents: input.kind === "load" ? events : []
24209
- };
24210
- } finally {
24211
- this.#opening = null;
24212
- this.#observeReplay = null;
24082
+ return entries;
24213
24083
  }
24214
- }
24215
- async setMode(modeId) {
24216
- const { connection, sessionId } = this.#session();
24217
- await this.#request(connection.setSessionMode({ sessionId, modeId }), "session/set_mode");
24218
- }
24219
- async setConfigOption(configId, value) {
24220
- const { connection, sessionId } = this.#session();
24221
- const response = await this.#request(connection.setSessionConfigOption({ sessionId, configId, value }), "session/set_config_option");
24222
- return response.configOptions;
24223
- }
24224
- async prompt(parts, handler) {
24225
- const { connection, sessionId } = this.#session();
24226
- if (this.#active)
24227
- throw new AntigravityTransportError("unavailable", "An ACP prompt is already active");
24228
- this.#active = handler;
24229
- this.#acceptCallbacks = true;
24230
- const interrupted = new AbortController();
24231
- this.#promptInterrupted = interrupted;
24084
+ });
24085
+ }
24086
+
24087
+ // dist/fork.js
24088
+ function nativeConversationDbPath(id, home = os3.homedir()) {
24089
+ return path9.join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
24090
+ }
24091
+ function nativeConversationSummariesDbPath(home = os3.homedir()) {
24092
+ return path9.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
24093
+ }
24094
+ function nativeBrainRoot(home = os3.homedir()) {
24095
+ return path9.join(home, ".gemini", "antigravity-cli", "brain");
24096
+ }
24097
+ function nativeBrainDirPath(id, home = os3.homedir()) {
24098
+ return path9.join(nativeBrainRoot(home), id);
24099
+ }
24100
+ function validNativeSessionRef(ref, harnessId2) {
24101
+ return nativeSessionRefSchema.safeParse(ref).success && ref.harnessId === harnessId2 && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(ref.nativeSessionId);
24102
+ }
24103
+ async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os3.homedir()) {
24104
+ if (![sourceId, derivedId].every((id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id)))
24105
+ throw new Error("Invalid native conversation ID");
24106
+ const home = typeof retainedTurnsCountOrHome === "string" ? retainedTurnsCountOrHome : homeOption;
24107
+ const retained = typeof retainedTurnsCountOrHome === "number" ? retainedTurnsCountOrHome : void 0;
24108
+ const sourcePath = nativeConversationDbPath(sourceId, home);
24109
+ const targetPath2 = nativeConversationDbPath(derivedId, home);
24110
+ await access2(sourcePath);
24111
+ const { DatabaseSync, backup } = await import("node:sqlite");
24112
+ const source = new DatabaseSync(sourcePath, { readOnly: true });
24113
+ let owned = false;
24114
+ try {
24115
+ source.exec("BEGIN");
24116
+ const count4 = Number(source.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
24117
+ if (retained !== void 0 && (!Number.isSafeInteger(retained) || retained < 0 || retained > count4))
24118
+ throw new Error("Invalid retained native Turn count");
24119
+ await mkdir(path9.dirname(targetPath2), { recursive: true });
24120
+ const reservation = await open(targetPath2, "wx");
24121
+ owned = true;
24122
+ await reservation.close();
24123
+ await backup(source, targetPath2);
24124
+ const target2 = new DatabaseSync(targetPath2);
24232
24125
  try {
24233
- return await this.#request(connection.prompt({ sessionId, prompt: [...parts] }), "session/prompt", null, interrupted.signal);
24126
+ target2.exec("BEGIN IMMEDIATE");
24127
+ target2.prepare("UPDATE trajectory_meta SET cascade_id = ?").run(derivedId);
24128
+ const row = target2.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get();
24129
+ const blob = row?.data instanceof Uint8Array ? rewriteTrajectoryMetadataCascadeId(row.data, derivedId) : minimalTrajectoryMetadataBlob(derivedId);
24130
+ if (!blob)
24131
+ throw new Error("Invalid native trajectory metadata");
24132
+ target2.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(blob);
24133
+ if (retained !== void 0 && retained < count4) {
24134
+ const boundary = target2.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
24135
+ const cutoff = retained === 0 ? 0 : Number(boundary?.idx);
24136
+ target2.prepare("DELETE FROM steps WHERE idx >= ?").run(cutoff);
24137
+ for (const table of [
24138
+ "gen_metadata",
24139
+ "executor_metadata",
24140
+ "parent_references",
24141
+ "battle_mode_infos"
24142
+ ]) {
24143
+ if (target2.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table))
24144
+ target2.prepare(`DELETE FROM ${table} WHERE idx >= ?`).run(cutoff);
24145
+ }
24146
+ }
24147
+ target2.exec("COMMIT");
24234
24148
  } finally {
24235
- this.#clearCallbacks();
24236
- this.#acceptCallbacks = false;
24237
- this.#active = null;
24238
- this.#promptInterrupted = null;
24149
+ target2.close();
24239
24150
  }
24151
+ await registerDerivedSummary(sourceId, derivedId, home);
24152
+ return true;
24153
+ } catch (error51) {
24154
+ if (owned)
24155
+ await removeDerivedDb(derivedId, home);
24156
+ throw error51;
24157
+ } finally {
24158
+ source.close();
24240
24159
  }
24241
- async cancel() {
24242
- const { connection, sessionId } = this.#session();
24243
- this.#acceptCallbacks = false;
24244
- this.#clearCallbacks();
24245
- await this.#request(connection.cancel({ sessionId }), "session/cancel");
24246
- }
24247
- async closeSession() {
24248
- const sessionId = this.#sessionId;
24249
- this.#sessionId = null;
24250
- this.#acceptCallbacks = false;
24251
- this.#promptInterrupted?.abort(new AntigravityTransportError("unavailable", "ACP session closed"));
24252
- this.#active = null;
24253
- this.#pendingEvents = [];
24254
- this.#clearCallbacks();
24255
- if (sessionId && this.#connection)
24256
- await this.#request(this.#connection.closeSession({ sessionId }), "session/close", this.options.closeTimeoutMs ?? 2e3);
24257
- }
24258
- close() {
24259
- if (this.#closing)
24260
- return this.#closing;
24261
- this.#closed = true;
24262
- return this.#closing = this.#shutdown();
24160
+ }
24161
+ async function registerDerivedSummary(sourceId, derivedId, home) {
24162
+ const summaryPath = nativeConversationSummariesDbPath(home);
24163
+ try {
24164
+ await access2(summaryPath);
24165
+ } catch (error51) {
24166
+ if (error51.code === "ENOENT")
24167
+ return;
24168
+ throw error51;
24263
24169
  }
24264
- async #shutdown() {
24170
+ const { DatabaseSync } = await import("node:sqlite");
24171
+ const summaries = new DatabaseSync(summaryPath);
24172
+ try {
24173
+ const template = summaries.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?").get(sourceId);
24174
+ if (!template)
24175
+ return;
24176
+ const derived = new DatabaseSync(nativeConversationDbPath(derivedId, home), { readOnly: true });
24177
+ let row;
24265
24178
  try {
24266
- await this.closeSession();
24267
- } catch (error51) {
24268
- this.#stderrRaw = `${this.#stderrRaw}
24269
- ${this.#error(error51).message}`.slice(-32e3);
24270
- }
24271
- this.#faultSignal.abort(new AntigravityTransportError("unavailable", "Antigravity ACP closed"));
24272
- this.#opening = null;
24273
- this.#sessionHandler = null;
24274
- const child = this.#child;
24275
- if (child && child.exitCode === null && child.signalCode === null && child.pid) {
24276
- const exited = new Promise((resolve) => child.once("exit", () => resolve()));
24277
- const timeout = this.options.closeTimeoutMs ?? 2e3;
24278
- const term = setTimeout(() => child.kill("SIGTERM"), Math.max(1, timeout / 2));
24279
- const kill = setTimeout(() => child.kill("SIGKILL"), Math.max(2, timeout));
24280
- child.stdin.end();
24281
- try {
24282
- await exited;
24283
- } finally {
24284
- clearTimeout(term);
24285
- clearTimeout(kill);
24286
- }
24179
+ const metadata = derived.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get()?.data;
24180
+ const trajectoryId = derived.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get()?.trajectory_id;
24181
+ row = {
24182
+ ...template,
24183
+ conversation_id: derivedId,
24184
+ status: "CASCADE_RUN_STATUS_IDLE",
24185
+ step_count: Number(derived.prepare("SELECT count(*) AS n FROM steps").get()?.n),
24186
+ last_user_input_step_index: Number(derived.prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = 14").get()?.idx ?? -1),
24187
+ not_fully_idle: 0,
24188
+ killed: 0,
24189
+ last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
24190
+ raw_summary: minimalRawSummaryBlob(String(trajectoryId), Buffer.from(metadata))
24191
+ };
24192
+ } finally {
24193
+ derived.close();
24287
24194
  }
24288
- this.#connection = null;
24289
- this.#child = null;
24290
- }
24291
- #session() {
24292
- if (this.#closed || !this.#connection || !this.#sessionId)
24293
- throw new AntigravityTransportError("unavailable", "Antigravity ACP session is unavailable");
24294
- return { connection: this.#connection, sessionId: this.#sessionId };
24195
+ const columns = Object.keys(template);
24196
+ summaries.prepare(`INSERT INTO conversation_summaries (${columns.map((name) => `"${name.replaceAll('"', '""')}"`).join(",")}) VALUES (${columns.map(() => "?").join(",")})`).run(...columns.map((name) => row[name] ?? null));
24197
+ } finally {
24198
+ summaries.close();
24295
24199
  }
24296
- #update(sessionId, raw) {
24297
- if (this.#closed)
24298
- return;
24299
- const event = projectAcpSessionUpdate(raw);
24300
- if (!event)
24301
- return;
24302
- if (this.#opening) {
24303
- this.#opening.push({ sessionId, event });
24304
- this.#observeReplay?.(sessionId, event);
24200
+ }
24201
+ async function removeDerivedSummary(id, home) {
24202
+ try {
24203
+ await access2(nativeConversationSummariesDbPath(home));
24204
+ } catch (error51) {
24205
+ if (error51.code === "ENOENT")
24305
24206
  return;
24306
- }
24307
- if (sessionId === this.#sessionId)
24308
- this.#dispatch(event);
24309
- }
24310
- #dispatch(event) {
24311
- if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type)) {
24312
- if (this.#sessionHandler)
24313
- this.#sessionHandler(event);
24314
- else
24315
- this.#pendingEvents.push(event);
24316
- } else
24317
- this.#active?.onEvent(event);
24207
+ throw error51;
24318
24208
  }
24319
- async #callback(sessionId, invoke, cancelled) {
24320
- const active = this.#active;
24321
- if (!active || !this.#acceptCallbacks || sessionId !== this.#sessionId || this.#closed)
24322
- return cancelled;
24323
- let cancel;
24324
- const cancellation = new Promise((resolve) => {
24325
- cancel = () => resolve(cancelled);
24326
- });
24327
- this.#callbacks.add(cancel);
24328
- try {
24329
- return await Promise.race([invoke(active), cancellation]);
24330
- } finally {
24331
- this.#callbacks.delete(cancel);
24332
- }
24209
+ const { DatabaseSync } = await import("node:sqlite");
24210
+ const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
24211
+ try {
24212
+ db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
24213
+ } finally {
24214
+ db.close();
24333
24215
  }
24334
- #clearCallbacks() {
24335
- for (const cancel of this.#callbacks)
24336
- cancel();
24337
- this.#callbacks.clear();
24216
+ }
24217
+ async function removeDerivedDb(id, home) {
24218
+ const file2 = nativeConversationDbPath(id, home);
24219
+ await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
24220
+ }
24221
+ async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedir()) {
24222
+ try {
24223
+ await access2(nativeBrainDirPath(sourceId, home));
24224
+ } catch (error51) {
24225
+ if (error51.code === "ENOENT")
24226
+ return false;
24227
+ throw error51;
24338
24228
  }
24339
- async #request(promise2, operation, timeoutMs = this.options.commandTimeoutMs ?? 3e4, signal) {
24340
- let timer;
24341
- let abort;
24342
- const signals = [this.#faultSignal.signal, ...signal ? [signal] : []];
24343
- const interrupted = new Promise((_, reject) => {
24344
- abort = () => reject(signal?.aborted ? signal.reason : this.#faultSignal.signal.reason);
24345
- if (signals.some((candidate) => candidate.aborted))
24346
- abort();
24347
- else
24348
- for (const candidate of signals)
24349
- candidate.addEventListener("abort", abort, { once: true });
24350
- if (timeoutMs !== null)
24351
- timer = setTimeout(() => reject(new AntigravityTransportError("unavailable", `${operation} timed out after ${timeoutMs}ms`, { diagnostic: this.#stderr })), timeoutMs);
24229
+ await cp(nativeBrainDirPath(sourceId, home), nativeBrainDirPath(derivedId, home), {
24230
+ recursive: true,
24231
+ errorOnExist: true,
24232
+ force: false,
24233
+ filter: (source) => path9.basename(source) !== ".system_generated"
24234
+ });
24235
+ return true;
24236
+ }
24237
+ async function openDerivedAntigravitySession(options, input, sourceRef, retained) {
24238
+ const environment = { ...options.adapterEnvironment, ...input.environment };
24239
+ const home = antigravityHome(environment);
24240
+ const derivedId = randomUUID();
24241
+ let cloned = false;
24242
+ try {
24243
+ await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home);
24244
+ cloned = true;
24245
+ await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
24246
+ const result = await options.openSession({
24247
+ ...input,
24248
+ environment,
24249
+ nativeRef: { ...sourceRef, nativeSessionId: derivedId }
24352
24250
  });
24353
- try {
24354
- return await Promise.race([promise2, interrupted]);
24355
- } catch (error51) {
24356
- const normalized = this.#error(error51);
24357
- if (normalized.kind === "unavailable" && normalized.message.includes("timed out"))
24358
- void this.close();
24359
- throw normalized;
24360
- } finally {
24361
- clearTimeout(timer);
24362
- for (const candidate of signals)
24363
- candidate.removeEventListener("abort", abort);
24364
- }
24365
- }
24366
- #error(error51) {
24367
- if (error51 instanceof AntigravityTransportError)
24368
- return error51;
24369
- const message2 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
24370
- const code = error51?.code;
24371
- return new AntigravityTransportError(code === -32e3 || /auth|login|sign[ -]?in|unauthenticated/iu.test(message2) ? "authenticationRequired" : "unavailable", message2, { cause: error51, diagnostic: this.#stderr });
24251
+ if (result.ok)
24252
+ return result;
24253
+ const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24254
+ return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
24255
+ } catch (error51) {
24256
+ const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24257
+ return {
24258
+ ok: false,
24259
+ error: {
24260
+ ...nativeHistoryError(error51),
24261
+ ...cleanupFailure ? { diagnostic: cleanupFailure } : {}
24262
+ }
24263
+ };
24372
24264
  }
24373
- #fault(error51) {
24374
- if (this.#closed || this.#faultSignal.signal.aborted)
24265
+ async function cleanup() {
24266
+ if (!cloned)
24375
24267
  return;
24376
- this.#faultSignal.abort(error51);
24377
- this.#clearCallbacks();
24378
- void this.close();
24379
- this.options.onFault?.(error51);
24268
+ await Promise.all([
24269
+ removeDerivedDb(derivedId, home),
24270
+ rm2(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
24271
+ removeDerivedSummary(derivedId, home)
24272
+ ]);
24380
24273
  }
24381
- };
24382
-
24383
- // dist/delegation.js
24384
- var DELEGATION_ENVIRONMENT_KEYS = [
24385
- "CODEXHOST_CLI_PATH",
24386
- "CODEXHOST_RUNTIME_ENDPOINT",
24387
- "CODEXHOST_RUNTIME_TOKEN",
24388
- "CODEXHOST_THREAD_ID"
24389
- ];
24390
- var ANTIGRAVITY_DELEGATION_INSTRUCTIONS = `This Antigravity Session runs inside codexhost.
24391
- 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.`;
24392
- function antigravityDelegationInstructions(environment) {
24393
- return DELEGATION_ENVIRONMENT_KEYS.every((key) => environment[key]) ? ANTIGRAVITY_DELEGATION_INSTRUCTIONS : void 0;
24274
+ }
24275
+ async function forkAntigravitySession(options) {
24276
+ const { input, harnessId: harnessId2 } = options;
24277
+ if (!validNativeSessionRef(input.sourceRef, harnessId2))
24278
+ return {
24279
+ ok: false,
24280
+ error: {
24281
+ code: "invalidRequest",
24282
+ message: "Invalid Antigravity source Native Session",
24283
+ retryable: false
24284
+ }
24285
+ };
24286
+ const checkpoint = nativeCheckpointRefSchema.safeParse(input.checkpoint);
24287
+ if (!checkpoint.success || checkpoint.data.harnessId !== harnessId2 || checkpoint.data.nativeSessionId !== input.sourceRef.nativeSessionId)
24288
+ return checkpointError();
24289
+ if (options.sourceSession?.isActive)
24290
+ return {
24291
+ ok: false,
24292
+ error: {
24293
+ code: "sessionBusy",
24294
+ message: "Source Session is busy",
24295
+ retryable: true
24296
+ }
24297
+ };
24298
+ const match = /^turn-(0|[1-9]\d*)$/u.exec(checkpoint.data.checkpointId);
24299
+ if (!match)
24300
+ return checkpointError();
24301
+ try {
24302
+ const count4 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
24303
+ const index = Number(match[1]);
24304
+ if (!Number.isSafeInteger(index) || index >= count4)
24305
+ return checkpointError();
24306
+ return openDerivedAntigravitySession(options, {
24307
+ kind: "resume",
24308
+ nativeRef: input.sourceRef,
24309
+ cwd: input.cwd,
24310
+ ...input.environment ? { environment: input.environment } : {}
24311
+ }, input.sourceRef, index + 1);
24312
+ } catch (error51) {
24313
+ return { ok: false, error: nativeHistoryError(error51) };
24314
+ }
24315
+ }
24316
+ function checkpointError() {
24317
+ return {
24318
+ ok: false,
24319
+ error: {
24320
+ code: "checkpointNotFound",
24321
+ message: "Antigravity native Turn checkpoint not found",
24322
+ retryable: false
24323
+ }
24324
+ };
24394
24325
  }
24395
24326
 
24396
24327
  // dist/model-catalog.js
@@ -24549,6 +24480,128 @@ function splitAntigravityModelAndEffort(rawModelId) {
24549
24480
  return { modelRef: harnessModelRefSchema.parse({ id: rawModelId.trim() }) };
24550
24481
  }
24551
24482
 
24483
+ // dist/native-replay.js
24484
+ var USER_INPUT = 14;
24485
+ var PLANNER_RESPONSE = 15;
24486
+ var ERROR_MESSAGE = 17;
24487
+ var GENERIC_TOOL = 132;
24488
+ var DONE = 3;
24489
+ var ERROR = 7;
24490
+ var IN_FLIGHT = /* @__PURE__ */ new Set([1, 2, 8, 9, 11]);
24491
+ function message2(payload) {
24492
+ const fields = payload instanceof Uint8Array ? readProtoFields(payload) : null;
24493
+ if (!fields)
24494
+ throw new Error("Invalid Antigravity history protobuf");
24495
+ return fields;
24496
+ }
24497
+ function messageField(fields, number4) {
24498
+ const field3 = fields.find((entry) => entry.number === number4 && entry.wire === 2);
24499
+ return field3?.value instanceof Uint8Array ? field3.value : void 0;
24500
+ }
24501
+ function nested(fields, number4) {
24502
+ const payload = messageField(fields, number4);
24503
+ return payload ? message2(payload) : [];
24504
+ }
24505
+ function textField(fields, number4) {
24506
+ const bytes = messageField(fields, number4);
24507
+ return bytes ? Buffer.from(bytes).toString("utf8") : "";
24508
+ }
24509
+ function argsValue(raw) {
24510
+ if (!raw)
24511
+ return void 0;
24512
+ try {
24513
+ return JSON.parse(raw);
24514
+ } catch {
24515
+ return raw;
24516
+ }
24517
+ }
24518
+ async function readNativeHistory(sessionId, home) {
24519
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
24520
+ throw new Error("Invalid native Session ID");
24521
+ const { DatabaseSync } = await import("node:sqlite");
24522
+ const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
24523
+ const events = [];
24524
+ const pendingCalls = /* @__PURE__ */ new Set();
24525
+ let turnCount = 0;
24526
+ const append = (type, text2) => {
24527
+ if (text2)
24528
+ events.push({ type, text: events.at(-1)?.type === type ? `
24529
+
24530
+ ${text2}` : text2 });
24531
+ };
24532
+ try {
24533
+ db.exec("BEGIN");
24534
+ if (db.prepare("PRAGMA user_version").get()?.user_version !== 1)
24535
+ throw new Error("Unsupported Antigravity history database version");
24536
+ for (const row of db.prepare(`SELECT step_type, status, step_payload FROM steps
24537
+ WHERE step_type IN (${USER_INPUT}, ${PLANNER_RESPONSE}, ${ERROR_MESSAGE}, ${GENERIC_TOOL})
24538
+ ORDER BY idx`).iterate()) {
24539
+ if (row.step_type === USER_INPUT)
24540
+ turnCount++;
24541
+ if (IN_FLIGHT.has(Number(row.status)))
24542
+ continue;
24543
+ const step = message2(row.step_payload);
24544
+ const number4 = row.step_type === USER_INPUT ? 19 : row.step_type === PLANNER_RESPONSE ? 20 : row.step_type === ERROR_MESSAGE ? 24 : 140;
24545
+ const body = message2(messageField(step, number4));
24546
+ switch (row.step_type) {
24547
+ case USER_INPUT: {
24548
+ const items = body.flatMap((field3) => field3.number === 3 && field3.wire === 2 ? [textField(message2(field3.value), 1)] : []);
24549
+ const text2 = items.join("") || textField(body, 2) || textField(body, 1);
24550
+ pendingCalls.clear();
24551
+ if (text2)
24552
+ events.push({ type: "user.text", text: text2 });
24553
+ break;
24554
+ }
24555
+ case PLANNER_RESPONSE: {
24556
+ append("agent.thought", textField(body, 3));
24557
+ append("agent.text", textField(body, 1));
24558
+ for (const field3 of body) {
24559
+ if (field3.number !== 7 || field3.wire !== 2)
24560
+ continue;
24561
+ const call = message2(field3.value);
24562
+ const toolCallId = textField(call, 1);
24563
+ const name = textField(call, 2);
24564
+ if (!toolCallId || !name)
24565
+ continue;
24566
+ pendingCalls.add(toolCallId);
24567
+ events.push({
24568
+ type: "tool.call",
24569
+ toolCallId,
24570
+ name,
24571
+ args: argsValue(textField(call, 3))
24572
+ });
24573
+ }
24574
+ break;
24575
+ }
24576
+ case ERROR_MESSAGE: {
24577
+ const warning = textField(nested(body, 3), 2);
24578
+ if (warning)
24579
+ append("agent.text", `⚠ ${warning}`);
24580
+ break;
24581
+ }
24582
+ case GENERIC_TOOL: {
24583
+ const toolCallId = textField(nested(nested(step, 5), 4), 1);
24584
+ if (!pendingCalls.delete(toolCallId))
24585
+ break;
24586
+ const error51 = nested(step, 31);
24587
+ const output = textField(nested(body, 2), 1) || textField(error51, 3) || textField(error51, 2) || textField(error51, 1);
24588
+ const status = row.status === DONE ? "completed" : row.status === ERROR ? "failed" : "cancelled";
24589
+ events.push({
24590
+ type: "tool.update",
24591
+ toolCallId,
24592
+ status,
24593
+ ...output ? { rawOutput: output } : {}
24594
+ });
24595
+ break;
24596
+ }
24597
+ }
24598
+ }
24599
+ return { events, turnCount };
24600
+ } finally {
24601
+ db.close();
24602
+ }
24603
+ }
24604
+
24552
24605
  // dist/permission-modes.js
24553
24606
  var ANTIGRAVITY_ACP_SESSION_MODES = ["default", "accept-edits", "auto", "plan"];
24554
24607
  var ANTIGRAVITY_DEFAULT_PERMISSION_MODE_ID = harnessPermissionModeIdSchema.parse("default");
@@ -24858,8 +24911,8 @@ import { fileURLToPath } from "node:url";
24858
24911
  // ../../harness-adapter/dist/session-import.js
24859
24912
  import { lstat as lstat2 } from "node:fs/promises";
24860
24913
  var SessionImportChangedError = class extends Error {
24861
- constructor(message2 = "Native Session changed during discovery; refresh and retry") {
24862
- super(message2);
24914
+ constructor(message3 = "Native Session changed during discovery; refresh and retry") {
24915
+ super(message3);
24863
24916
  this.name = "SessionImportChangedError";
24864
24917
  }
24865
24918
  };
@@ -25132,144 +25185,6 @@ var AntigravitySessionImport = class {
25132
25185
  }
25133
25186
  };
25134
25187
 
25135
- // dist/snapshot-reader-pool.js
25136
- var THREAD_SCOPED_ENV_KEYS = /* @__PURE__ */ new Set(["CODEXHOST_THREAD_ID"]);
25137
- function sanitizeReaderEnvironment(environment) {
25138
- const sanitized = {};
25139
- for (const [key, value] of Object.entries(environment)) {
25140
- if (value !== void 0 && !THREAD_SCOPED_ENV_KEYS.has(key)) {
25141
- sanitized[key] = value;
25142
- }
25143
- }
25144
- return sanitized;
25145
- }
25146
- function readerScopeKey(command, skipPermissions, environment) {
25147
- const entries = Object.entries(environment).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
25148
- return JSON.stringify([command ?? "", skipPermissions, entries]);
25149
- }
25150
- var AntigravitySnapshotReaderPool = class {
25151
- adapterOptions;
25152
- #lanes = /* @__PURE__ */ new Map();
25153
- #retiring = /* @__PURE__ */ new Set();
25154
- #retired = /* @__PURE__ */ new WeakSet();
25155
- #closed = false;
25156
- #closing;
25157
- constructor(adapterOptions) {
25158
- this.adapterOptions = adapterOptions;
25159
- }
25160
- loadSession(input) {
25161
- if (this.#closed || input.signal?.aborted) {
25162
- return Promise.reject(new AntigravityTransportError("unavailable", "Snapshot reader is closed"));
25163
- }
25164
- const environment = sanitizeReaderEnvironment(input.environment);
25165
- const key = readerScopeKey(this.adapterOptions.command, input.skipPermissions, environment);
25166
- let lane = this.#lanes.get(key);
25167
- if (!lane) {
25168
- lane = { transport: void 0, initialized: false, tail: Promise.resolve() };
25169
- this.#lanes.set(key, lane);
25170
- }
25171
- const currentLane = lane;
25172
- const run = currentLane.tail.then(() => this.#loadInLane(currentLane, input, environment));
25173
- currentLane.tail = run.then(() => void 0, () => void 0);
25174
- return run;
25175
- }
25176
- close() {
25177
- return this.#closing ??= this.#close().catch((error51) => {
25178
- this.#closing = void 0;
25179
- throw error51;
25180
- });
25181
- }
25182
- async #close() {
25183
- this.#closed = true;
25184
- for (const lane of this.#lanes.values()) {
25185
- if (lane.transport)
25186
- this.#retire(lane, lane.transport);
25187
- }
25188
- this.#lanes.clear();
25189
- await Promise.all(this.#retiring);
25190
- }
25191
- async #loadInLane(lane, input, environment) {
25192
- if (this.#closed || input.signal?.aborted) {
25193
- throw new AntigravityTransportError("unavailable", "Snapshot reader is closed");
25194
- }
25195
- let transport = lane.transport;
25196
- if (!transport || transport.isClosed) {
25197
- transport = this.#createTransport(lane, input.cwd, environment, input.skipPermissions);
25198
- lane.transport = transport;
25199
- lane.initialized = false;
25200
- }
25201
- if (!lane.initialized) {
25202
- try {
25203
- await transport.initialize();
25204
- lane.initialized = true;
25205
- } catch (error51) {
25206
- this.#retire(lane, transport);
25207
- throw error51;
25208
- }
25209
- }
25210
- if (this.#closed || transport.isClosed) {
25211
- this.#retire(lane, transport);
25212
- throw new AntigravityTransportError("unavailable", "Snapshot reader is closed");
25213
- }
25214
- if (input.signal?.aborted) {
25215
- throw new AntigravityTransportError("unavailable", "Snapshot read aborted");
25216
- }
25217
- try {
25218
- const { opened, replayedEvents } = await transport.openSession({
25219
- kind: "load",
25220
- sessionId: input.sessionId,
25221
- cwd: input.cwd
25222
- });
25223
- if (opened.sessionId !== input.sessionId) {
25224
- throw new AntigravityTransportError("protocolError", "Snapshot loaded a different Session");
25225
- }
25226
- await transport.closeSession();
25227
- if (this.#closed || transport.isClosed) {
25228
- this.#retire(lane, transport);
25229
- }
25230
- return { opened, replayedEvents };
25231
- } catch (error51) {
25232
- this.#retire(lane, transport);
25233
- throw error51;
25234
- }
25235
- }
25236
- #createTransport(lane, cwd, environment, skipPermissions) {
25237
- const options = {
25238
- cwd,
25239
- ...this.adapterOptions.command ? { command: this.adapterOptions.command } : {},
25240
- environment,
25241
- skipPermissions,
25242
- ...this.adapterOptions.commandTimeoutMs !== void 0 ? { commandTimeoutMs: this.adapterOptions.commandTimeoutMs } : {},
25243
- ...this.adapterOptions.closeTimeoutMs !== void 0 ? { closeTimeoutMs: this.adapterOptions.closeTimeoutMs } : {},
25244
- onFault: () => {
25245
- this.#retire(lane, transport);
25246
- }
25247
- };
25248
- const transport = this.adapterOptions.createTransport?.(options) ?? new AntigravityAcpTransport(options);
25249
- return transport;
25250
- }
25251
- #retire(lane, transport) {
25252
- if (lane.transport === transport) {
25253
- lane.transport = void 0;
25254
- lane.initialized = false;
25255
- }
25256
- if (this.#retired.has(transport))
25257
- return;
25258
- this.#retired.add(transport);
25259
- let raw;
25260
- try {
25261
- raw = transport.close();
25262
- } catch (error51) {
25263
- raw = Promise.reject(error51);
25264
- }
25265
- const tracked = raw.then(() => {
25266
- this.#retiring.delete(tracked);
25267
- });
25268
- this.#retiring.add(tracked);
25269
- void tracked.catch(() => void 0);
25270
- }
25271
- };
25272
-
25273
25188
  // dist/subagent-transcript.js
25274
25189
  import { open as open2, realpath } from "node:fs/promises";
25275
25190
  import path11 from "node:path";
@@ -25622,8 +25537,8 @@ var antigravitySessionCapabilities = {
25622
25537
  function ok(value) {
25623
25538
  return { ok: true, value };
25624
25539
  }
25625
- function err(code, message2, retryable = false) {
25626
- return { ok: false, error: { code, message: message2, retryable } };
25540
+ function err(code, message3, retryable = false) {
25541
+ return { ok: false, error: { code, message: message3, retryable } };
25627
25542
  }
25628
25543
  function normalizeAntigravityError(error51) {
25629
25544
  if (error51 instanceof AntigravityTransportError)
@@ -25633,11 +25548,11 @@ function normalizeAntigravityError(error51) {
25633
25548
  retryable: error51.retryable,
25634
25549
  ...error51.diagnostic ? { diagnostic: sanitizeDiagnosticTail(error51.diagnostic) } : {}
25635
25550
  };
25636
- const message2 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
25551
+ const message3 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
25637
25552
  const code = error51?.code;
25638
25553
  return {
25639
- code: code === "ENOENT" ? "notInstalled" : /authenticat|sign.?in|login|credential/iu.test(message2) ? "authenticationRequired" : "nativeFailure",
25640
- message: message2,
25554
+ code: code === "ENOENT" ? "notInstalled" : /authenticat|sign.?in|login|credential/iu.test(message3) ? "authenticationRequired" : "nativeFailure",
25555
+ message: message3,
25641
25556
  retryable: false
25642
25557
  };
25643
25558
  }
@@ -25838,7 +25753,7 @@ var AntigravitySession = class {
25838
25753
  return;
25839
25754
  }
25840
25755
  const ref = this.nativeRef ?? this.#options.nativeRef;
25841
- const { opened, replayedEvents } = await transport.openSession({
25756
+ const { opened } = await transport.openSession({
25842
25757
  kind: ref ? "resume" : "create",
25843
25758
  ...ref ? { sessionId: ref.nativeSessionId } : {},
25844
25759
  cwd: this.#options.cwd,
@@ -25853,17 +25768,8 @@ var AntigravitySession = class {
25853
25768
  if (!validNativeSessionRef({ harnessId, nativeSessionId: opened.sessionId, formatVersion: 1 }, harnessId))
25854
25769
  throw new AntigravityTransportError("protocolError", "Antigravity returned an invalid native Session ID");
25855
25770
  this.#applyOpened(opened, skip);
25856
- try {
25857
- this.#turnCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment)));
25858
- } catch {
25859
- this.#turnCount = Math.max(this.#turnCount, projectReplayedEventsToTurns({
25860
- nativeSessionId: opened.sessionId,
25861
- cwd: this.#options.cwd,
25862
- events: replayedEvents,
25863
- ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {}
25864
- }).length);
25865
- }
25866
- this.#initializeUsage(opened.sessionId, replayedEvents);
25771
+ this.#turnCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment))).catch(() => this.#turnCount);
25772
+ this.#initializeUsage(opened.sessionId);
25867
25773
  transport.setSessionEventHandler((event) => {
25868
25774
  if (this.#transport === transport && !this.#closed && !this.#faulted)
25869
25775
  this.#sessionEvent(event);
@@ -25893,15 +25799,13 @@ var AntigravitySession = class {
25893
25799
  throw error51;
25894
25800
  }
25895
25801
  }
25896
- #initializeUsage(nativeSessionId, events) {
25802
+ #initializeUsage(nativeSessionId) {
25897
25803
  if (this.#usage)
25898
25804
  return;
25899
- const context = events.findLast((event) => event.type === "usage.context");
25900
25805
  this.#usage = new AntigravitySessionUsageTracker({
25901
25806
  nativeSessionId,
25902
25807
  homedir: antigravityHome(this.#options.environment),
25903
- expectedInitialTurns: this.#turnCount,
25904
- ...context ? { initialContextUsedTokens: context.used, initialContextWindowTokens: context.size } : {}
25808
+ expectedInitialTurns: this.#turnCount
25905
25809
  });
25906
25810
  this.#usageWork = this.#replayUsage();
25907
25811
  }
@@ -26093,38 +25997,30 @@ var AntigravitySession = class {
26093
25997
  async readSnapshot() {
26094
25998
  if (this.#closed || this.#faulted)
26095
25999
  return err("invalidState", "Session is closed");
26096
- if (!this.nativeRef)
26000
+ const nativeRef = this.nativeRef;
26001
+ if (!nativeRef)
26097
26002
  return ok({ turns: [], state: { ...this.#state } });
26098
- const skip = this.#transport?.skipPermissions ?? (this.#options.unattended || this.#requested.permissionModeId === SKIP);
26003
+ const { nativeSessionId } = nativeRef;
26099
26004
  try {
26100
- const { opened, replayedEvents } = await this.#options.readerPool.loadSession({
26101
- sessionId: this.nativeRef.nativeSessionId,
26102
- cwd: this.#options.cwd,
26103
- environment: this.#options.environment,
26104
- skipPermissions: skip,
26105
- signal: this.#abort.signal
26106
- });
26005
+ const { events, turnCount } = await readNativeHistory(nativeSessionId, antigravityHome(this.#options.environment));
26107
26006
  if (this.#closed || this.#faulted)
26108
26007
  return err("invalidState", "Session is closed");
26109
26008
  const turns = projectReplayedEventsToTurns({
26110
- nativeSessionId: opened.sessionId,
26009
+ nativeSessionId,
26111
26010
  cwd: this.#options.cwd,
26112
- events: replayedEvents,
26011
+ events,
26113
26012
  ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {},
26114
26013
  ...this.#options.adapter.toolOutputLimit !== void 0 ? { outputLimit: this.#options.adapter.toolOutputLimit } : {}
26115
26014
  });
26116
- const turnCount = this.#transport ? this.#turnCount : await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment))).catch(() => turns.length);
26117
- if (this.#closed || this.#faulted)
26118
- return err("invalidState", "Session is closed");
26119
26015
  if (!this.#transport) {
26120
26016
  this.#turnCount = turnCount;
26121
- this.#initializeUsage(opened.sessionId, replayedEvents);
26017
+ this.#initializeUsage(nativeSessionId);
26122
26018
  }
26123
26019
  return ok({ turns, ...this.#transport ? { state: { ...this.#state } } : {} });
26124
- } catch (error51) {
26020
+ } catch {
26125
26021
  if (this.#closed || this.#faulted)
26126
26022
  return err("invalidState", "Session is closed");
26127
- return { ok: false, error: normalizeAntigravityError(error51) };
26023
+ return err("nativeFailure", "Antigravity history unavailable");
26128
26024
  }
26129
26025
  }
26130
26026
  async execute(command) {
@@ -26582,7 +26478,6 @@ var AntigravityAdapter = class {
26582
26478
  usageStatistics;
26583
26479
  #environment;
26584
26480
  #sessions = /* @__PURE__ */ new Set();
26585
- #readerPool;
26586
26481
  #cache = /* @__PURE__ */ new Map();
26587
26482
  #inflight = /* @__PURE__ */ new Map();
26588
26483
  #abort = new AbortController();
@@ -26593,7 +26488,6 @@ var AntigravityAdapter = class {
26593
26488
  constructor(options = {}) {
26594
26489
  this.options = options;
26595
26490
  this.#environment = options.environment ?? process.env;
26596
- this.#readerPool = new AntigravitySnapshotReaderPool(this.options);
26597
26491
  this.sessionImport = new AntigravitySessionImport(this.#environment);
26598
26492
  this.usageStatistics = createAntigravityUsageStatistics(this.#environment);
26599
26493
  }
@@ -26734,7 +26628,6 @@ var AntigravityAdapter = class {
26734
26628
  ...input.kind === "resume" ? { nativeRef: input.nativeRef, knownTurnRefs: input.knownTurnRefs } : {},
26735
26629
  unattended,
26736
26630
  adapter: this.options,
26737
- readerPool: this.#readerPool,
26738
26631
  onClosed: (closed) => this.#sessions.delete(closed)
26739
26632
  });
26740
26633
  this.#sessions.add(session);
@@ -26809,10 +26702,7 @@ var AntigravityAdapter = class {
26809
26702
  this.#cache.clear();
26810
26703
  this.#inflight.clear();
26811
26704
  this.#quota = null;
26812
- await Promise.all([
26813
- ...[...this.#sessions].map((session) => session.close()),
26814
- this.#readerPool.close()
26815
- ]);
26705
+ await Promise.all([...this.#sessions].map((session) => session.close()));
26816
26706
  this.#sessions.clear();
26817
26707
  }
26818
26708
  };