@codexhost/cli-darwin-x64 0.20.0 → 0.21.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 (50) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +26 -6
  4. package/app/console-web.js +34 -7
  5. package/app/desktop-controller.mjs +162 -51
  6. package/app/host-runtime.mjs +35562 -29076
  7. package/app/plugins/antigravity/assets/icon.svg +1 -1
  8. package/app/plugins/antigravity/plugin.mjs +1112 -822
  9. package/app/plugins/claude-code/plugin.mjs +152 -28
  10. package/app/plugins/codebuddy/plugin.mjs +35 -6
  11. package/app/plugins/codex-usage/plugin.mjs +35 -6
  12. package/app/plugins/copilot/plugin.mjs +27 -6
  13. package/app/plugins/cursor-cli/plugin.mjs +27 -6
  14. package/app/plugins/deepseek-harness/plugin.mjs +52 -11
  15. package/app/plugins/devin/plugin.mjs +27 -6
  16. package/app/plugins/grok/plugin.mjs +63 -15
  17. package/app/plugins/hermes/plugin.mjs +27 -6
  18. package/app/plugins/kimi-code/plugin.mjs +52 -16
  19. package/app/plugins/kiro-cli/plugin.mjs +27 -6
  20. package/app/plugins/omp/plugin.mjs +35 -6
  21. package/app/plugins/opencode/plugin.mjs +53 -15
  22. package/app/plugins/pi/plugin.mjs +35 -6
  23. package/app/plugins/qoder/plugin.mjs +42 -6
  24. package/app/plugins/qoder-cn/plugin.mjs +42 -6
  25. package/app/plugins/qwen-code/plugin.mjs +27 -6
  26. package/app/plugins/workbuddy/plugin.mjs +35 -6
  27. package/app/plugins/zcode/plugin.mjs +35 -6
  28. package/app/renderer-extension.js +26 -6
  29. package/app/web/assets/{index-D85gPBbQ.js → index-BdmZfTRW.js} +62 -62
  30. package/app/web/assets/{index-D6-hvggd.css → index-DJW4bmyx.css} +1 -1
  31. package/app/web/codexhost-settings.js +34 -7
  32. package/app/web/index.html +2 -2
  33. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  34. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +3 -3
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +68 -68
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +6 -6
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +22 -22
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +1 -1
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +1 -1
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +2 -2
  46. package/app/web-modules/server.mjs +1012 -667
  47. package/bin/codexhost +0 -0
  48. package/libexec/codexhost-shim +0 -0
  49. package/libexec/codexhost-updater +0 -0
  50. package/package.json +1 -1
@@ -15066,7 +15066,7 @@ var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonneg
15066
15066
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15067
15067
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15068
15068
  var usageOutputTimingSchema = external_exports.object({
15069
- version: external_exports.literal(3).optional(),
15069
+ version: external_exports.union([external_exports.literal(3), external_exports.literal(4)]).optional(),
15070
15070
  requestId: external_exports.string().min(1),
15071
15071
  turnId: external_exports.string().min(1).max(1024),
15072
15072
  outputTokens: nonNegativeSafeIntegerSchema,
@@ -15074,16 +15074,16 @@ var usageOutputTimingSchema = external_exports.object({
15074
15074
  completedAtMs: nonNegativeSafeIntegerSchema
15075
15075
  }).strict().refine((value) => value.completedAtMs > value.startedAtMs);
15076
15076
  var usageMeasurementSchema = external_exports.object({
15077
- version: external_exports.union([external_exports.literal(2), external_exports.literal(3)]).optional(),
15077
+ version: external_exports.union([external_exports.literal(2), external_exports.literal(3), external_exports.literal(4)]).optional(),
15078
15078
  value: finiteNonNegativeNumberSchema,
15079
15079
  turnId: external_exports.string().min(1).max(1024),
15080
15080
  at: nonNegativeSafeIntegerSchema
15081
15081
  }).strict();
15082
15082
  var usageMeasurementsSchema = external_exports.object({
15083
- // Unversioned intervals can omit hidden thinking time; do not restore them into averages.
15084
- outputTimings: external_exports.array(usageOutputTimingSchema).transform((values) => values.filter((value) => value.version === 3)).optional(),
15083
+ // Older intervals can omit hidden thinking time; do not restore them into averages.
15084
+ outputTimings: external_exports.array(usageOutputTimingSchema).transform((values) => values.filter((value) => value.version === 4)).optional(),
15085
15085
  // Retain independent TTFT facts when dropping incompatible speed measurements.
15086
- outputTokensPerSecond: usageMeasurementSchema.refine((value) => value.version === 3).optional().catch(void 0),
15086
+ outputTokensPerSecond: usageMeasurementSchema.refine((value) => value.version === 4).optional().catch(void 0),
15087
15087
  timeToFirstOutputMs: usageMeasurementSchema.extend({ value: nonNegativeSafeIntegerSchema }).optional()
15088
15088
  }).strict();
15089
15089
  var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text2) => text2.length <= maximum));
@@ -15549,6 +15549,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15549
15549
  cursor: clientChannelCursorSchema,
15550
15550
  cwd: external_exports.string().optional()
15551
15551
  }),
15552
+ external_exports.object({
15553
+ type: external_exports.literal("harness-inspection-changed"),
15554
+ cursor: clientChannelCursorSchema,
15555
+ harnessId: external_exports.string().min(1)
15556
+ }),
15552
15557
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
15553
15558
  external_exports.object({
15554
15559
  type: external_exports.literal("preferences-changed"),
@@ -15620,6 +15625,8 @@ var clientItemTruncationSchema = external_exports.object({
15620
15625
  var clientTurnSchema = external_exports.object({
15621
15626
  id: external_exports.string().min(1),
15622
15627
  status: external_exports.string().min(1),
15628
+ /** Native history has no terminal evidence; Desktop's status vocabulary cannot express this. */
15629
+ codexhostTurnOutcome: external_exports.object({ status: external_exports.literal("unknown"), reason: external_exports.string() }).optional(),
15623
15630
  items: external_exports.array(external_exports.object({ id: external_exports.string().min(1), type: external_exports.string().min(1) }).passthrough()),
15624
15631
  /** Original file operations, independent of the cumulative Desktop fileChange card.
15625
15632
  * Insert before the named non-file Item; null appends at the end of the Turn.
@@ -16836,6 +16843,7 @@ var THREAD_WATCH_NOTICE_OUTCOMES = [
16836
16843
  "completed",
16837
16844
  "failed",
16838
16845
  "interrupted",
16846
+ "needsInput",
16839
16847
  "timedOut",
16840
16848
  "unreadable",
16841
16849
  "notFound"
@@ -16882,13 +16890,25 @@ var target = { hostId: identity.regex(/^remote-(?:ssh(?:-|:)|control:)/u) };
16882
16890
  var thread = { ...target, threadId: identity };
16883
16891
  var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16884
16892
  external_exports.strictObject({ kind: external_exports.literal("hosts") }),
16893
+ external_exports.strictObject({ kind: external_exports.literal("status"), ...thread }),
16885
16894
  external_exports.strictObject({
16886
16895
  kind: external_exports.literal("list"),
16887
16896
  ...target,
16888
16897
  cursor: external_exports.string().nullable(),
16889
16898
  archived: external_exports.boolean()
16890
16899
  }),
16891
- external_exports.strictObject({ kind: external_exports.literal("read"), ...thread }),
16900
+ external_exports.strictObject({
16901
+ kind: external_exports.literal("read"),
16902
+ ...thread,
16903
+ page: external_exports.strictObject({
16904
+ cursor: external_exports.string().min(1).max(8192).nullable(),
16905
+ epoch: identity.optional(),
16906
+ sortDirection: external_exports.enum(["asc", "desc"]).optional(),
16907
+ limit: external_exports.number().int().min(1).max(20).optional()
16908
+ }).refine((page) => page.cursor === null || page.epoch !== void 0, {
16909
+ message: "A history continuation requires its connection epoch"
16910
+ }).optional()
16911
+ }),
16892
16912
  external_exports.strictObject({
16893
16913
  kind: external_exports.literal("configure"),
16894
16914
  ...thread,
@@ -17267,6 +17287,7 @@ var requestTokenFields = [
17267
17287
  "cacheWrite1hInputTokens",
17268
17288
  "outputTokens",
17269
17289
  "reasoningOutputTokens",
17290
+ "timedOutputTokens",
17270
17291
  "startedAtMs",
17271
17292
  "completedAtMs"
17272
17293
  ];
@@ -17319,6 +17340,14 @@ function parseHostUsageRequest(value) {
17319
17340
  if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17320
17341
  throw new Error("Harness Usage request timing fields must be provided together");
17321
17342
  }
17343
+ if (request.timedOutputTokens !== void 0) {
17344
+ if (request.startedAtMs === void 0) {
17345
+ throw new Error("Harness Usage request 'timedOutputTokens' requires timing fields");
17346
+ }
17347
+ if (request.timedOutputTokens > request.outputTokens) {
17348
+ throw new Error("Harness Usage request 'timedOutputTokens' must not exceed 'outputTokens'");
17349
+ }
17350
+ }
17322
17351
  if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17323
17352
  throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17324
17353
  }
@@ -22845,390 +22874,264 @@ var AntigravityTransportError = class extends Error {
22845
22874
  }
22846
22875
  };
22847
22876
 
22848
- // dist/acp-transport.js
22849
- var AntigravityAcpTransport = class {
22850
- options;
22851
- skipPermissions;
22852
- #child = null;
22853
- #connection = null;
22854
- #initializing = null;
22855
- #sessionId = null;
22856
- #sessionHandler = null;
22857
- #active = null;
22858
- #callbacks = /* @__PURE__ */ new Set();
22859
- #acceptCallbacks = false;
22860
- #promptInterrupted = null;
22861
- #opening = null;
22862
- #pendingEvents = [];
22863
- #closed = false;
22864
- #closing = null;
22865
- #stderrRaw = "";
22866
- get #stderr() {
22867
- return sanitizeDiagnosticTail(this.#stderrRaw);
22868
- }
22869
- #faultSignal = new AbortController();
22870
- constructor(options) {
22871
- this.options = options;
22872
- this.skipPermissions = options.skipPermissions === true;
22873
- }
22874
- get sessionId() {
22875
- return this.#sessionId;
22876
- }
22877
- get isClosed() {
22878
- return this.#closed;
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];
22879
22893
  }
22880
- setSessionEventHandler(handler) {
22881
- this.#sessionHandler = handler;
22882
- if (handler)
22883
- for (const event of this.#pendingEvents.splice(0))
22884
- handler(event);
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;
22885
22930
  }
22886
- initialize() {
22887
- if (this.#closed)
22888
- return Promise.reject(new AntigravityTransportError("unavailable", "Antigravity ACP is closed"));
22889
- return this.#initializing ??= this.#start();
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;
22890
22942
  }
22891
- async #start() {
22892
- try {
22893
- const executable = resolveAntigravityExecutable(this.options);
22894
- if (!executable)
22895
- throw new AntigravityTransportError("notInstalled", "Antigravity CLI was not found");
22896
- const invocation = commandInvocation(executable, this.skipPermissions ? ["acp", "--dangerously-skip-permissions"] : ["acp"], this.options.environment ?? process.env);
22897
- const child = spawn(invocation.command, invocation.arguments, {
22898
- cwd: this.options.cwd,
22899
- env: this.options.environment ?? process.env,
22900
- stdio: ["pipe", "pipe", "pipe"],
22901
- windowsHide: true,
22902
- windowsVerbatimArguments: invocation.windowsVerbatimArguments
22903
- });
22904
- this.#child = child;
22905
- child.stderr.on("data", (chunk) => {
22906
- this.#stderrRaw = (this.#stderrRaw + chunk.toString()).slice(-32e3);
22907
- });
22908
- child.on("error", (error51) => this.#fault(new AntigravityTransportError(error51.code === "ENOENT" ? "notInstalled" : "unavailable", error51.message, { diagnostic: this.#stderr })));
22909
- child.on("exit", (code, signal) => this.#fault(new AntigravityTransportError("processExited", `Antigravity ACP exited (code ${code}, signal ${signal})`, { diagnostic: this.#stderr })));
22910
- child.stdin.on("error", (error51) => this.#fault(this.#error(error51)));
22911
- const stream = ndJsonStream2(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
22912
- const nativeMethods = /* @__PURE__ */ new Set(["session/request_permission", "elicitation/create"]);
22913
- stream.readable = stream.readable.pipeThrough(new TransformStream({
22914
- transform: (message2, controller) => {
22915
- if ("method" in message2 && message2.method === "session/update") {
22916
- const params = message2.params;
22917
- this.#update(params.sessionId, params.update);
22918
- return;
22919
- }
22920
- if ("method" in message2 && nativeMethods.has(message2.method))
22921
- message2.method = `_antigravity/${message2.method}`;
22922
- controller.enqueue(message2);
22923
- }
22924
- }));
22925
- const onElicitation = (request) => this.#callback("sessionId" in request ? request.sessionId : void 0, (handler) => handler.onElicitation(request), { action: "cancel" });
22926
- const client2 = {
22927
- sessionUpdate: ({ sessionId, update }) => this.#update(sessionId, update),
22928
- requestPermission: (request) => this.#callback(request.sessionId, (handler) => handler.onPermission(request), {
22929
- outcome: { outcome: "cancelled" }
22930
- }),
22931
- unstable_createElicitation: onElicitation,
22932
- extMethod: async (method, params) => {
22933
- if (method === "_antigravity/session/request_permission")
22934
- return await client2.requestPermission(params);
22935
- if (method === "_antigravity/elicitation/create")
22936
- return await onElicitation(params);
22937
- throw new AntigravityTransportError("unsupported", `Unsupported ACP client method: ${method}`);
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;
22938
23006
  }
22939
- };
22940
- const connection = new ClientSideConnection(() => client2, stream);
22941
- this.#connection = connection;
22942
- connection.signal.addEventListener("abort", () => this.#fault(new AntigravityTransportError("processExited", "Antigravity ACP connection closed", {
22943
- diagnostic: this.#stderr
22944
- })), { once: true });
22945
- const response = await this.#request(connection.initialize({
22946
- protocolVersion: 1,
22947
- clientCapabilities: { elicitation: { form: {} } }
22948
- }), "initialize");
22949
- if (response.protocolVersion !== 1)
22950
- throw new AntigravityTransportError("protocolError", `Unsupported ACP version ${response.protocolVersion}`);
22951
- return response;
22952
- } catch (error51) {
22953
- await this.close();
22954
- throw this.#error(error51);
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;
22955
23017
  }
23018
+ chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
22956
23019
  }
22957
- async openSession(input) {
22958
- await this.initialize();
22959
- if (this.#closed || !this.#connection || this.#active || this.#opening || this.#sessionId)
22960
- throw new AntigravityTransportError("unavailable", "Close the current ACP session before opening another");
22961
- const connection = this.#connection;
22962
- const buffered = [];
22963
- this.#opening = buffered;
22964
- this.#pendingEvents = [];
22965
- const params = {
22966
- cwd: input.cwd,
22967
- mcpServers: [],
22968
- ...input.additionalDirectories?.length ? { additionalDirectories: input.additionalDirectories } : {},
22969
- ...input.systemPromptAppend ? { _meta: { antigravity: { systemPrompt: { append: input.systemPromptAppend } } } } : {}
22970
- };
22971
- try {
22972
- let request;
22973
- if (input.kind === "create")
22974
- request = connection.newSession(params);
22975
- else {
22976
- if (!input.sessionId)
22977
- throw new AntigravityTransportError("protocolError", "Session ID required for resume/load");
22978
- const target2 = { ...params, sessionId: input.sessionId };
22979
- request = input.kind === "resume" ? connection.resumeSession(target2) : connection.loadSession(target2);
22980
- }
22981
- const result = await this.#request(request, `session/${input.kind === "create" ? "new" : input.kind}`);
22982
- const raw = result;
22983
- const sessionId = raw.sessionId ?? input.sessionId;
22984
- if (!sessionId)
22985
- throw new AntigravityTransportError("protocolError", "Antigravity session/new returned no sessionId");
22986
- this.#sessionId = sessionId;
22987
- const events = buffered.filter((entry) => entry.sessionId === sessionId).map(({ event }) => event);
22988
- if (input.kind !== "load")
22989
- for (const event of events)
22990
- this.#dispatch(event);
22991
- return {
22992
- opened: {
22993
- sessionId,
22994
- ...raw.models ? { models: raw.models } : {},
22995
- ...raw.modes ? { modes: raw.modes } : {},
22996
- ...raw.configOptions ? { configOptions: raw.configOptions } : {},
22997
- ...raw._meta?.antigravity?.tier ? { tier: raw._meta.antigravity.tier } : {}
22998
- },
22999
- replayedEvents: input.kind === "load" ? events : []
23000
- };
23001
- } finally {
23002
- this.#opening = null;
23003
- }
23004
- }
23005
- async setMode(modeId) {
23006
- const { connection, sessionId } = this.#session();
23007
- await this.#request(connection.setSessionMode({ sessionId, modeId }), "session/set_mode");
23008
- }
23009
- async setConfigOption(configId, value) {
23010
- const { connection, sessionId } = this.#session();
23011
- const response = await this.#request(connection.setSessionConfigOption({ sessionId, configId, value }), "session/set_config_option");
23012
- return response.configOptions;
23013
- }
23014
- async prompt(parts, handler) {
23015
- const { connection, sessionId } = this.#session();
23016
- if (this.#active)
23017
- throw new AntigravityTransportError("unavailable", "An ACP prompt is already active");
23018
- this.#active = handler;
23019
- this.#acceptCallbacks = true;
23020
- const interrupted = new AbortController();
23021
- this.#promptInterrupted = interrupted;
23022
- try {
23023
- return await this.#request(connection.prompt({ sessionId, prompt: [...parts] }), "session/prompt", null, interrupted.signal);
23024
- } finally {
23025
- this.#clearCallbacks();
23026
- this.#acceptCallbacks = false;
23027
- this.#active = null;
23028
- this.#promptInterrupted = null;
23029
- }
23030
- }
23031
- async cancel() {
23032
- const { connection, sessionId } = this.#session();
23033
- this.#acceptCallbacks = false;
23034
- this.#clearCallbacks();
23035
- await this.#request(connection.cancel({ sessionId }), "session/cancel");
23036
- }
23037
- async closeSession() {
23038
- const sessionId = this.#sessionId;
23039
- this.#sessionId = null;
23040
- this.#acceptCallbacks = false;
23041
- this.#promptInterrupted?.abort(new AntigravityTransportError("unavailable", "ACP session closed"));
23042
- this.#active = null;
23043
- this.#pendingEvents = [];
23044
- this.#clearCallbacks();
23045
- if (sessionId && this.#connection)
23046
- await this.#request(this.#connection.closeSession({ sessionId }), "session/close", this.options.closeTimeoutMs ?? 2e3);
23047
- }
23048
- close() {
23049
- if (this.#closing)
23050
- return this.#closing;
23051
- this.#closed = true;
23052
- return this.#closing = this.#shutdown();
23053
- }
23054
- async #shutdown() {
23055
- try {
23056
- await this.closeSession();
23057
- } catch (error51) {
23058
- this.#stderrRaw = `${this.#stderrRaw}
23059
- ${this.#error(error51).message}`.slice(-32e3);
23060
- }
23061
- this.#faultSignal.abort(new AntigravityTransportError("unavailable", "Antigravity ACP closed"));
23062
- this.#opening = null;
23063
- this.#sessionHandler = null;
23064
- const child = this.#child;
23065
- if (child && child.exitCode === null && child.signalCode === null && child.pid) {
23066
- const exited = new Promise((resolve) => child.once("exit", () => resolve()));
23067
- const timeout = this.options.closeTimeoutMs ?? 2e3;
23068
- const term = setTimeout(() => child.kill("SIGTERM"), Math.max(1, timeout / 2));
23069
- const kill = setTimeout(() => child.kill("SIGKILL"), Math.max(2, timeout));
23070
- child.stdin.end();
23071
- try {
23072
- await exited;
23073
- } finally {
23074
- clearTimeout(term);
23075
- clearTimeout(kill);
23076
- }
23077
- }
23078
- this.#connection = null;
23079
- this.#child = null;
23080
- }
23081
- #session() {
23082
- if (this.#closed || !this.#connection || !this.#sessionId)
23083
- throw new AntigravityTransportError("unavailable", "Antigravity ACP session is unavailable");
23084
- return { connection: this.#connection, sessionId: this.#sessionId };
23085
- }
23086
- #update(sessionId, raw) {
23087
- if (this.#closed)
23088
- return;
23089
- const event = projectAcpSessionUpdate(raw);
23090
- if (!event)
23091
- return;
23092
- if (this.#opening) {
23093
- this.#opening.push({ sessionId, event });
23094
- return;
23095
- }
23096
- if (sessionId === this.#sessionId)
23097
- this.#dispatch(event);
23098
- }
23099
- #dispatch(event) {
23100
- if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type)) {
23101
- if (this.#sessionHandler)
23102
- this.#sessionHandler(event);
23103
- else
23104
- this.#pendingEvents.push(event);
23105
- } else
23106
- this.#active?.onEvent(event);
23107
- }
23108
- async #callback(sessionId, invoke, cancelled) {
23109
- const active = this.#active;
23110
- if (!active || !this.#acceptCallbacks || sessionId !== this.#sessionId || this.#closed)
23111
- return cancelled;
23112
- let cancel;
23113
- const cancellation = new Promise((resolve) => {
23114
- cancel = () => resolve(cancelled);
23115
- });
23116
- this.#callbacks.add(cancel);
23117
- try {
23118
- return await Promise.race([invoke(active), cancellation]);
23119
- } finally {
23120
- this.#callbacks.delete(cancel);
23121
- }
23122
- }
23123
- #clearCallbacks() {
23124
- for (const cancel of this.#callbacks)
23125
- cancel();
23126
- this.#callbacks.clear();
23127
- }
23128
- async #request(promise2, operation, timeoutMs = this.options.commandTimeoutMs ?? 3e4, signal) {
23129
- let timer;
23130
- let abort;
23131
- const signals = [this.#faultSignal.signal, ...signal ? [signal] : []];
23132
- const interrupted = new Promise((_, reject) => {
23133
- abort = () => reject(signal?.aborted ? signal.reason : this.#faultSignal.signal.reason);
23134
- if (signals.some((candidate) => candidate.aborted))
23135
- abort();
23136
- else
23137
- for (const candidate of signals)
23138
- candidate.addEventListener("abort", abort, { once: true });
23139
- if (timeoutMs !== null)
23140
- timer = setTimeout(() => reject(new AntigravityTransportError("unavailable", `${operation} timed out after ${timeoutMs}ms`, { diagnostic: this.#stderr })), timeoutMs);
23141
- });
23142
- try {
23143
- return await Promise.race([promise2, interrupted]);
23144
- } catch (error51) {
23145
- const normalized = this.#error(error51);
23146
- if (normalized.kind === "unavailable" && normalized.message.includes("timed out"))
23147
- void this.close();
23148
- throw normalized;
23149
- } finally {
23150
- clearTimeout(timer);
23151
- for (const candidate of signals)
23152
- candidate.removeEventListener("abort", abort);
23153
- }
23020
+ if (!wroteCascadeId) {
23021
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23154
23022
  }
23155
- #error(error51) {
23156
- if (error51 instanceof AntigravityTransportError)
23157
- return error51;
23158
- const message2 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
23159
- const code = error51?.code;
23160
- return new AntigravityTransportError(code === -32e3 || /auth|login|sign[ -]?in|unauthenticated/iu.test(message2) ? "authenticationRequired" : "unavailable", message2, { cause: error51, diagnostic: this.#stderr });
23023
+ if (!hasProjectId) {
23024
+ chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
23161
23025
  }
23162
- #fault(error51) {
23163
- if (this.#closed || this.#faultSignal.signal.aborted)
23164
- return;
23165
- this.#faultSignal.abort(error51);
23166
- this.#clearCallbacks();
23167
- void this.close();
23168
- this.options.onFault?.(error51);
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();
23169
23040
  }
23170
- };
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
+ }
23171
23050
 
23172
- // dist/acp-usage.js
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
23173
23057
  import { createReadStream } from "node:fs";
23174
- import path7 from "node:path";
23175
23058
  import { createInterface } from "node:readline";
23176
-
23177
- // dist/native-request-timing.js
23178
- import path6 from "node:path";
23179
-
23180
- // dist/native-protobuf.js
23181
- function decodeVarint(buffer, start) {
23182
- let value = 0n;
23183
- for (let index = 0; index < 10; index++) {
23184
- const byte = buffer[start + index];
23185
- if (byte === void 0 || index === 9 && byte > 1)
23186
- return null;
23187
- value |= BigInt(byte & 127) << BigInt(index * 7);
23188
- if ((byte & 128) === 0)
23189
- return [value, start + index + 1];
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";
23190
23064
  }
23191
- return null;
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;
23082
+ }
23083
+ return `${title.trimEnd()}…`;
23192
23084
  }
23193
- function readProtoFields(blob) {
23194
- const fields = [];
23195
- let offset = 0;
23196
- while (offset < blob.length) {
23197
- if (fields.length >= 1e4)
23198
- return null;
23199
- const tag = decodeVarint(blob, offset);
23200
- if (!tag || tag[0] < 8n || tag[0] > 0xffffffffn)
23201
- return null;
23202
- offset = tag[1];
23203
- const number4 = Number(tag[0] >> 3n);
23204
- const wire = Number(tag[0] & 7n);
23205
- if (wire === 0) {
23206
- const value = decodeVarint(blob, offset);
23207
- if (!value)
23208
- return null;
23209
- fields.push({ number: number4, wire, value: value[0] });
23210
- offset = value[1];
23211
- } else if (wire === 1 || wire === 5) {
23212
- const length = wire === 1 ? 8 : 4;
23213
- if (offset + length > blob.length)
23214
- return null;
23215
- fields.push({ number: number4, wire, value: blob.subarray(offset, offset + length) });
23216
- offset += length;
23217
- } else if (wire === 2) {
23218
- const length = decodeVarint(blob, offset);
23219
- if (!length || length[0] > BigInt(blob.length - length[1]))
23220
- return null;
23221
- offset = length[1];
23222
- const end = offset + Number(length[0]);
23223
- fields.push({ number: number4, wire, value: blob.subarray(offset, end) });
23224
- offset = end;
23225
- } else
23226
- return null;
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;
23113
+ try {
23114
+ value = JSON.parse(line);
23115
+ } catch {
23116
+ continue;
23117
+ }
23118
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
23119
+ yield value;
23120
+ }
23227
23121
  }
23228
- return fields;
23229
23122
  }
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";
23230
23132
 
23231
23133
  // dist/native-request-timing.js
23134
+ import path6 from "node:path";
23232
23135
  var MAX_METADATA_BYTES = 8 * 1024 * 1024;
23233
23136
  var NANOSECONDS_PER_MS = 1000000n;
23234
23137
  var MAX_MS = BigInt(Number.MAX_SAFE_INTEGER);
@@ -23279,31 +23182,40 @@ function stepIndices(fields) {
23279
23182
  function matchesUsage(fields, request) {
23280
23183
  if (!fields)
23281
23184
  return false;
23282
- const input = unsigned(fields, 2), output = unsigned(fields, 3), cached2 = unsigned(fields, 5);
23283
- return input !== null && output !== null && cached2 !== null && input + cached2 + BigInt(request.cacheWriteInputTokens ?? 0) === BigInt(request.inputTokens) && output === BigInt(request.outputTokens) && (request.cachedInputTokens === void 0 || cached2 === BigInt(request.cachedInputTokens));
23185
+ const input = unsigned(fields, 2), output = unsigned(fields, 3), cached2 = unsigned(fields, 5), thought = unsigned(fields, 9);
23186
+ return input !== null && output !== null && cached2 !== null && thought !== null && output >= thought && (request.reasoningOutputTokens === void 0 || thought === BigInt(request.reasoningOutputTokens)) && input + cached2 + BigInt(request.cacheWriteInputTokens ?? 0) === BigInt(request.inputTokens) && output === BigInt(request.outputTokens) && (request.cachedInputTokens === void 0 || cached2 === BigInt(request.cachedInputTokens));
23284
23187
  }
23285
23188
  function closeTo(left, right) {
23286
23189
  const difference = left - right;
23287
23190
  return difference >= -NANOSECONDS_PER_MS && difference <= NANOSECONDS_PER_MS;
23288
23191
  }
23289
- function timing(metadata, generator, request) {
23192
+ function requestMetadata(metadata, generator, request) {
23290
23193
  const chat = message(generator, 1);
23291
- if (!chat || !matchesUsage(message(metadata, 9), request) || !matchesUsage(message(chat, 4), request))
23194
+ const stepUsage = message(metadata, 9);
23195
+ const chatUsage = chat && message(chat, 4);
23196
+ if (!chat || !stepUsage || !chatUsage || !matchesUsage(stepUsage, request) || !matchesUsage(chatUsage, request))
23292
23197
  return null;
23293
- if (unsigned(chat, 14) !== 0n || chat.filter((value) => value.number === 17).length > 1)
23198
+ const thought = unsigned(stepUsage, 9);
23199
+ if (thought === null || thought !== unsigned(chatUsage, 9))
23294
23200
  return null;
23201
+ const facts = { reasoningOutputTokens: Number(thought) };
23202
+ if (unsigned(chat, 14) !== 0n || chat.filter((value) => value.number === 17).length > 1)
23203
+ return facts;
23295
23204
  const created = nanoseconds(message(metadata, 1));
23296
23205
  const started = nanoseconds(message(metadata, 6));
23297
23206
  const completed = nanoseconds(message(metadata, 7));
23298
23207
  const ttft = nanoseconds(message(chat, 11));
23299
23208
  const streamed = nanoseconds(message(chat, 12));
23300
23209
  if (created === null || started === null || completed === null || ttft === null || streamed === null || started < created || completed <= started || streamed <= 0n || !closeTo(started - created, ttft) || !closeTo(completed - started, streamed))
23301
- return null;
23210
+ return facts;
23302
23211
  const startedAtMs = Number(started / NANOSECONDS_PER_MS);
23303
23212
  const completedAtMs = Number(completed / NANOSECONDS_PER_MS);
23304
- return completedAtMs > startedAtMs ? { startedAtMs, completedAtMs } : null;
23213
+ return {
23214
+ ...facts,
23215
+ ...completedAtMs > startedAtMs ? { timing: { startedAtMs, completedAtMs } } : {}
23216
+ };
23305
23217
  }
23306
- async function readAntigravityRequestTimings(nativeSessionId, home, requests, neededSteps = new Set(requests.keys())) {
23218
+ async function readAntigravityRequestMetadata(nativeSessionId, home, requests, neededSteps = new Set(requests.keys())) {
23307
23219
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(nativeSessionId))
23308
23220
  return null;
23309
23221
  let database;
@@ -23327,6 +23239,10 @@ async function readAntigravityRequestTimings(nativeSessionId, home, requests, ne
23327
23239
  const cascade = source && field2(source, 4);
23328
23240
  if (!metadata || !source || cascade?.wire !== 2 || !(cascade.value instanceof Uint8Array) || Buffer.from(cascade.value).toString("utf8") !== nativeSessionId || unsigned(source, 2) !== BigInt(index) || generatorIndex === null || generatorIndex > BigInt(Number.MAX_SAFE_INTEGER))
23329
23241
  continue;
23242
+ const usage = message(metadata, 9);
23243
+ if (!usage || !matchesUsage(usage, request))
23244
+ continue;
23245
+ result.set(index, { reasoningOutputTokens: Number(unsigned(usage, 9)) });
23330
23246
  const generated = generatorQuery.get(Number(generatorIndex));
23331
23247
  if (!(generated?.data instanceof Uint8Array))
23332
23248
  continue;
@@ -23337,9 +23253,11 @@ async function readAntigravityRequestTimings(nativeSessionId, home, requests, ne
23337
23253
  const plannerSteps = [...new Set(indices.filter((step) => requests.get(step)))];
23338
23254
  if (plannerSteps.length !== 1 || plannerSteps[0] !== index)
23339
23255
  continue;
23340
- const clock = timing(metadata, fields, request);
23341
- if (clock)
23342
- result.set(index, clock);
23256
+ const facts = requestMetadata(metadata, fields, request);
23257
+ if (facts)
23258
+ result.set(index, facts);
23259
+ else
23260
+ result.delete(index);
23343
23261
  }
23344
23262
  return result;
23345
23263
  } catch {
@@ -23402,7 +23320,7 @@ function promptUsage(raw) {
23402
23320
  return null;
23403
23321
  }
23404
23322
  }
23405
- function timing2(input) {
23323
+ function timing(input) {
23406
23324
  const { firstOutputAtMs, completedAtMs } = input;
23407
23325
  return count2(firstOutputAtMs) && count2(completedAtMs) && completedAtMs >= firstOutputAtMs ? { startedAtMs: firstOutputAtMs, completedAtMs } : {};
23408
23326
  }
@@ -23513,7 +23431,7 @@ var AntigravitySessionUsageTracker = class {
23513
23431
  this.#turnActive = false;
23514
23432
  }
23515
23433
  #historyComplete() {
23516
- return this.#complete && !this.#invalidated && !this.#turnActive && !this.#pending;
23434
+ return this.#complete && !this.#invalidated && !this.#pending;
23517
23435
  }
23518
23436
  #reconcile() {
23519
23437
  if (this.#pending && usageMatches(requestUsage([...this.#requests.values()]), addUsage(this.#pending.base, this.#pending.usage), false))
@@ -23556,8 +23474,8 @@ var AntigravitySessionUsageTracker = class {
23556
23474
  const requests = this.#consume(transcript, false, cacheUsage, input.completedAtMs !== void 0);
23557
23475
  const single = requests[0];
23558
23476
  const step = [...this.#turnCollectionSteps][0];
23559
- if (!hadPending && !input.hasToolCalls && transcript.timings === null && usage?.inputTokens !== void 0 && usage.outputTokens !== void 0 && requests.length === 1 && single && step !== void 0 && !transcript.toolCallSteps.has(step) && this.#turnCollectionSteps.size === 1 && transcript.complete && !this.#invalidated && usageMatches(requestUsage([single]), usage, true)) {
23560
- const updated = parseHostUsageRequest({ ...single, ...timing2(input) });
23477
+ if (!hadPending && !input.hasToolCalls && transcript.metadata === null && single?.reasoningOutputTokens === 0 && usage?.inputTokens !== void 0 && usage.outputTokens !== void 0 && requests.length === 1 && single && step !== void 0 && !transcript.toolCallSteps.has(step) && this.#turnCollectionSteps.size === 1 && transcript.complete && !this.#invalidated && usageMatches(requestUsage([single]), usage, true)) {
23478
+ const updated = parseHostUsageRequest({ ...single, ...timing(input) });
23561
23479
  requests[0] = updated;
23562
23480
  this.#requests.set(step, updated);
23563
23481
  }
@@ -23572,7 +23490,7 @@ var AntigravitySessionUsageTracker = class {
23572
23490
  const request = this.#requests.get(step);
23573
23491
  if (request?.startedAtMs === void 0 || request.completedAtMs === void 0 || request.completedAtMs <= request.startedAtMs || request.outputTokens <= 0)
23574
23492
  continue;
23575
- tokens += request.outputTokens;
23493
+ tokens += request.timedOutputTokens ?? request.outputTokens;
23576
23494
  milliseconds += request.completedAtMs - request.startedAtMs;
23577
23495
  }
23578
23496
  if (milliseconds > 0)
@@ -23599,13 +23517,18 @@ var AntigravitySessionUsageTracker = class {
23599
23517
  this.#invalidated = true;
23600
23518
  continue;
23601
23519
  }
23602
- let parsed = request;
23520
+ const write = cacheUsage?.cacheWriteInputTokens;
23521
+ const singleMatches = steps.size === 1 && cacheUsage?.inputTokens !== void 0 && request.inputTokens - (request.cacheWriteInputTokens ?? 0) === cacheUsage.inputTokens - (write ?? 0) && request.outputTokens === cacheUsage.outputTokens && (cacheUsage.cachedInputTokens === void 0 || request.cachedInputTokens === cacheUsage.cachedInputTokens);
23522
+ const native = transcript.metadata?.get(step);
23523
+ const thought = !historical && singleMatches && transcript.complete ? cacheUsage?.reasoningOutputTokens ?? native?.reasoningOutputTokens : native?.reasoningOutputTokens;
23524
+ let parsed = parseHostUsageRequest({
23525
+ ...request,
23526
+ ...thought !== void 0 && thought <= request.outputTokens ? { reasoningOutputTokens: thought } : {}
23527
+ });
23603
23528
  if (!historical && request.cachedInputTokens !== void 0 && request.cacheWriteInputTokens === void 0) {
23604
- const write = cacheUsage?.cacheWriteInputTokens;
23605
- const singleMatches = steps.size === 1 && cacheUsage?.inputTokens !== void 0 && request.inputTokens === cacheUsage.inputTokens - (write ?? 0) && request.outputTokens === cacheUsage.outputTokens && (cacheUsage.cachedInputTokens === void 0 || request.cachedInputTokens === cacheUsage.cachedInputTokens);
23606
23529
  if (write === 0 || write !== void 0 && singleMatches && transcript.complete)
23607
23530
  parsed = parseHostUsageRequest({
23608
- ...request,
23531
+ ...parsed,
23609
23532
  inputTokens: request.inputTokens + (write ?? 0),
23610
23533
  cacheWriteInputTokens: write
23611
23534
  });
@@ -23614,9 +23537,13 @@ var AntigravitySessionUsageTracker = class {
23614
23537
  this.#complete = false;
23615
23538
  continue;
23616
23539
  }
23617
- const candidate = transcript.timings?.get(step);
23618
- const clock = candidate && (historical || candidate.startedAtMs >= this.#turnStartedAtMs) && candidate.completedAtMs <= Date.now() ? candidate : void 0;
23619
- if (!historical && this.#turnActive && !finalizing && transcript.timings !== null && !clock && !transcript.toolCallSteps.has(step))
23540
+ const candidate = native?.timing;
23541
+ const clock = parsed.reasoningOutputTokens !== void 0 && parsed.reasoningOutputTokens === native?.reasoningOutputTokens && // A thinking-only request has no output inside the visible window to time.
23542
+ parsed.reasoningOutputTokens < parsed.outputTokens && !transcript.toolCallSteps.has(step) && candidate && (historical || candidate.startedAtMs >= this.#turnStartedAtMs) && candidate.completedAtMs <= Date.now() ? {
23543
+ ...candidate,
23544
+ timedOutputTokens: parsed.outputTokens - parsed.reasoningOutputTokens
23545
+ } : void 0;
23546
+ if (!historical && this.#turnActive && !finalizing && transcript.metadata !== null && !clock && !transcript.toolCallSteps.has(step))
23620
23547
  continue;
23621
23548
  parsed = parseHostUsageRequest({
23622
23549
  ...parsed,
@@ -23631,13 +23558,13 @@ var AntigravitySessionUsageTracker = class {
23631
23558
  }
23632
23559
  async #read(signal, withTimings = true) {
23633
23560
  signal?.throwIfAborted();
23634
- const stream = createReadStream(this.#file, { encoding: "utf8", signal });
23635
- const lines = createInterface({ input: stream, crlfDelay: Infinity });
23561
+ const stream = createReadStream2(this.#file, { encoding: "utf8", signal });
23562
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
23636
23563
  const result = {
23637
23564
  steps: /* @__PURE__ */ new Map(),
23638
23565
  toolCallSteps: /* @__PURE__ */ new Set(),
23639
23566
  complete: true,
23640
- timings: null
23567
+ metadata: null
23641
23568
  };
23642
23569
  try {
23643
23570
  for await (const line of lines) {
@@ -23691,227 +23618,14 @@ var AntigravitySessionUsageTracker = class {
23691
23618
  stream.destroy();
23692
23619
  }
23693
23620
  result.complete &&= [...result.steps.values()].every((request) => request !== null) && [...this.#consumed.keys()].every((step) => result.steps.has(step));
23694
- const unseen = new Set([...result.steps.keys()].filter((step) => !this.#consumed.has(step) && !result.toolCallSteps.has(step)));
23621
+ const unseen = new Set([...result.steps.keys()].filter((step) => !this.#consumed.has(step)));
23695
23622
  if (withTimings && unseen.size > 0)
23696
- result.timings = await readAntigravityRequestTimings(this.#nativeSessionId, this.#home, result.steps, unseen);
23623
+ result.metadata = await readAntigravityRequestMetadata(this.#nativeSessionId, this.#home, result.steps, unseen);
23697
23624
  signal?.throwIfAborted();
23698
23625
  return result;
23699
23626
  }
23700
23627
  };
23701
23628
 
23702
- // dist/delegation.js
23703
- var DELEGATION_ENVIRONMENT_KEYS = [
23704
- "CODEXHOST_CLI_PATH",
23705
- "CODEXHOST_RUNTIME_ENDPOINT",
23706
- "CODEXHOST_RUNTIME_TOKEN",
23707
- "CODEXHOST_THREAD_ID"
23708
- ];
23709
- var ANTIGRAVITY_DELEGATION_INSTRUCTIONS = `This Antigravity Session runs inside codexhost.
23710
- 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.`;
23711
- function antigravityDelegationInstructions(environment) {
23712
- return DELEGATION_ENVIRONMENT_KEYS.every((key) => environment[key]) ? ANTIGRAVITY_DELEGATION_INSTRUCTIONS : void 0;
23713
- }
23714
-
23715
- // dist/fork.js
23716
- import { randomUUID } from "node:crypto";
23717
- import { access as access2, cp, mkdir, open, rm as rm2 } from "node:fs/promises";
23718
- import os3 from "node:os";
23719
- import path9 from "node:path";
23720
-
23721
- // dist/native-trajectory-metadata.js
23722
- var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
23723
- function encodeVarint(value) {
23724
- const bytes = [];
23725
- let remaining = value >>> 0;
23726
- while (remaining >= 128) {
23727
- bytes.push(remaining & 127 | 128);
23728
- remaining >>>= 7;
23729
- }
23730
- bytes.push(remaining);
23731
- return Buffer.from(bytes);
23732
- }
23733
- function encodeLengthDelimited(fieldNumber, payload) {
23734
- return Buffer.concat([
23735
- encodeVarint(fieldNumber << 3 | 2),
23736
- encodeVarint(payload.length),
23737
- Buffer.from(payload)
23738
- ]);
23739
- }
23740
- function minimalTrajectoryMetadataBlob(cascadeId, projectId = DEFAULT_CLI_PROJECT_ID) {
23741
- return Buffer.concat([
23742
- encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")),
23743
- encodeLengthDelimited(18, Buffer.from(projectId, "utf8"))
23744
- ]);
23745
- }
23746
- function minimalRawSummaryBlob(trajectoryId, metadataBlob) {
23747
- return Buffer.concat([
23748
- encodeLengthDelimited(4, Buffer.from(trajectoryId, "utf8")),
23749
- Buffer.from([40, 1]),
23750
- encodeLengthDelimited(17, metadataBlob),
23751
- Buffer.from([176, 1, 4])
23752
- ]);
23753
- }
23754
- function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
23755
- const chunks = [];
23756
- let offset = 0;
23757
- let wroteCascadeId = false;
23758
- let hasProjectId = false;
23759
- while (offset < blob.length) {
23760
- const fieldStart = offset;
23761
- const tagParsed = decodeVarint(blob, offset);
23762
- if (!tagParsed)
23763
- return null;
23764
- const [tag, afterTag] = tagParsed;
23765
- if (tag < 8n || tag > 0xffffffffn)
23766
- return null;
23767
- const fieldNumber = Number(tag >> 3n);
23768
- const wireType = Number(tag & 7n);
23769
- if (fieldNumber === 6 && wireType !== 2)
23770
- return null;
23771
- offset = afterTag;
23772
- if (wireType === 0) {
23773
- const valParsed = decodeVarint(blob, offset);
23774
- if (!valParsed)
23775
- return null;
23776
- offset = valParsed[1];
23777
- } else if (wireType === 1) {
23778
- if (offset + 8 > blob.length)
23779
- return null;
23780
- offset += 8;
23781
- } else if (wireType === 2) {
23782
- const lenParsed = decodeVarint(blob, offset);
23783
- if (!lenParsed)
23784
- return null;
23785
- const [length, afterLen] = lenParsed;
23786
- if (length > BigInt(blob.length - afterLen))
23787
- return null;
23788
- offset = afterLen + Number(length);
23789
- if (fieldNumber === 6) {
23790
- if (!wroteCascadeId) {
23791
- chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23792
- wroteCascadeId = true;
23793
- }
23794
- continue;
23795
- }
23796
- if (fieldNumber === 18)
23797
- hasProjectId = true;
23798
- } else if (wireType === 5) {
23799
- if (offset + 4 > blob.length)
23800
- return null;
23801
- offset += 4;
23802
- } else {
23803
- return null;
23804
- }
23805
- chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
23806
- }
23807
- if (!wroteCascadeId) {
23808
- chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23809
- }
23810
- if (!hasProjectId) {
23811
- chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
23812
- }
23813
- return Buffer.concat(chunks);
23814
- }
23815
-
23816
- // dist/native-turn-boundaries.js
23817
- import { access } from "node:fs/promises";
23818
- async function readNativeTurnCount(dbPath) {
23819
- await access(dbPath);
23820
- const { DatabaseSync } = await import("node:sqlite");
23821
- const db = new DatabaseSync(dbPath, { readOnly: true });
23822
- try {
23823
- const row = db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get();
23824
- return Number(row?.n ?? 0);
23825
- } finally {
23826
- db.close();
23827
- }
23828
- }
23829
- function nativeHistoryError(error51) {
23830
- const missing = error51?.code === "ENOENT";
23831
- return {
23832
- code: missing ? "sessionNotFound" : "nativeFailure",
23833
- message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
23834
- retryable: false
23835
- };
23836
- }
23837
-
23838
- // dist/usage-statistics.js
23839
- import { lstat, opendir } from "node:fs/promises";
23840
- import os2 from "node:os";
23841
- import path8 from "node:path";
23842
-
23843
- // ../../harness-adapter/dist/usage-statistics.js
23844
- import { createReadStream as createReadStream2 } from "node:fs";
23845
- import { createInterface as createInterface2 } from "node:readline";
23846
- var HarnessUsageSourceChangedError = class extends Error {
23847
- code = "HARNESS_USAGE_SOURCE_CHANGED";
23848
- /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
23849
- static is(error51) {
23850
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
23851
- }
23852
- };
23853
- var MAX_SESSION_ID_LENGTH = 512;
23854
- var MAX_CWD_LENGTH = 4096;
23855
- var MAX_SESSION_TITLE_LENGTH = 200;
23856
- function usageSessionTitle(value) {
23857
- if (typeof value !== "string")
23858
- return void 0;
23859
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
23860
- if (!normalized)
23861
- return void 0;
23862
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
23863
- return normalized;
23864
- let title = "";
23865
- for (const character of normalized) {
23866
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
23867
- break;
23868
- title += character;
23869
- }
23870
- return `${title.trimEnd()}…`;
23871
- }
23872
- function sessionIdOk(value) {
23873
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
23874
- }
23875
- function cwdOk(value) {
23876
- 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("\\\\"));
23877
- }
23878
- function withUsageSession(entry, session) {
23879
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
23880
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
23881
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
23882
- if (sessionId === void 0 && cwd === void 0)
23883
- return entry;
23884
- return {
23885
- ...entry,
23886
- ...sessionId !== void 0 ? { sessionId } : {},
23887
- ...cwd !== void 0 ? { cwd } : {},
23888
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
23889
- };
23890
- }
23891
- async function* jsonlRecords(file2, marker, signal) {
23892
- const lines = createInterface2({
23893
- input: createReadStream2(file2, { encoding: "utf8", signal }),
23894
- crlfDelay: Infinity
23895
- });
23896
- for await (const line of lines) {
23897
- if (!line.includes(marker))
23898
- continue;
23899
- let value;
23900
- try {
23901
- value = JSON.parse(line);
23902
- } catch {
23903
- continue;
23904
- }
23905
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
23906
- yield value;
23907
- }
23908
- }
23909
- }
23910
- function nativeTimeMs(value) {
23911
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
23912
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
23913
- }
23914
-
23915
23629
  // dist/usage-statistics.js
23916
23630
  function count3(value) {
23917
23631
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
@@ -24081,184 +23795,602 @@ async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCount
24081
23795
  target2.prepare(`DELETE FROM ${table} WHERE idx >= ?`).run(cutoff);
24082
23796
  }
24083
23797
  }
24084
- target2.exec("COMMIT");
23798
+ target2.exec("COMMIT");
23799
+ } finally {
23800
+ target2.close();
23801
+ }
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();
23810
+ }
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;
23820
+ }
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();
23850
+ }
23851
+ }
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
+ }
23860
+ const { DatabaseSync } = await import("node:sqlite");
23861
+ const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
23862
+ try {
23863
+ db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
23864
+ } finally {
23865
+ db.close();
23866
+ }
23867
+ }
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() {
23968
+ return {
23969
+ ok: false,
23970
+ error: {
23971
+ code: "checkpointNotFound",
23972
+ message: "Antigravity native Turn checkpoint not found",
23973
+ retryable: false
23974
+ }
23975
+ };
23976
+ }
23977
+
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();
24009
+ }
24010
+ }
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
24019
+ };
24020
+ let resolve;
24021
+ const complete = new Promise((done) => {
24022
+ resolve = done;
24023
+ });
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();
24045
+ }
24046
+ };
24047
+ }
24048
+
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;
24078
+ }
24079
+ get isClosed() {
24080
+ return this.#closed;
24081
+ }
24082
+ setSessionEventHandler(handler) {
24083
+ this.#sessionHandler = handler;
24084
+ if (handler)
24085
+ for (const event of this.#pendingEvents.splice(0))
24086
+ handler(event);
24087
+ }
24088
+ initialize() {
24089
+ if (this.#closed)
24090
+ return Promise.reject(new AntigravityTransportError("unavailable", "Antigravity ACP is closed"));
24091
+ return this.#initializing ??= this.#start();
24092
+ }
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}`);
24140
+ }
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);
24187
+ }
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
+ };
24085
24210
  } finally {
24086
- target2.close();
24211
+ this.#opening = null;
24212
+ this.#observeReplay = null;
24087
24213
  }
24088
- await registerDerivedSummary(sourceId, derivedId, home);
24089
- return true;
24090
- } catch (error51) {
24091
- if (owned)
24092
- await removeDerivedDb(derivedId, home);
24093
- throw error51;
24094
- } finally {
24095
- source.close();
24096
24214
  }
24097
- }
24098
- async function registerDerivedSummary(sourceId, derivedId, home) {
24099
- const summaryPath = nativeConversationSummariesDbPath(home);
24100
- try {
24101
- await access2(summaryPath);
24102
- } catch (error51) {
24103
- if (error51.code === "ENOENT")
24104
- return;
24105
- throw error51;
24215
+ async setMode(modeId) {
24216
+ const { connection, sessionId } = this.#session();
24217
+ await this.#request(connection.setSessionMode({ sessionId, modeId }), "session/set_mode");
24106
24218
  }
24107
- const { DatabaseSync } = await import("node:sqlite");
24108
- const summaries = new DatabaseSync(summaryPath);
24109
- try {
24110
- const template = summaries.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?").get(sourceId);
24111
- if (!template)
24112
- return;
24113
- const derived = new DatabaseSync(nativeConversationDbPath(derivedId, home), { readOnly: true });
24114
- let row;
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;
24115
24232
  try {
24116
- const metadata = derived.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get()?.data;
24117
- const trajectoryId = derived.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get()?.trajectory_id;
24118
- row = {
24119
- ...template,
24120
- conversation_id: derivedId,
24121
- status: "CASCADE_RUN_STATUS_IDLE",
24122
- step_count: Number(derived.prepare("SELECT count(*) AS n FROM steps").get()?.n),
24123
- last_user_input_step_index: Number(derived.prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = 14").get()?.idx ?? -1),
24124
- not_fully_idle: 0,
24125
- killed: 0,
24126
- last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
24127
- raw_summary: minimalRawSummaryBlob(String(trajectoryId), Buffer.from(metadata))
24128
- };
24233
+ return await this.#request(connection.prompt({ sessionId, prompt: [...parts] }), "session/prompt", null, interrupted.signal);
24129
24234
  } finally {
24130
- derived.close();
24235
+ this.#clearCallbacks();
24236
+ this.#acceptCallbacks = false;
24237
+ this.#active = null;
24238
+ this.#promptInterrupted = null;
24131
24239
  }
24132
- const columns = Object.keys(template);
24133
- summaries.prepare(`INSERT INTO conversation_summaries (${columns.map((name) => `"${name.replaceAll('"', '""')}"`).join(",")}) VALUES (${columns.map(() => "?").join(",")})`).run(...columns.map((name) => row[name] ?? null));
24134
- } finally {
24135
- summaries.close();
24136
24240
  }
24137
- }
24138
- async function removeDerivedSummary(id, home) {
24139
- try {
24140
- await access2(nativeConversationSummariesDbPath(home));
24141
- } catch (error51) {
24142
- if (error51.code === "ENOENT")
24143
- return;
24144
- throw error51;
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");
24145
24246
  }
24146
- const { DatabaseSync } = await import("node:sqlite");
24147
- const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
24148
- try {
24149
- db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
24150
- } finally {
24151
- db.close();
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);
24152
24257
  }
24153
- }
24154
- async function removeDerivedDb(id, home) {
24155
- const file2 = nativeConversationDbPath(id, home);
24156
- await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
24157
- }
24158
- async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedir()) {
24159
- try {
24160
- await access2(nativeBrainDirPath(sourceId, home));
24161
- } catch (error51) {
24162
- if (error51.code === "ENOENT")
24163
- return false;
24164
- throw error51;
24258
+ close() {
24259
+ if (this.#closing)
24260
+ return this.#closing;
24261
+ this.#closed = true;
24262
+ return this.#closing = this.#shutdown();
24165
24263
  }
24166
- await cp(nativeBrainDirPath(sourceId, home), nativeBrainDirPath(derivedId, home), {
24167
- recursive: true,
24168
- errorOnExist: true,
24169
- force: false,
24170
- filter: (source) => path9.basename(source) !== ".system_generated"
24171
- });
24172
- return true;
24173
- }
24174
- async function openDerivedAntigravitySession(options, input, sourceRef, retained) {
24175
- const environment = { ...options.adapterEnvironment, ...input.environment };
24176
- const home = antigravityHome(environment);
24177
- const derivedId = randomUUID();
24178
- let cloned = false;
24179
- try {
24180
- await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home);
24181
- cloned = true;
24182
- await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
24183
- const result = await options.openSession({
24184
- ...input,
24185
- environment,
24186
- nativeRef: { ...sourceRef, nativeSessionId: derivedId }
24187
- });
24188
- if (result.ok)
24189
- return result;
24190
- const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24191
- return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
24192
- } catch (error51) {
24193
- const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24194
- return {
24195
- ok: false,
24196
- error: {
24197
- ...nativeHistoryError(error51),
24198
- ...cleanupFailure ? { diagnostic: cleanupFailure } : {}
24264
+ async #shutdown() {
24265
+ 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);
24199
24286
  }
24200
- };
24287
+ }
24288
+ this.#connection = null;
24289
+ this.#child = null;
24201
24290
  }
24202
- async function cleanup() {
24203
- if (!cloned)
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 };
24295
+ }
24296
+ #update(sessionId, raw) {
24297
+ if (this.#closed)
24204
24298
  return;
24205
- await Promise.all([
24206
- removeDerivedDb(derivedId, home),
24207
- rm2(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
24208
- removeDerivedSummary(derivedId, home)
24209
- ]);
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);
24305
+ return;
24306
+ }
24307
+ if (sessionId === this.#sessionId)
24308
+ this.#dispatch(event);
24210
24309
  }
24211
- }
24212
- async function forkAntigravitySession(options) {
24213
- const { input, harnessId: harnessId2 } = options;
24214
- if (!validNativeSessionRef(input.sourceRef, harnessId2))
24215
- return {
24216
- ok: false,
24217
- error: {
24218
- code: "invalidRequest",
24219
- message: "Invalid Antigravity source Native Session",
24220
- retryable: false
24221
- }
24222
- };
24223
- const checkpoint = nativeCheckpointRefSchema.safeParse(input.checkpoint);
24224
- if (!checkpoint.success || checkpoint.data.harnessId !== harnessId2 || checkpoint.data.nativeSessionId !== input.sourceRef.nativeSessionId)
24225
- return checkpointError();
24226
- if (options.sourceSession?.isActive)
24227
- return {
24228
- ok: false,
24229
- error: {
24230
- code: "sessionBusy",
24231
- message: "Source Session is busy",
24232
- retryable: true
24233
- }
24234
- };
24235
- const match = /^turn-(0|[1-9]\d*)$/u.exec(checkpoint.data.checkpointId);
24236
- if (!match)
24237
- return checkpointError();
24238
- try {
24239
- const count4 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
24240
- const index = Number(match[1]);
24241
- if (!Number.isSafeInteger(index) || index >= count4)
24242
- return checkpointError();
24243
- return openDerivedAntigravitySession(options, {
24244
- kind: "resume",
24245
- nativeRef: input.sourceRef,
24246
- cwd: input.cwd,
24247
- ...input.environment ? { environment: input.environment } : {}
24248
- }, input.sourceRef, index + 1);
24249
- } catch (error51) {
24250
- return { ok: false, error: nativeHistoryError(error51) };
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);
24251
24318
  }
24252
- }
24253
- function checkpointError() {
24254
- return {
24255
- ok: false,
24256
- error: {
24257
- code: "checkpointNotFound",
24258
- message: "Antigravity native Turn checkpoint not found",
24259
- retryable: false
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);
24260
24332
  }
24261
- };
24333
+ }
24334
+ #clearCallbacks() {
24335
+ for (const cancel of this.#callbacks)
24336
+ cancel();
24337
+ this.#callbacks.clear();
24338
+ }
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);
24352
+ });
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 });
24372
+ }
24373
+ #fault(error51) {
24374
+ if (this.#closed || this.#faultSignal.signal.aborted)
24375
+ return;
24376
+ this.#faultSignal.abort(error51);
24377
+ this.#clearCallbacks();
24378
+ void this.close();
24379
+ this.options.onFault?.(error51);
24380
+ }
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;
24262
24394
  }
24263
24395
 
24264
24396
  // dist/model-catalog.js
@@ -25000,6 +25132,144 @@ var AntigravitySessionImport = class {
25000
25132
  }
25001
25133
  };
25002
25134
 
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
+
25003
25273
  // dist/subagent-transcript.js
25004
25274
  import { open as open2, realpath } from "node:fs/promises";
25005
25275
  import path11 from "node:path";
@@ -25464,7 +25734,6 @@ var AntigravitySession = class {
25464
25734
  #state = {};
25465
25735
  #requested;
25466
25736
  #transport;
25467
- #readers = /* @__PURE__ */ new Set();
25468
25737
  #opening;
25469
25738
  #availableModels = [];
25470
25739
  #configOptions = [];
@@ -25483,6 +25752,8 @@ var AntigravitySession = class {
25483
25752
  #historyOperation = false;
25484
25753
  constructor(options) {
25485
25754
  this.#options = options;
25755
+ if (options.nativeRef)
25756
+ this.#state = { nativeRef: options.nativeRef };
25486
25757
  this.#requested = {
25487
25758
  model: options.model,
25488
25759
  thinkingOptionId: options.thinkingOptionId,
@@ -25585,23 +25856,14 @@ var AntigravitySession = class {
25585
25856
  try {
25586
25857
  this.#turnCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment)));
25587
25858
  } catch {
25588
- this.#turnCount = projectReplayedEventsToTurns({
25859
+ this.#turnCount = Math.max(this.#turnCount, projectReplayedEventsToTurns({
25589
25860
  nativeSessionId: opened.sessionId,
25590
25861
  cwd: this.#options.cwd,
25591
25862
  events: replayedEvents,
25592
25863
  ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {}
25593
- }).length;
25594
- }
25595
- if (!this.#usage) {
25596
- const context = replayedEvents.findLast((event) => event.type === "usage.context");
25597
- this.#usage = new AntigravitySessionUsageTracker({
25598
- nativeSessionId: opened.sessionId,
25599
- homedir: antigravityHome(this.#options.environment),
25600
- expectedInitialTurns: this.#turnCount,
25601
- ...context ? { initialContextUsedTokens: context.used, initialContextWindowTokens: context.size } : {}
25602
- });
25603
- this.#usageWork = this.#replayUsage();
25864
+ }).length);
25604
25865
  }
25866
+ this.#initializeUsage(opened.sessionId, replayedEvents);
25605
25867
  transport.setSessionEventHandler((event) => {
25606
25868
  if (this.#transport === transport && !this.#closed && !this.#faulted)
25607
25869
  this.#sessionEvent(event);
@@ -25631,6 +25893,18 @@ var AntigravitySession = class {
25631
25893
  throw error51;
25632
25894
  }
25633
25895
  }
25896
+ #initializeUsage(nativeSessionId, events) {
25897
+ if (this.#usage)
25898
+ return;
25899
+ const context = events.findLast((event) => event.type === "usage.context");
25900
+ this.#usage = new AntigravitySessionUsageTracker({
25901
+ nativeSessionId,
25902
+ homedir: antigravityHome(this.#options.environment),
25903
+ expectedInitialTurns: this.#turnCount,
25904
+ ...context ? { initialContextUsedTokens: context.used, initialContextWindowTokens: context.size } : {}
25905
+ });
25906
+ this.#usageWork = this.#replayUsage();
25907
+ }
25634
25908
  #setLocatorPermissionMode(permissionModeId) {
25635
25909
  const ref = this.#state.nativeRef;
25636
25910
  if (!ref)
@@ -25821,33 +26095,35 @@ var AntigravitySession = class {
25821
26095
  return err("invalidState", "Session is closed");
25822
26096
  if (!this.nativeRef)
25823
26097
  return ok({ turns: [], state: { ...this.#state } });
25824
- const transport = this.#newTransport(this.#transport?.skipPermissions ?? this.#options.unattended);
25825
- this.#readers.add(transport);
26098
+ const skip = this.#transport?.skipPermissions ?? (this.#options.unattended || this.#requested.permissionModeId === SKIP);
25826
26099
  try {
25827
- await transport.initialize();
25828
- const { opened, replayedEvents } = await transport.openSession({
25829
- kind: "load",
26100
+ const { opened, replayedEvents } = await this.#options.readerPool.loadSession({
25830
26101
  sessionId: this.nativeRef.nativeSessionId,
25831
26102
  cwd: this.#options.cwd,
25832
- ...this.#delegationPrompt()
26103
+ environment: this.#options.environment,
26104
+ skipPermissions: skip,
26105
+ signal: this.#abort.signal
25833
26106
  });
25834
- if (opened.sessionId !== this.nativeRef.nativeSessionId)
25835
- throw new AntigravityTransportError("protocolError", "Snapshot loaded a different Session");
25836
- const snapshot = {
25837
- turns: projectReplayedEventsToTurns({
25838
- nativeSessionId: opened.sessionId,
25839
- cwd: this.#options.cwd,
25840
- events: replayedEvents,
25841
- ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {},
25842
- ...this.#options.adapter.toolOutputLimit !== void 0 ? { outputLimit: this.#options.adapter.toolOutputLimit } : {}
25843
- }),
25844
- state: { ...this.#state }
25845
- };
25846
- await transport.close();
25847
- this.#readers.delete(transport);
25848
- return this.#closed || this.#faulted ? err("invalidState", "Session is closed") : ok(snapshot);
26107
+ if (this.#closed || this.#faulted)
26108
+ return err("invalidState", "Session is closed");
26109
+ const turns = projectReplayedEventsToTurns({
26110
+ nativeSessionId: opened.sessionId,
26111
+ cwd: this.#options.cwd,
26112
+ events: replayedEvents,
26113
+ ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {},
26114
+ ...this.#options.adapter.toolOutputLimit !== void 0 ? { outputLimit: this.#options.adapter.toolOutputLimit } : {}
26115
+ });
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
+ if (!this.#transport) {
26120
+ this.#turnCount = turnCount;
26121
+ this.#initializeUsage(opened.sessionId, replayedEvents);
26122
+ }
26123
+ return ok({ turns, ...this.#transport ? { state: { ...this.#state } } : {} });
25849
26124
  } catch (error51) {
25850
- await transport.close().then(() => this.#readers.delete(transport)).catch(() => void 0);
26125
+ if (this.#closed || this.#faulted)
26126
+ return err("invalidState", "Session is closed");
25851
26127
  return { ok: false, error: normalizeAntigravityError(error51) };
25852
26128
  }
25853
26129
  }
@@ -26066,19 +26342,19 @@ var AntigravitySession = class {
26066
26342
  await this.#usageWork;
26067
26343
  if (this.#usage && this.#isCurrent(turn)) {
26068
26344
  try {
26069
- const timing3 = {
26345
+ const timing2 = {
26070
26346
  ...turn.firstOutputAtMs !== void 0 ? { firstOutputAtMs: turn.firstOutputAtMs } : {},
26071
26347
  completedAtMs
26072
26348
  };
26073
26349
  const update = await this.#usage.collectNewTranscriptRequests({
26074
- ...timing3,
26350
+ ...timing2,
26075
26351
  ...turn.hasToolCalls ? { hasToolCalls: true } : {},
26076
26352
  ...result.usage ? { promptUsage: result.usage } : {},
26077
26353
  signal: this.#abort.signal
26078
26354
  });
26079
26355
  const recorded = this.#usage.recordTurnPromptUsage({
26080
26356
  ...result.usage ? { usage: result.usage } : {},
26081
- ...timing3
26357
+ ...timing2
26082
26358
  });
26083
26359
  if (!this.#isCurrent(turn))
26084
26360
  return;
@@ -26281,12 +26557,7 @@ var AntigravitySession = class {
26281
26557
  this.#transport?.setSessionEventHandler(null);
26282
26558
  if (active)
26283
26559
  await this.#transport?.cancel().catch(() => void 0);
26284
- await Promise.all([
26285
- this.#transport?.close(),
26286
- this.#subagents.close(),
26287
- ...[...this.#readers].map((reader) => reader.close())
26288
- ]);
26289
- this.#readers.clear();
26560
+ await Promise.all([this.#transport?.close(), this.#subagents.close()]);
26290
26561
  this.#options.onClosed(this);
26291
26562
  }
26292
26563
  };
@@ -26311,6 +26582,7 @@ var AntigravityAdapter = class {
26311
26582
  usageStatistics;
26312
26583
  #environment;
26313
26584
  #sessions = /* @__PURE__ */ new Set();
26585
+ #readerPool;
26314
26586
  #cache = /* @__PURE__ */ new Map();
26315
26587
  #inflight = /* @__PURE__ */ new Map();
26316
26588
  #abort = new AbortController();
@@ -26321,6 +26593,7 @@ var AntigravityAdapter = class {
26321
26593
  constructor(options = {}) {
26322
26594
  this.options = options;
26323
26595
  this.#environment = options.environment ?? process.env;
26596
+ this.#readerPool = new AntigravitySnapshotReaderPool(this.options);
26324
26597
  this.sessionImport = new AntigravitySessionImport(this.#environment);
26325
26598
  this.usageStatistics = createAntigravityUsageStatistics(this.#environment);
26326
26599
  }
@@ -26416,7 +26689,22 @@ var AntigravityAdapter = class {
26416
26689
  const common = {
26417
26690
  harnessId,
26418
26691
  adapterEnvironment: this.#environment,
26419
- openSession: (resume) => this.open(resume)
26692
+ openSession: async (resume) => {
26693
+ const result = await this.open(resume);
26694
+ if (!result.ok || !(result.value instanceof AntigravitySession))
26695
+ return result;
26696
+ try {
26697
+ await result.value.initialize();
26698
+ if (this.#closed) {
26699
+ await result.value.close();
26700
+ return err("invalidState", "Adapter is closed");
26701
+ }
26702
+ return result;
26703
+ } catch (error51) {
26704
+ await result.value.close().catch(() => void 0);
26705
+ return { ok: false, error: normalizeAntigravityError(error51) };
26706
+ }
26707
+ }
26420
26708
  };
26421
26709
  try {
26422
26710
  return await (input.kind === "fork" ? forkAntigravitySession({ ...common, input }) : rollbackAntigravityLastTurn({ ...common, input }));
@@ -26446,12 +26734,11 @@ var AntigravityAdapter = class {
26446
26734
  ...input.kind === "resume" ? { nativeRef: input.nativeRef, knownTurnRefs: input.knownTurnRefs } : {},
26447
26735
  unattended,
26448
26736
  adapter: this.options,
26737
+ readerPool: this.#readerPool,
26449
26738
  onClosed: (closed) => this.#sessions.delete(closed)
26450
26739
  });
26451
26740
  this.#sessions.add(session);
26452
26741
  try {
26453
- if (input.kind === "resume")
26454
- await session.initialize();
26455
26742
  if (this.#closed) {
26456
26743
  await session.close();
26457
26744
  return err("invalidState", "Adapter is closed");
@@ -26522,7 +26809,10 @@ var AntigravityAdapter = class {
26522
26809
  this.#cache.clear();
26523
26810
  this.#inflight.clear();
26524
26811
  this.#quota = null;
26525
- await Promise.all([...this.#sessions].map((session) => session.close()));
26812
+ await Promise.all([
26813
+ ...[...this.#sessions].map((session) => session.close()),
26814
+ this.#readerPool.close()
26815
+ ]);
26526
26816
  this.#sessions.clear();
26527
26817
  }
26528
26818
  };