@codexhost/cli-linux-arm64 0.18.0-beta.3 → 0.18.0-beta.5

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 (53) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +102 -57
  4. package/app/console-web.js +168 -123
  5. package/app/desktop-controller.mjs +292 -117
  6. package/app/host-runtime.mjs +5875 -3270
  7. package/app/plugins/antigravity/plugin.mjs +796 -307
  8. package/app/plugins/claude-code/plugin.mjs +214 -103
  9. package/app/plugins/codebuddy/plugin.mjs +108 -63
  10. package/app/plugins/codex-usage/plugin.mjs +94 -49
  11. package/app/plugins/copilot/plugin.mjs +99 -54
  12. package/app/plugins/cursor-cli/plugin.mjs +122 -77
  13. package/app/plugins/deepseek-harness/plugin.mjs +125 -80
  14. package/app/plugins/devin/plugin.mjs +99 -54
  15. package/app/plugins/grok/plugin.mjs +105 -60
  16. package/app/plugins/hermes/plugin.mjs +86 -41
  17. package/app/plugins/kimi-code/plugin.mjs +103 -58
  18. package/app/plugins/kiro-cli/plugin.mjs +99 -54
  19. package/app/plugins/omp/plugin.mjs +90 -45
  20. package/app/plugins/opencode/plugin.mjs +87 -42
  21. package/app/plugins/pi/plugin.mjs +103 -58
  22. package/app/plugins/qoder/plugin.mjs +115 -70
  23. package/app/plugins/qoder-cn/plugin.mjs +115 -70
  24. package/app/plugins/qwen-code/plugin.mjs +110 -65
  25. package/app/plugins/workbuddy/plugin.mjs +108 -63
  26. package/app/plugins/zcode/plugin.mjs +91 -46
  27. package/app/renderer-extension.js +362 -299
  28. package/app/web/assets/index-C0aXz2jD.js +199 -0
  29. package/app/web/codex-agent.png +0 -0
  30. package/app/web/codexhost-settings.js +163 -118
  31. package/app/web/index.html +1 -1
  32. package/app/web/plugins/deepseek-ai__dsh-api-gateway/client.js +1 -1
  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 +61 -61
  35. package/app/web/plugins/deepseek-ai__dsh-client-connection/client.js +1 -1
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +8 -8
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +63 -63
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +12 -12
  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-permission-presets/client.js +1 -1
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +2 -2
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +2 -2
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +9 -13
  46. package/app/web/plugins.json +4 -0
  47. package/app/web/sw.js +1 -6
  48. package/app/web-modules/server.mjs +2443 -1345
  49. package/bin/codexhost +0 -0
  50. package/libexec/codexhost-shim +0 -0
  51. package/libexec/codexhost-updater +0 -0
  52. package/package.json +1 -1
  53. package/app/web/assets/index-aKvkfNJN.js +0 -199
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __codexhostCreateRequire } from "node:module"; const require = __codexhostCreateRequire(import.meta.url);
2
2
  var __defProp = Object.defineProperty;
3
- var __export = (target, all) => {
3
+ var __export = (target2, all) => {
4
4
  for (var name in all)
5
- __defProp(target, name, { get: all[name], enumerable: true });
5
+ __defProp(target2, name, { get: all[name], enumerable: true });
6
6
  };
7
7
 
8
8
  // ../../harness-discovery/dist/environment.js
@@ -411,7 +411,7 @@ function createHarnessInstaller(environment, source) {
411
411
  // dist/antigravity-adapter.js
412
412
  import { spawn } from "node:child_process";
413
413
  import { randomUUID as randomUUID6 } from "node:crypto";
414
- import { readFile as readFile2, unlink } from "node:fs/promises";
414
+ import { access as access2, readFile as readFile2, unlink } from "node:fs/promises";
415
415
  import https3 from "node:https";
416
416
  import os6 from "node:os";
417
417
  import path11 from "node:path";
@@ -1164,8 +1164,8 @@ function defineLazy(object2, key, getter) {
1164
1164
  function objectClone(obj) {
1165
1165
  return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
1166
1166
  }
1167
- function assignProp(target, prop, value) {
1168
- Object.defineProperty(target, prop, {
1167
+ function assignProp(target2, prop, value) {
1168
+ Object.defineProperty(target2, prop, {
1169
1169
  value,
1170
1170
  writable: true,
1171
1171
  enumerable: true,
@@ -1348,35 +1348,35 @@ function normalizeParams(_params) {
1348
1348
  return params;
1349
1349
  }
1350
1350
  function createTransparentProxy(getter) {
1351
- let target;
1351
+ let target2;
1352
1352
  return new Proxy({}, {
1353
1353
  get(_, prop, receiver) {
1354
- target ?? (target = getter());
1355
- return Reflect.get(target, prop, receiver);
1354
+ target2 ?? (target2 = getter());
1355
+ return Reflect.get(target2, prop, receiver);
1356
1356
  },
1357
1357
  set(_, prop, value, receiver) {
1358
- target ?? (target = getter());
1359
- return Reflect.set(target, prop, value, receiver);
1358
+ target2 ?? (target2 = getter());
1359
+ return Reflect.set(target2, prop, value, receiver);
1360
1360
  },
1361
1361
  has(_, prop) {
1362
- target ?? (target = getter());
1363
- return Reflect.has(target, prop);
1362
+ target2 ?? (target2 = getter());
1363
+ return Reflect.has(target2, prop);
1364
1364
  },
1365
1365
  deleteProperty(_, prop) {
1366
- target ?? (target = getter());
1367
- return Reflect.deleteProperty(target, prop);
1366
+ target2 ?? (target2 = getter());
1367
+ return Reflect.deleteProperty(target2, prop);
1368
1368
  },
1369
1369
  ownKeys(_) {
1370
- target ?? (target = getter());
1371
- return Reflect.ownKeys(target);
1370
+ target2 ?? (target2 = getter());
1371
+ return Reflect.ownKeys(target2);
1372
1372
  },
1373
1373
  getOwnPropertyDescriptor(_, prop) {
1374
- target ?? (target = getter());
1375
- return Reflect.getOwnPropertyDescriptor(target, prop);
1374
+ target2 ?? (target2 = getter());
1375
+ return Reflect.getOwnPropertyDescriptor(target2, prop);
1376
1376
  },
1377
1377
  defineProperty(_, prop, descriptor) {
1378
- target ?? (target = getter());
1379
- return Reflect.defineProperty(target, prop, descriptor);
1378
+ target2 ?? (target2 = getter());
1379
+ return Reflect.defineProperty(target2, prop, descriptor);
1380
1380
  }
1381
1381
  });
1382
1382
  }
@@ -11828,15 +11828,15 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) {
11828
11828
 
11829
11829
  // ../../../node_modules/zod/v4/core/to-json-schema.js
11830
11830
  function initializeContext(params) {
11831
- let target = params?.target ?? "draft-2020-12";
11832
- if (target === "draft-4")
11833
- target = "draft-04";
11834
- if (target === "draft-7")
11835
- target = "draft-07";
11831
+ let target2 = params?.target ?? "draft-2020-12";
11832
+ if (target2 === "draft-4")
11833
+ target2 = "draft-04";
11834
+ if (target2 === "draft-7")
11835
+ target2 = "draft-07";
11836
11836
  return {
11837
11837
  processors: params.processors ?? {},
11838
11838
  metadataRegistry: params?.metadata ?? globalRegistry,
11839
- target,
11839
+ target: target2,
11840
11840
  unrepresentable: params?.unrepresentable ?? "throw",
11841
11841
  override: params?.override ?? (() => {
11842
11842
  }),
@@ -12178,8 +12178,8 @@ var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
12178
12178
  return finalize(ctx, schema);
12179
12179
  };
12180
12180
  var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
12181
- const { libraryOptions, target } = params ?? {};
12182
- const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
12181
+ const { libraryOptions, target: target2 } = params ?? {};
12182
+ const ctx = initializeContext({ ...libraryOptions ?? {}, target: target2, io, processors });
12183
12183
  process2(schema, ctx);
12184
12184
  extractDefs(ctx, schema);
12185
12185
  return finalize(ctx, schema);
@@ -13238,8 +13238,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
13238
13238
  catch(params) {
13239
13239
  return _catch2(this, params);
13240
13240
  },
13241
- pipe(target) {
13242
- return pipe(this, target);
13241
+ pipe(target2) {
13242
+ return pipe(this, target2);
13243
13243
  },
13244
13244
  readonly() {
13245
13245
  return readonly(this);
@@ -15469,15 +15469,15 @@ var threadOwnershipListResultSchema = external_exports.object({
15469
15469
  threads: external_exports.array(threadOwnershipSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
15470
15470
  }).strict().superRefine(({ threads }, context) => {
15471
15471
  const seen = /* @__PURE__ */ new Set();
15472
- for (const [index, thread] of threads.entries()) {
15473
- if (seen.has(thread.threadId)) {
15472
+ for (const [index, thread2] of threads.entries()) {
15473
+ if (seen.has(thread2.threadId)) {
15474
15474
  context.addIssue({
15475
15475
  code: "custom",
15476
15476
  message: "Thread ownership-list results must be unique",
15477
15477
  path: ["threads", index, "threadId"]
15478
15478
  });
15479
15479
  }
15480
- seen.add(thread.threadId);
15480
+ seen.add(thread2.threadId);
15481
15481
  }
15482
15482
  });
15483
15483
  var threadSteeringInspectParamsSchema = external_exports.object({
@@ -15686,13 +15686,18 @@ var clientChannelResponseSchema = external_exports.object({
15686
15686
  });
15687
15687
 
15688
15688
  // ../../shared-contracts/dist/thread-catalog.js
15689
- var threadCatalogReadParamsSchema = external_exports.object({ includeArchived: external_exports.boolean().optional() }).strict();
15689
+ var threadCatalogReadParamsSchema = external_exports.object({
15690
+ includeArchived: external_exports.boolean().optional(),
15691
+ /** Absent means first page; null means this branch is exhausted. Native cursors only. */
15692
+ officialCursor: external_exports.object({ live: external_exports.string().nullable(), archived: external_exports.string().nullable().optional() }).strict().optional()
15693
+ }).strict();
15690
15694
  var threadCatalogReadResultSchema = external_exports.object({
15691
15695
  threads: external_exports.array(jsonObjectSchema),
15692
15696
  ownership: external_exports.array(threadOwnershipSchema),
15693
15697
  /** Known archived IDs, including visible local external records even when their rows are
15694
- * excluded. Native archived IDs are complete only when includeArchived is true. */
15695
- archivedThreadIds: external_exports.array(hostThreadIdSchema)
15698
+ * excluded. Native archived IDs describe only the returned page, never a complete set. */
15699
+ archivedThreadIds: external_exports.array(hostThreadIdSchema),
15700
+ officialCursor: external_exports.object({ live: external_exports.string().nullable(), archived: external_exports.string().nullable().optional() }).strict().optional()
15696
15701
  }).strict();
15697
15702
 
15698
15703
  // ../../shared-contracts/dist/voice.js
@@ -15907,7 +15912,7 @@ var idleReleaseSettingsSchema = external_exports.strictObject({
15907
15912
  });
15908
15913
  var DEFAULT_IDLE_RELEASE_SETTINGS = Object.freeze({
15909
15914
  enabled: false,
15910
- timeoutMinutes: 30
15915
+ timeoutMinutes: 10
15911
15916
  });
15912
15917
 
15913
15918
  // ../../shared-contracts/dist/harness-preferences.js
@@ -16810,6 +16815,44 @@ var remoteSshSetupParamsSchema = external_exports.object({
16810
16815
  }).strict();
16811
16816
  var remoteSshSetupResultSchema = external_exports.object({ state: external_exports.enum(["installed", "not-installed"]) }).strict();
16812
16817
 
16818
+ // ../../shared-contracts/dist/remote-sessions.js
16819
+ var REMOTE_CONTROLLER_REQUEST_MAX_BYTES = 16 * 1024;
16820
+ var identity = external_exports.string().min(1).max(1024);
16821
+ var target = { hostId: identity.regex(/^remote-(?:ssh(?:-|:)|control:)/u) };
16822
+ var thread = { ...target, threadId: identity };
16823
+ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16824
+ external_exports.strictObject({ kind: external_exports.literal("hosts") }),
16825
+ external_exports.strictObject({
16826
+ kind: external_exports.literal("list"),
16827
+ ...target,
16828
+ cursor: external_exports.string().nullable(),
16829
+ archived: external_exports.boolean()
16830
+ }),
16831
+ external_exports.strictObject({ kind: external_exports.literal("read"), ...thread }),
16832
+ external_exports.strictObject({
16833
+ kind: external_exports.literal("prompt"),
16834
+ ...thread,
16835
+ epoch: identity,
16836
+ text: external_exports.string().min(1).max(8e3),
16837
+ requestId: identity.optional()
16838
+ }),
16839
+ external_exports.strictObject({ kind: external_exports.literal("interrupt"), ...thread, epoch: identity, turnId: identity }),
16840
+ external_exports.strictObject({
16841
+ kind: external_exports.literal("rename"),
16842
+ ...thread,
16843
+ epoch: identity,
16844
+ name: external_exports.string().min(1).max(512)
16845
+ }),
16846
+ external_exports.strictObject({ kind: external_exports.literal("archive"), ...thread, epoch: identity, archived: external_exports.boolean() }),
16847
+ external_exports.strictObject({
16848
+ kind: external_exports.literal("respond"),
16849
+ ...thread,
16850
+ epoch: identity,
16851
+ requestId: external_exports.union([identity, external_exports.number().int()]),
16852
+ result: external_exports.record(external_exports.string(), external_exports.unknown())
16853
+ })
16854
+ ]);
16855
+
16813
16856
  // ../../shared-contracts/dist/remote-connections.js
16814
16857
  var hostId = external_exports.string().min(1).max(1024);
16815
16858
  var codexSshConnectionSchema = external_exports.object({
@@ -16830,7 +16873,9 @@ var codexSshDraftSchema = external_exports.strictObject({
16830
16873
  identity: external_exports.string().max(4096).nullable()
16831
16874
  });
16832
16875
  var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
16876
+ external_exports.strictObject({ action: external_exports.literal("session"), operation: remoteSessionOperationSchema }),
16833
16877
  external_exports.strictObject({ action: external_exports.literal("list") }),
16878
+ external_exports.strictObject({ action: external_exports.literal("catalog") }),
16834
16879
  external_exports.strictObject({
16835
16880
  action: external_exports.literal("read-thread"),
16836
16881
  hostId: hostId.refine((id) => id !== "local"),
@@ -17085,9 +17130,9 @@ function resolveAntigravityExecutable(input = {}) {
17085
17130
 
17086
17131
  // dist/fork.js
17087
17132
  import { randomUUID as randomUUID2 } from "node:crypto";
17088
- import { copyFile, cp, mkdir as mkdir2 } from "node:fs/promises";
17089
- import os3 from "node:os";
17090
- import path6 from "node:path";
17133
+ import { access, copyFile, cp, mkdir as mkdir2 } from "node:fs/promises";
17134
+ import os4 from "node:os";
17135
+ import path7 from "node:path";
17091
17136
 
17092
17137
  // dist/history.js
17093
17138
  import { randomUUID } from "node:crypto";
@@ -17386,21 +17431,585 @@ var AntigravityHistory = class _AntigravityHistory {
17386
17431
  } finally {
17387
17432
  await rm2(temporary, { force: true }).catch(() => void 0);
17388
17433
  }
17389
- });
17434
+ });
17435
+ }
17436
+ };
17437
+
17438
+ // dist/native-turn-boundaries.js
17439
+ async function nativeTurnBoundaryError(dbPath, sidecarTurnCount) {
17440
+ try {
17441
+ const { DatabaseSync } = await import("node:sqlite");
17442
+ const db = new DatabaseSync(dbPath, { readOnly: true });
17443
+ try {
17444
+ const counts = db.prepare("SELECT count(*) AS steps, count(CASE WHEN step_type = 14 THEN 1 END) AS turns FROM steps").get();
17445
+ if (counts.steps > 0 && counts.turns !== sidecarTurnCount) {
17446
+ return {
17447
+ code: "unsupported",
17448
+ message: `Antigravity cannot fork or roll back precisely: native history has ${counts.turns} user_input boundaries but sidecar history has ${sidecarTurnCount} Turns`,
17449
+ retryable: false
17450
+ };
17451
+ }
17452
+ } finally {
17453
+ db.close();
17454
+ }
17455
+ } catch {
17456
+ }
17457
+ return null;
17458
+ }
17459
+
17460
+ // dist/usage-statistics.js
17461
+ import { lstat, opendir } from "node:fs/promises";
17462
+ import os3 from "node:os";
17463
+ import path6 from "node:path";
17464
+
17465
+ // ../../harness-adapter/dist/usage-statistics.js
17466
+ import { createReadStream } from "node:fs";
17467
+ import { createInterface } from "node:readline";
17468
+ var HarnessUsageSourceChangedError = class extends Error {
17469
+ code = "HARNESS_USAGE_SOURCE_CHANGED";
17470
+ /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
17471
+ static is(error51) {
17472
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
17473
+ }
17474
+ };
17475
+ var MAX_SESSION_ID_LENGTH = 512;
17476
+ var MAX_CWD_LENGTH = 4096;
17477
+ var MAX_SESSION_TITLE_LENGTH = 200;
17478
+ function usageSessionTitle(value) {
17479
+ if (typeof value !== "string")
17480
+ return void 0;
17481
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17482
+ if (!normalized)
17483
+ return void 0;
17484
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
17485
+ return normalized;
17486
+ let title = "";
17487
+ for (const character of normalized) {
17488
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
17489
+ break;
17490
+ title += character;
17491
+ }
17492
+ return `${title.trimEnd()}…`;
17493
+ }
17494
+ function sessionIdOk(value) {
17495
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
17496
+ }
17497
+ function cwdOk(value) {
17498
+ 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("\\\\"));
17499
+ }
17500
+ function withUsageSession(entry, session) {
17501
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
17502
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
17503
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
17504
+ if (sessionId === void 0 && cwd === void 0)
17505
+ return entry;
17506
+ return {
17507
+ ...entry,
17508
+ ...sessionId !== void 0 ? { sessionId } : {},
17509
+ ...cwd !== void 0 ? { cwd } : {},
17510
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
17511
+ };
17512
+ }
17513
+ async function* jsonlRecords(file2, marker, signal) {
17514
+ const lines = createInterface({
17515
+ input: createReadStream(file2, { encoding: "utf8", signal }),
17516
+ crlfDelay: Infinity
17517
+ });
17518
+ for await (const line of lines) {
17519
+ if (!line.includes(marker))
17520
+ continue;
17521
+ let value;
17522
+ try {
17523
+ value = JSON.parse(line);
17524
+ } catch {
17525
+ continue;
17526
+ }
17527
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
17528
+ yield value;
17529
+ }
17530
+ }
17531
+ }
17532
+ function nativeTimeMs(value) {
17533
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
17534
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
17535
+ }
17536
+
17537
+ // dist/usage-statistics.js
17538
+ function count2(value) {
17539
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
17540
+ }
17541
+ function antigravityHome(environment) {
17542
+ return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os3.homedir();
17543
+ }
17544
+ function transcriptPath(brainRoot, conversationId) {
17545
+ return path6.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
17546
+ }
17547
+ function isMissing(error51) {
17548
+ const code = error51?.code;
17549
+ return code === "ENOENT" || code === "ENOTDIR";
17550
+ }
17551
+ async function lstatIfPresent(target2) {
17552
+ try {
17553
+ return await lstat(target2);
17554
+ } catch (error51) {
17555
+ if (isMissing(error51))
17556
+ return null;
17557
+ throw error51;
17558
+ }
17559
+ }
17560
+ async function transcriptFingerprint(file2) {
17561
+ const logs = path6.dirname(file2);
17562
+ for (const directory of [path6.dirname(logs), logs]) {
17563
+ if (!(await lstatIfPresent(directory))?.isDirectory())
17564
+ return null;
17565
+ }
17566
+ const info = await lstatIfPresent(file2);
17567
+ return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
17568
+ }
17569
+ async function listTranscripts(brainRoot, signal) {
17570
+ signal.throwIfAborted();
17571
+ const conversations = await opendir(brainRoot).catch((error51) => {
17572
+ if (error51.code === "ENOENT")
17573
+ return null;
17574
+ throw error51;
17575
+ });
17576
+ if (!conversations)
17577
+ return [];
17578
+ const sources = [];
17579
+ for await (const entry of conversations) {
17580
+ signal.throwIfAborted();
17581
+ if (!entry.isDirectory())
17582
+ continue;
17583
+ const file2 = transcriptPath(brainRoot, entry.name);
17584
+ const fingerprint = await transcriptFingerprint(file2);
17585
+ if (fingerprint)
17586
+ sources.push({ id: file2, fingerprint });
17587
+ }
17588
+ return sources;
17589
+ }
17590
+ async function readAntigravityUsage(file2, signal) {
17591
+ const sessionId = path6.basename(path6.resolve(file2, "..", "..", ".."));
17592
+ const requests = /* @__PURE__ */ new Map();
17593
+ for await (const record3 of jsonlRecords(file2, '"input_tokens"', signal)) {
17594
+ if (record3.type !== "PLANNER_RESPONSE")
17595
+ continue;
17596
+ const step = count2(record3.step_index);
17597
+ const input = count2(record3.input_tokens);
17598
+ const output = count2(record3.output_tokens);
17599
+ const cached2 = count2(record3.cache_read_tokens);
17600
+ const at = nativeTimeMs(record3.created_at);
17601
+ if (step === null || input === null || output === null || at === null)
17602
+ continue;
17603
+ requests.set(step, withUsageSession({
17604
+ id: `${String(record3.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
17605
+ occurredAtMs: at,
17606
+ inputTokens: input + (cached2 ?? 0),
17607
+ ...cached2 !== null ? { cachedInputTokens: cached2 } : {},
17608
+ outputTokens: output
17609
+ }, { sessionId }));
17610
+ }
17611
+ return [...requests.values()];
17612
+ }
17613
+ function createAntigravityUsageStatistics(environment) {
17614
+ const brainRoot = nativeBrainRoot(antigravityHome(environment));
17615
+ let listed = /* @__PURE__ */ new Map();
17616
+ return Object.freeze({
17617
+ async listSources(signal) {
17618
+ const sources = await listTranscripts(brainRoot, signal);
17619
+ listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
17620
+ return sources;
17621
+ },
17622
+ async readSource(id, signal) {
17623
+ const expected = listed.get(id);
17624
+ let entries;
17625
+ try {
17626
+ entries = await readAntigravityUsage(id, signal);
17627
+ } catch (error51) {
17628
+ if (expected !== void 0 && isMissing(error51)) {
17629
+ throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
17630
+ }
17631
+ throw error51;
17632
+ }
17633
+ if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
17634
+ throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
17635
+ }
17636
+ return entries;
17637
+ }
17638
+ });
17639
+ }
17640
+
17641
+ // dist/fork.js
17642
+ var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
17643
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
17644
+ function nativeConversationDbPath(nativeSessionId, homedir2 = os4.homedir()) {
17645
+ return path7.join(homedir2, ".gemini", "antigravity-cli", "conversations", `${nativeSessionId}.db`);
17646
+ }
17647
+ function nativeConversationSummariesDbPath(homedir2 = os4.homedir()) {
17648
+ return path7.join(homedir2, ".gemini", "antigravity-cli", "conversation_summaries.db");
17649
+ }
17650
+ function nativeBrainRoot(homedir2 = os4.homedir()) {
17651
+ return path7.join(homedir2, ".gemini", "antigravity-cli", "brain");
17652
+ }
17653
+ function nativeBrainDirPath(nativeSessionId, homedir2 = os4.homedir()) {
17654
+ return path7.join(nativeBrainRoot(homedir2), nativeSessionId);
17655
+ }
17656
+ function encodeVarint(value) {
17657
+ const bytes = [];
17658
+ let remaining = value >>> 0;
17659
+ while (remaining >= 128) {
17660
+ bytes.push(remaining & 127 | 128);
17661
+ remaining >>>= 7;
17662
+ }
17663
+ bytes.push(remaining);
17664
+ return Buffer.from(bytes);
17665
+ }
17666
+ function decodeVarint(buffer, startOffset) {
17667
+ let value = 0;
17668
+ let shift = 0;
17669
+ let offset = startOffset;
17670
+ while (offset < buffer.length) {
17671
+ const byte = buffer[offset];
17672
+ if (byte === void 0)
17673
+ return null;
17674
+ offset += 1;
17675
+ value += (byte & 127) * 2 ** shift;
17676
+ if ((byte & 128) === 0)
17677
+ return [value, offset];
17678
+ shift += 7;
17679
+ if (shift > 53)
17680
+ return null;
17681
+ }
17682
+ return null;
17683
+ }
17684
+ function encodeLengthDelimited(fieldNumber, payload) {
17685
+ return Buffer.concat([
17686
+ encodeVarint(fieldNumber << 3 | 2),
17687
+ encodeVarint(payload.length),
17688
+ Buffer.from(payload)
17689
+ ]);
17690
+ }
17691
+ function minimalTrajectoryMetadataBlob(cascadeId, projectId = DEFAULT_CLI_PROJECT_ID) {
17692
+ return Buffer.concat([
17693
+ encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")),
17694
+ encodeLengthDelimited(18, Buffer.from(projectId, "utf8"))
17695
+ ]);
17696
+ }
17697
+ function minimalRawSummaryBlob(trajectoryId, metadataBlob) {
17698
+ return Buffer.concat([
17699
+ encodeLengthDelimited(4, Buffer.from(trajectoryId, "utf8")),
17700
+ Buffer.from([40, 1]),
17701
+ encodeLengthDelimited(17, metadataBlob),
17702
+ Buffer.from([176, 1, 4])
17703
+ ]);
17704
+ }
17705
+ function updateTrajectoryMetadataCascadeId(blob, cascadeId) {
17706
+ if (!blob || blob.length === 0)
17707
+ return minimalTrajectoryMetadataBlob(cascadeId);
17708
+ return rewriteTrajectoryMetadataCascadeId(blob, cascadeId) ?? minimalTrajectoryMetadataBlob(cascadeId);
17709
+ }
17710
+ function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
17711
+ const chunks = [];
17712
+ let offset = 0;
17713
+ let wroteCascadeId = false;
17714
+ let hasProjectId = false;
17715
+ while (offset < blob.length) {
17716
+ const fieldStart = offset;
17717
+ const tagParsed = decodeVarint(blob, offset);
17718
+ if (!tagParsed)
17719
+ return null;
17720
+ const [tag, afterTag] = tagParsed;
17721
+ const fieldNumber = tag >>> 3;
17722
+ const wireType = tag & 7;
17723
+ offset = afterTag;
17724
+ if (wireType === 0) {
17725
+ const valParsed = decodeVarint(blob, offset);
17726
+ if (!valParsed)
17727
+ return null;
17728
+ offset = valParsed[1];
17729
+ chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
17730
+ } else if (wireType === 1) {
17731
+ if (offset + 8 > blob.length)
17732
+ return null;
17733
+ offset += 8;
17734
+ chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
17735
+ } else if (wireType === 2) {
17736
+ const lenParsed = decodeVarint(blob, offset);
17737
+ if (!lenParsed)
17738
+ return null;
17739
+ const [length, afterLen] = lenParsed;
17740
+ if (afterLen + length > blob.length)
17741
+ return null;
17742
+ offset = afterLen + length;
17743
+ if (fieldNumber === 6) {
17744
+ if (!wroteCascadeId) {
17745
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
17746
+ wroteCascadeId = true;
17747
+ }
17748
+ } else {
17749
+ if (fieldNumber === 18)
17750
+ hasProjectId = true;
17751
+ chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
17752
+ }
17753
+ } else if (wireType === 5) {
17754
+ if (offset + 4 > blob.length)
17755
+ return null;
17756
+ offset += 4;
17757
+ chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
17758
+ } else {
17759
+ return null;
17760
+ }
17761
+ }
17762
+ if (!wroteCascadeId) {
17763
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
17764
+ }
17765
+ if (!hasProjectId) {
17766
+ chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
17767
+ }
17768
+ return Buffer.concat(chunks);
17769
+ }
17770
+ async function pathExists(targetPath2) {
17771
+ return access(targetPath2).then(() => true, (error51) => {
17772
+ if (error51?.code === "ENOENT")
17773
+ return false;
17774
+ throw error51;
17775
+ });
17776
+ }
17777
+ function readConversationSummaryRow(DatabaseSync, summariesDbPath, conversationId) {
17778
+ try {
17779
+ const sumDb = new DatabaseSync(summariesDbPath);
17780
+ try {
17781
+ const stmt = sumDb.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?");
17782
+ return stmt.get(conversationId);
17783
+ } finally {
17784
+ sumDb.close();
17785
+ }
17786
+ } catch {
17787
+ return void 0;
17788
+ }
17789
+ }
17790
+ function upsertConversationSummaryRow(DatabaseSync, summariesDbPath, conversationId, trajectoryId, metadataBlob, stepCount, templateRow) {
17791
+ try {
17792
+ const sumDb = new DatabaseSync(summariesDbPath);
17793
+ try {
17794
+ sumDb.exec(`
17795
+ CREATE TABLE IF NOT EXISTS \`conversation_summaries\` (
17796
+ \`conversation_id\` text,
17797
+ \`title\` text NOT NULL DEFAULT "",
17798
+ \`preview\` text NOT NULL DEFAULT "",
17799
+ \`step_count\` integer NOT NULL DEFAULT 0,
17800
+ \`last_modified_time\` datetime NOT NULL,
17801
+ \`workspace_uris\` text NOT NULL,
17802
+ \`status\` text NOT NULL DEFAULT "",
17803
+ \`source\` text NOT NULL DEFAULT "",
17804
+ \`project_id\` text NOT NULL DEFAULT "",
17805
+ \`agent_name\` text NOT NULL DEFAULT "",
17806
+ \`parent_conversation_id\` text NOT NULL DEFAULT "",
17807
+ \`nesting_depth\` integer NOT NULL DEFAULT 0,
17808
+ \`battle_id\` text NOT NULL DEFAULT "",
17809
+ \`winning_conversation_id\` text NOT NULL DEFAULT "",
17810
+ \`not_fully_idle\` numeric NOT NULL DEFAULT false,
17811
+ \`killed\` numeric NOT NULL DEFAULT false,
17812
+ \`last_user_input_time\` datetime NOT NULL,
17813
+ \`last_user_input_step_index\` integer NOT NULL DEFAULT -1,
17814
+ \`app_data_dir\` text NOT NULL DEFAULT "",
17815
+ \`raw_summary\` blob,
17816
+ \`group_id\` TEXT NOT NULL DEFAULT '',
17817
+ PRIMARY KEY (\`conversation_id\`)
17818
+ );
17819
+ `);
17820
+ const now = (/* @__PURE__ */ new Date()).toISOString();
17821
+ const rawSummary = minimalRawSummaryBlob(trajectoryId, metadataBlob);
17822
+ if (templateRow) {
17823
+ const cols = Object.keys(templateRow);
17824
+ const newRow = {
17825
+ ...templateRow,
17826
+ conversation_id: conversationId,
17827
+ step_count: stepCount,
17828
+ last_modified_time: now,
17829
+ ...stepCount === 0 ? { last_user_input_step_index: -1 } : {},
17830
+ raw_summary: rawSummary
17831
+ };
17832
+ const placeholders = cols.map(() => "?").join(", ");
17833
+ const values = cols.map((col) => newRow[col]);
17834
+ sumDb.prepare(`INSERT OR REPLACE INTO conversation_summaries (${cols.map((c) => `\`${c}\``).join(", ")}) VALUES (${placeholders})`).run(...values);
17835
+ } else {
17836
+ sumDb.prepare(`INSERT OR REPLACE INTO conversation_summaries (
17837
+ \`conversation_id\`, \`title\`, \`preview\`, \`step_count\`, \`last_modified_time\`,
17838
+ \`workspace_uris\`, \`status\`, \`source\`, \`project_id\`, \`agent_name\`,
17839
+ \`parent_conversation_id\`, \`nesting_depth\`, \`battle_id\`, \`winning_conversation_id\`,
17840
+ \`not_fully_idle\`, \`killed\`, \`last_user_input_time\`, \`last_user_input_step_index\`,
17841
+ \`app_data_dir\`, \`raw_summary\`, \`group_id\`
17842
+ ) VALUES (?, '', '', ?, ?, '[]', 'CASCADE_RUN_STATUS_IDLE', '', ?, '', '', 0, '', '', 0, 0, ?, -1, '', ?, '')`).run(conversationId, stepCount, now, DEFAULT_CLI_PROJECT_ID, now, rawSummary);
17843
+ }
17844
+ } finally {
17845
+ sumDb.close();
17846
+ }
17847
+ } catch {
17848
+ }
17849
+ }
17850
+ async function seedNativeConversationDb(nativeSessionId, homedir2 = os4.homedir(), templateSummaryRow) {
17851
+ let DatabaseSync;
17852
+ try {
17853
+ ({ DatabaseSync } = await import("node:sqlite"));
17854
+ } catch {
17855
+ return false;
17856
+ }
17857
+ const targetDb = nativeConversationDbPath(nativeSessionId, homedir2);
17858
+ const summariesDbPath = nativeConversationSummariesDbPath(homedir2);
17859
+ const trajectoryId = randomUUID2();
17860
+ const metadataBlob = minimalTrajectoryMetadataBlob(nativeSessionId);
17861
+ try {
17862
+ await mkdir2(path7.dirname(targetDb), { recursive: true });
17863
+ const db = new DatabaseSync(targetDb);
17864
+ try {
17865
+ db.exec(`
17866
+ CREATE TABLE IF NOT EXISTS \`trajectory_meta\` (
17867
+ \`trajectory_id\` text,
17868
+ \`cascade_id\` text,
17869
+ \`trajectory_type\` integer,
17870
+ \`source\` integer,
17871
+ PRIMARY KEY (\`trajectory_id\`)
17872
+ );
17873
+ CREATE TABLE IF NOT EXISTS \`steps\` (
17874
+ \`idx\` integer,
17875
+ \`step_type\` integer NOT NULL DEFAULT 0,
17876
+ \`status\` integer NOT NULL DEFAULT 0,
17877
+ \`has_subtrajectory\` numeric NOT NULL DEFAULT false,
17878
+ \`metadata\` blob,
17879
+ \`error_details\` blob,
17880
+ \`permissions\` blob,
17881
+ \`task_details\` blob,
17882
+ \`render_info\` blob,
17883
+ \`step_payload\` blob,
17884
+ \`step_format\` integer NOT NULL DEFAULT 0,
17885
+ PRIMARY KEY (\`idx\`)
17886
+ );
17887
+ CREATE INDEX IF NOT EXISTS \`idx_steps_status\` ON \`steps\`(\`status\`);
17888
+ CREATE INDEX IF NOT EXISTS \`idx_steps_step_type\` ON \`steps\`(\`step_type\`);
17889
+ CREATE TABLE IF NOT EXISTS \`gen_metadata\` (
17890
+ \`idx\` integer,
17891
+ \`data\` blob,
17892
+ \`size\` integer NOT NULL DEFAULT 0,
17893
+ PRIMARY KEY (\`idx\`)
17894
+ );
17895
+ CREATE TABLE IF NOT EXISTS \`executor_metadata\` (
17896
+ \`idx\` integer,
17897
+ \`data\` blob,
17898
+ PRIMARY KEY (\`idx\`)
17899
+ );
17900
+ CREATE TABLE IF NOT EXISTS \`parent_references\` (
17901
+ \`idx\` integer,
17902
+ \`data\` blob,
17903
+ PRIMARY KEY (\`idx\`)
17904
+ );
17905
+ CREATE TABLE IF NOT EXISTS \`trajectory_metadata_blob\` (
17906
+ \`id\` text DEFAULT "main",
17907
+ \`data\` blob,
17908
+ PRIMARY KEY (\`id\`)
17909
+ );
17910
+ CREATE TABLE IF NOT EXISTS \`battle_mode_infos\` (
17911
+ \`idx\` integer,
17912
+ \`data\` blob,
17913
+ PRIMARY KEY (\`idx\`)
17914
+ );
17915
+ `);
17916
+ db.prepare("DELETE FROM trajectory_meta").run();
17917
+ db.prepare("INSERT INTO trajectory_meta (trajectory_id, cascade_id, trajectory_type, source) VALUES (?, ?, 4, 17)").run(trajectoryId, nativeSessionId);
17918
+ db.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(metadataBlob);
17919
+ } finally {
17920
+ db.close();
17921
+ }
17922
+ } catch {
17923
+ return false;
17924
+ }
17925
+ try {
17926
+ const existingSummary = templateSummaryRow ?? (await pathExists(summariesDbPath) ? readConversationSummaryRow(DatabaseSync, summariesDbPath, nativeSessionId) : void 0);
17927
+ upsertConversationSummaryRow(DatabaseSync, summariesDbPath, nativeSessionId, trajectoryId, metadataBlob, 0, existingSummary);
17928
+ } catch {
17929
+ }
17930
+ return true;
17931
+ }
17932
+ async function ensureNativeConversationDb(nativeSessionId, homedir2 = os4.homedir(), hasPriorHistory = false) {
17933
+ const dbPath = nativeConversationDbPath(nativeSessionId, homedir2);
17934
+ let exists;
17935
+ try {
17936
+ exists = await pathExists(dbPath);
17937
+ } catch {
17938
+ return { seeded: false, emptySteps: false };
17939
+ }
17940
+ if (exists) {
17941
+ try {
17942
+ const { DatabaseSync: DatabaseSync2 } = await import("node:sqlite");
17943
+ const db = new DatabaseSync2(dbPath);
17944
+ let trajectoryId = randomUUID2();
17945
+ let metadataBlob = null;
17946
+ let stepCount = 0;
17947
+ let validTrajectory = false;
17948
+ try {
17949
+ const metaRow = db.prepare("SELECT trajectory_id, cascade_id FROM trajectory_meta LIMIT 1").get();
17950
+ if (metaRow?.trajectory_id) {
17951
+ validTrajectory = true;
17952
+ trajectoryId = metaRow.trajectory_id;
17953
+ if (metaRow.cascade_id !== nativeSessionId) {
17954
+ db.prepare("UPDATE trajectory_meta SET cascade_id = ?").run(nativeSessionId);
17955
+ }
17956
+ }
17957
+ try {
17958
+ const blobRow = db.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get();
17959
+ const current = blobRow?.data?.length ? Buffer.from(blobRow.data) : null;
17960
+ const updated = current ? rewriteTrajectoryMetadataCascadeId(current, nativeSessionId) : minimalTrajectoryMetadataBlob(nativeSessionId);
17961
+ metadataBlob = updated ?? current;
17962
+ if (updated && !current?.equals(updated)) {
17963
+ db.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(updated);
17964
+ }
17965
+ } catch {
17966
+ }
17967
+ const countRow = db.prepare("SELECT count(*) as c FROM steps").get();
17968
+ stepCount = countRow?.c ?? 0;
17969
+ } finally {
17970
+ db.close();
17971
+ }
17972
+ if (validTrajectory) {
17973
+ try {
17974
+ const summariesDbPath2 = nativeConversationSummariesDbPath(homedir2);
17975
+ const existingRow = await pathExists(summariesDbPath2) ? readConversationSummaryRow(DatabaseSync2, summariesDbPath2, nativeSessionId) : void 0;
17976
+ if (!existingRow || !existingRow.raw_summary) {
17977
+ upsertConversationSummaryRow(DatabaseSync2, summariesDbPath2, nativeSessionId, trajectoryId, metadataBlob ?? minimalTrajectoryMetadataBlob(nativeSessionId), stepCount, existingRow);
17978
+ }
17979
+ } catch {
17980
+ }
17981
+ return { seeded: false, emptySteps: stepCount === 0 };
17982
+ }
17983
+ } catch {
17984
+ return { seeded: false, emptySteps: false };
17985
+ }
17986
+ return { seeded: false, emptySteps: false };
17390
17987
  }
17391
- };
17392
-
17393
- // dist/fork.js
17394
- function nativeConversationDbPath(nativeSessionId, homedir2 = os3.homedir()) {
17395
- return path6.join(homedir2, ".gemini", "antigravity-cli", "conversations", `${nativeSessionId}.db`);
17396
- }
17397
- function nativeBrainRoot(homedir2 = os3.homedir()) {
17398
- return path6.join(homedir2, ".gemini", "antigravity-cli", "brain");
17399
- }
17400
- function nativeBrainDirPath(nativeSessionId, homedir2 = os3.homedir()) {
17401
- return path6.join(nativeBrainRoot(homedir2), nativeSessionId);
17988
+ if (!UUID_PATTERN.test(nativeSessionId)) {
17989
+ return { seeded: false, emptySteps: false };
17990
+ }
17991
+ let DatabaseSync;
17992
+ try {
17993
+ ({ DatabaseSync } = await import("node:sqlite"));
17994
+ } catch {
17995
+ return { seeded: false, emptySteps: false };
17996
+ }
17997
+ const summariesDbPath = nativeConversationSummariesDbPath(homedir2);
17998
+ let existingSummary;
17999
+ let hasBrainDir;
18000
+ try {
18001
+ existingSummary = await pathExists(summariesDbPath) ? readConversationSummaryRow(DatabaseSync, summariesDbPath, nativeSessionId) : void 0;
18002
+ hasBrainDir = await pathExists(nativeBrainDirPath(nativeSessionId, homedir2));
18003
+ } catch {
18004
+ return { seeded: false, emptySteps: false };
18005
+ }
18006
+ if (!hasPriorHistory && !existingSummary && !hasBrainDir) {
18007
+ return { seeded: false, emptySteps: false };
18008
+ }
18009
+ const seeded = await seedNativeConversationDb(nativeSessionId, homedir2, existingSummary);
18010
+ return { seeded, emptySteps: seeded };
17402
18011
  }
17403
- async function cloneNativeConversationDb(sourceSessionId, derivedSessionId, retainedTurnsCountOrHomedir, homedirOption = os3.homedir()) {
18012
+ async function cloneNativeConversationDb(sourceSessionId, derivedSessionId, retainedTurnsCountOrHomedir, homedirOption = os4.homedir()) {
17404
18013
  let retainedTurnsCount;
17405
18014
  let homedir2 = homedirOption;
17406
18015
  if (typeof retainedTurnsCountOrHomedir === "string") {
@@ -17410,22 +18019,48 @@ async function cloneNativeConversationDb(sourceSessionId, derivedSessionId, reta
17410
18019
  }
17411
18020
  const sourceDb = nativeConversationDbPath(sourceSessionId, homedir2);
17412
18021
  const targetDb = nativeConversationDbPath(derivedSessionId, homedir2);
18022
+ const summariesDbPath = nativeConversationSummariesDbPath(homedir2);
18023
+ let copiedFromDisk = false;
17413
18024
  try {
17414
- await mkdir2(path6.dirname(targetDb), { recursive: true });
18025
+ await mkdir2(path7.dirname(targetDb), { recursive: true });
17415
18026
  await copyFile(sourceDb, targetDb);
18027
+ copiedFromDisk = true;
17416
18028
  } catch {
17417
- return false;
18029
+ copiedFromDisk = false;
17418
18030
  }
17419
18031
  let DatabaseSync;
17420
18032
  try {
17421
18033
  ({ DatabaseSync } = await import("node:sqlite"));
17422
18034
  } catch {
17423
- return false;
18035
+ return copiedFromDisk;
18036
+ }
18037
+ if (!copiedFromDisk) {
18038
+ const sourceSummary = await pathExists(summariesDbPath) ? readConversationSummaryRow(DatabaseSync, summariesDbPath, sourceSessionId) : void 0;
18039
+ const sourceBrainExists = await pathExists(nativeBrainDirPath(sourceSessionId, homedir2));
18040
+ if (!UUID_PATTERN.test(sourceSessionId) && !sourceSummary && !sourceBrainExists) {
18041
+ return false;
18042
+ }
18043
+ return seedNativeConversationDb(derivedSessionId, homedir2, sourceSummary);
17424
18044
  }
18045
+ let trajectoryId = randomUUID2();
18046
+ let metadataBlob = minimalTrajectoryMetadataBlob(derivedSessionId);
18047
+ let remainingStepCount = 0;
17425
18048
  try {
17426
18049
  const db = new DatabaseSync(targetDb);
17427
18050
  try {
17428
18051
  db.prepare("UPDATE trajectory_meta SET cascade_id = ?").run(derivedSessionId);
18052
+ try {
18053
+ const metaRow = db.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get();
18054
+ if (metaRow?.trajectory_id)
18055
+ trajectoryId = metaRow.trajectory_id;
18056
+ } catch {
18057
+ }
18058
+ try {
18059
+ const blobRow = db.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get();
18060
+ metadataBlob = updateTrajectoryMetadataCascadeId(blobRow?.data, derivedSessionId);
18061
+ db.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(metadataBlob);
18062
+ } catch {
18063
+ }
17429
18064
  if (retainedTurnsCount !== void 0) {
17430
18065
  try {
17431
18066
  if (retainedTurnsCount === 0) {
@@ -17456,56 +18091,33 @@ async function cloneNativeConversationDb(sourceSessionId, derivedSessionId, reta
17456
18091
  } catch {
17457
18092
  }
17458
18093
  }
18094
+ try {
18095
+ const countRow = db.prepare("SELECT count(*) as c FROM steps").get();
18096
+ if (countRow)
18097
+ remainingStepCount = countRow.c;
18098
+ } catch {
18099
+ }
17459
18100
  } finally {
17460
18101
  db.close();
17461
18102
  }
17462
18103
  } catch {
18104
+ return true;
17463
18105
  }
17464
- try {
17465
- const summariesDbPath = path6.join(homedir2, ".gemini", "antigravity-cli", "conversation_summaries.db");
17466
- const sumDb = new DatabaseSync(summariesDbPath);
17467
- try {
17468
- const cur = sumDb.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?");
17469
- const row = cur.get(sourceSessionId);
17470
- if (row) {
17471
- let remainingStepCount = 0;
17472
- try {
17473
- const countDb = new DatabaseSync(targetDb);
17474
- try {
17475
- const countRow = countDb.prepare("SELECT count(*) as c FROM steps").get();
17476
- if (countRow)
17477
- remainingStepCount = countRow.c;
17478
- } finally {
17479
- countDb.close();
17480
- }
17481
- } catch {
17482
- }
17483
- const cols = Object.keys(row);
17484
- const newRow = {
17485
- ...row,
17486
- conversation_id: derivedSessionId,
17487
- last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
17488
- ...retainedTurnsCount !== void 0 ? { step_count: remainingStepCount } : {}
17489
- };
17490
- const placeholders = cols.map(() => "?").join(", ");
17491
- const values = cols.map((col) => newRow[col]);
17492
- sumDb.prepare(`INSERT OR REPLACE INTO conversation_summaries (${cols.map((c) => `\`${c}\``).join(", ")}) VALUES (${placeholders})`).run(...values);
17493
- }
17494
- } finally {
17495
- sumDb.close();
17496
- }
17497
- } catch {
18106
+ if (await pathExists(summariesDbPath)) {
18107
+ const sourceRow = readConversationSummaryRow(DatabaseSync, summariesDbPath, sourceSessionId);
18108
+ const effectiveStepCount = retainedTurnsCount !== void 0 ? remainingStepCount : typeof sourceRow?.step_count === "number" ? sourceRow.step_count : remainingStepCount;
18109
+ upsertConversationSummaryRow(DatabaseSync, summariesDbPath, derivedSessionId, trajectoryId, metadataBlob, effectiveStepCount, sourceRow);
17498
18110
  }
17499
18111
  return true;
17500
18112
  }
17501
18113
  var copyNativeConversationDbIfExists = cloneNativeConversationDb;
17502
- async function copyNativeBrainDirIfExists(sourceSessionId, derivedSessionId, homedir2 = os3.homedir()) {
18114
+ async function copyNativeBrainDirIfExists(sourceSessionId, derivedSessionId, homedir2 = os4.homedir()) {
17503
18115
  const sourceBrain = nativeBrainDirPath(sourceSessionId, homedir2);
17504
18116
  const targetBrain = nativeBrainDirPath(derivedSessionId, homedir2);
17505
18117
  try {
17506
18118
  await cp(sourceBrain, targetBrain, {
17507
18119
  recursive: true,
17508
- filter: (source) => path6.basename(source) !== ".system_generated"
18120
+ filter: (source) => path7.basename(source) !== ".system_generated"
17509
18121
  });
17510
18122
  return true;
17511
18123
  } catch {
@@ -17575,6 +18187,10 @@ async function forkAntigravitySession(options) {
17575
18187
  }
17576
18188
  };
17577
18189
  }
18190
+ const homedir2 = antigravityHome(sessionEnvironment);
18191
+ const boundaryError = await nativeTurnBoundaryError(nativeConversationDbPath(sourceRef.nativeSessionId, homedir2), sourceTurns.length);
18192
+ if (boundaryError)
18193
+ return { ok: false, error: boundaryError };
17578
18194
  const retainedTurns = sourceTurns.slice(0, boundaryIndex + 1);
17579
18195
  const derivedNativeSessionId = randomUUID2();
17580
18196
  const copiedTurns = retainedTurns.map((turn) => ({
@@ -17601,8 +18217,8 @@ async function forkAntigravitySession(options) {
17601
18217
  ...thinkingOptionId ? { thinkingOptionId } : {}
17602
18218
  });
17603
18219
  await Promise.all([
17604
- copyNativeConversationDbIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, retainedTurns.length),
17605
- copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedNativeSessionId)
18220
+ copyNativeConversationDbIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, retainedTurns.length, homedir2),
18221
+ copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, homedir2)
17606
18222
  ]);
17607
18223
  const derivedNativeRef = {
17608
18224
  harnessId,
@@ -17795,6 +18411,10 @@ async function rollbackAntigravityLastTurn(options) {
17795
18411
  }
17796
18412
  };
17797
18413
  }
18414
+ const homedir2 = antigravityHome(sessionEnvironment);
18415
+ const boundaryError = await nativeTurnBoundaryError(nativeConversationDbPath(sourceRef.nativeSessionId, homedir2), sourceTurns.length);
18416
+ if (boundaryError)
18417
+ return { ok: false, error: boundaryError };
17798
18418
  const truncatedTurns = sourceTurns.slice(0, -1);
17799
18419
  const derivedNativeSessionId = randomUUID3();
17800
18420
  const mappedTurns = truncatedTurns.map((turn) => ({
@@ -17821,8 +18441,8 @@ async function rollbackAntigravityLastTurn(options) {
17821
18441
  ...thinkingOptionId ? { thinkingOptionId } : {}
17822
18442
  });
17823
18443
  await Promise.all([
17824
- copyNativeConversationDbIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, mappedTurns.length),
17825
- copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedNativeSessionId)
18444
+ copyNativeConversationDbIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, mappedTurns.length, homedir2),
18445
+ copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, homedir2)
17826
18446
  ]);
17827
18447
  const derivedNativeRef = {
17828
18448
  harnessId,
@@ -17969,7 +18589,7 @@ function parseAndFormatAntigravityCommand(command) {
17969
18589
  import https from "node:https";
17970
18590
 
17971
18591
  // dist/tool-projection.js
17972
- import path7 from "node:path";
18592
+ import path8 from "node:path";
17973
18593
  function isRecord(value) {
17974
18594
  return typeof value === "object" && value !== null && !Array.isArray(value);
17975
18595
  }
@@ -17990,10 +18610,10 @@ function displayPath(nativePath, cwd) {
17990
18610
  if (typeof nativePath !== "string" || nativePath.trim().length === 0 || nativePath.includes("\0") || nativePath.includes("\n") || nativePath.includes("\r")) {
17991
18611
  return null;
17992
18612
  }
17993
- const resolvedCwd = path7.resolve(cwd);
17994
- const resolvedPath = path7.isAbsolute(nativePath) ? path7.resolve(nativePath) : path7.resolve(cwd, nativePath);
17995
- const relative = path7.relative(resolvedCwd, resolvedPath);
17996
- const inside = !path7.isAbsolute(relative) && relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path7.sep}`);
18613
+ const resolvedCwd = path8.resolve(cwd);
18614
+ const resolvedPath = path8.isAbsolute(nativePath) ? path8.resolve(nativePath) : path8.resolve(cwd, nativePath);
18615
+ const relative = path8.relative(resolvedCwd, resolvedPath);
18616
+ const inside = !path8.isAbsolute(relative) && relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`);
17997
18617
  const selected = inside ? relative : resolvedPath;
17998
18618
  const normalized = selected.replaceAll("\\", "/");
17999
18619
  if (normalized.length === 0 || normalized === ".")
@@ -18124,7 +18744,7 @@ function synthesizeAntigravityCommand(toolName, params, cwd) {
18124
18744
  ]);
18125
18745
  let resolvedCwd;
18126
18746
  if (workingDir && workingDir.trim().length > 0) {
18127
- resolvedCwd = cwd && !path7.isAbsolute(workingDir) ? path7.resolve(cwd, workingDir) : workingDir;
18747
+ resolvedCwd = cwd && !path8.isAbsolute(workingDir) ? path8.resolve(cwd, workingDir) : workingDir;
18128
18748
  } else if (cwd) {
18129
18749
  resolvedCwd = cwd;
18130
18750
  }
@@ -18532,8 +19152,8 @@ async function fetchAntigravityQuota(run, now = /* @__PURE__ */ new Date()) {
18532
19152
  import { randomBytes, randomUUID as randomUUID4, timingSafeEqual } from "node:crypto";
18533
19153
  import { mkdir as mkdir3, mkdtemp as mkdtemp2, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
18534
19154
  import { createServer } from "node:http";
18535
- import os4 from "node:os";
18536
- import path8 from "node:path";
19155
+ import os5 from "node:os";
19156
+ import path9 from "node:path";
18537
19157
 
18538
19158
  // dist/question-hook-client.js
18539
19159
  var ANTIGRAVITY_QUESTION_HOOK_CLIENT = String.raw`
@@ -18658,7 +19278,7 @@ var AntigravityQuestionBridge = class _AntigravityQuestionBridge {
18658
19278
  this.#server.on("request", (request, response) => this.#receive(request, response));
18659
19279
  }
18660
19280
  static async create(options) {
18661
- const directory = options.directory ?? await mkdtemp2(path8.join(os4.tmpdir(), "codexhost-agy-question-"));
19281
+ const directory = options.directory ?? await mkdtemp2(path9.join(os5.tmpdir(), "codexhost-agy-question-"));
18662
19282
  const bridge = new _AntigravityQuestionBridge(directory, options);
18663
19283
  try {
18664
19284
  await new Promise((resolve, reject) => {
@@ -18673,14 +19293,14 @@ var AntigravityQuestionBridge = class _AntigravityQuestionBridge {
18673
19293
  if (!address || typeof address === "string")
18674
19294
  throw new Error("Question bridge did not bind");
18675
19295
  bridge.environment.CODEXHOST_AGY_QUESTION_URL = `http://127.0.0.1:${address.port}/question`;
18676
- const client = path8.join(directory, "question-hook.cjs");
18677
- await mkdir3(path8.join(directory, ".agents"), { recursive: true, mode: 448 });
19296
+ const client = path9.join(directory, "question-hook.cjs");
19297
+ await mkdir3(path9.join(directory, ".agents"), { recursive: true, mode: 448 });
18678
19298
  await writeFile3(client, ANTIGRAVITY_QUESTION_HOOK_CLIENT, "utf8");
18679
19299
  const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
18680
19300
  bridge.environment.CODEXHOST_AGY_QUESTION_NODE = `"${process.execPath.replaceAll("\\", "/")}"`;
18681
19301
  bridge.environment.CODEXHOST_AGY_QUESTION_CLIENT = `"${client.replaceAll("\\", "/")}"`;
18682
19302
  const command = process.platform === "win32" ? "%CODEXHOST_AGY_QUESTION_NODE% %CODEXHOST_AGY_QUESTION_CLIENT%" : `${quote(process.execPath)} ${quote(client)}`;
18683
- await writeFile3(path8.join(directory, ".agents", "hooks.json"), JSON.stringify({
19303
+ await writeFile3(path9.join(directory, ".agents", "hooks.json"), JSON.stringify({
18684
19304
  "codexhost-question-bridge": {
18685
19305
  PreToolUse: [
18686
19306
  {
@@ -18917,7 +19537,7 @@ import { randomUUID as randomUUID5 } from "node:crypto";
18917
19537
  // dist/subagent-transcript.js
18918
19538
  import { open, realpath } from "node:fs/promises";
18919
19539
  import https2 from "node:https";
18920
- import path9 from "node:path";
19540
+ import path10 from "node:path";
18921
19541
  var nativeSubagentIdSchema = external_exports.uuid();
18922
19542
  var MAX_TRANSCRIPT_BYTES = 8 * 1024 * 1024;
18923
19543
  var transcriptStepSchema = external_exports.object({
@@ -19085,10 +19705,10 @@ async function readSubagentTranscript(input) {
19085
19705
  };
19086
19706
  }
19087
19707
  try {
19088
- const file2 = path9.join(nativeBrainDirPath(input.childId, input.home), ".system_generated", "logs", "transcript.jsonl");
19089
- const brainRoot = await realpath(path9.dirname(nativeBrainDirPath(input.childId, input.home)));
19708
+ const file2 = path10.join(nativeBrainDirPath(input.childId, input.home), ".system_generated", "logs", "transcript.jsonl");
19709
+ const brainRoot = await realpath(path10.dirname(nativeBrainDirPath(input.childId, input.home)));
19090
19710
  const resolved = await realpath(file2);
19091
- const expected = path9.join(brainRoot, input.childId, ".system_generated", "logs", "transcript.jsonl");
19711
+ const expected = path10.join(brainRoot, input.childId, ".system_generated", "logs", "transcript.jsonl");
19092
19712
  const normalize = (value) => process.platform === "win32" ? value.toLowerCase() : value;
19093
19713
  if (normalize(resolved) !== normalize(expected))
19094
19714
  throw new Error("Subagent log redirects outside its native location");
@@ -19399,187 +20019,6 @@ var AntigravitySubagents = class {
19399
20019
  }
19400
20020
  };
19401
20021
 
19402
- // dist/usage-statistics.js
19403
- import { lstat, opendir } from "node:fs/promises";
19404
- import os5 from "node:os";
19405
- import path10 from "node:path";
19406
-
19407
- // ../../harness-adapter/dist/usage-statistics.js
19408
- import { createReadStream } from "node:fs";
19409
- import { createInterface } from "node:readline";
19410
- var HarnessUsageSourceChangedError = class extends Error {
19411
- code = "HARNESS_USAGE_SOURCE_CHANGED";
19412
- /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
19413
- static is(error51) {
19414
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
19415
- }
19416
- };
19417
- var MAX_SESSION_ID_LENGTH = 512;
19418
- var MAX_CWD_LENGTH = 4096;
19419
- var MAX_SESSION_TITLE_LENGTH = 200;
19420
- function usageSessionTitle(value) {
19421
- if (typeof value !== "string")
19422
- return void 0;
19423
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
19424
- if (!normalized)
19425
- return void 0;
19426
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
19427
- return normalized;
19428
- let title = "";
19429
- for (const character of normalized) {
19430
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
19431
- break;
19432
- title += character;
19433
- }
19434
- return `${title.trimEnd()}…`;
19435
- }
19436
- function sessionIdOk(value) {
19437
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
19438
- }
19439
- function cwdOk(value) {
19440
- 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("\\\\"));
19441
- }
19442
- function withUsageSession(entry, session) {
19443
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
19444
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
19445
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
19446
- if (sessionId === void 0 && cwd === void 0)
19447
- return entry;
19448
- return {
19449
- ...entry,
19450
- ...sessionId !== void 0 ? { sessionId } : {},
19451
- ...cwd !== void 0 ? { cwd } : {},
19452
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
19453
- };
19454
- }
19455
- async function* jsonlRecords(file2, marker, signal) {
19456
- const lines = createInterface({
19457
- input: createReadStream(file2, { encoding: "utf8", signal }),
19458
- crlfDelay: Infinity
19459
- });
19460
- for await (const line of lines) {
19461
- if (!line.includes(marker))
19462
- continue;
19463
- let value;
19464
- try {
19465
- value = JSON.parse(line);
19466
- } catch {
19467
- continue;
19468
- }
19469
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
19470
- yield value;
19471
- }
19472
- }
19473
- }
19474
- function nativeTimeMs(value) {
19475
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
19476
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
19477
- }
19478
-
19479
- // dist/usage-statistics.js
19480
- function count2(value) {
19481
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
19482
- }
19483
- function antigravityHome(environment) {
19484
- return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os5.homedir();
19485
- }
19486
- function transcriptPath(brainRoot, conversationId) {
19487
- return path10.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
19488
- }
19489
- function isMissing(error51) {
19490
- const code = error51?.code;
19491
- return code === "ENOENT" || code === "ENOTDIR";
19492
- }
19493
- async function lstatIfPresent(target) {
19494
- try {
19495
- return await lstat(target);
19496
- } catch (error51) {
19497
- if (isMissing(error51))
19498
- return null;
19499
- throw error51;
19500
- }
19501
- }
19502
- async function transcriptFingerprint(file2) {
19503
- const logs = path10.dirname(file2);
19504
- for (const directory of [path10.dirname(logs), logs]) {
19505
- if (!(await lstatIfPresent(directory))?.isDirectory())
19506
- return null;
19507
- }
19508
- const info = await lstatIfPresent(file2);
19509
- return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
19510
- }
19511
- async function listTranscripts(brainRoot, signal) {
19512
- signal.throwIfAborted();
19513
- const conversations = await opendir(brainRoot).catch((error51) => {
19514
- if (error51.code === "ENOENT")
19515
- return null;
19516
- throw error51;
19517
- });
19518
- if (!conversations)
19519
- return [];
19520
- const sources = [];
19521
- for await (const entry of conversations) {
19522
- signal.throwIfAborted();
19523
- if (!entry.isDirectory())
19524
- continue;
19525
- const file2 = transcriptPath(brainRoot, entry.name);
19526
- const fingerprint = await transcriptFingerprint(file2);
19527
- if (fingerprint)
19528
- sources.push({ id: file2, fingerprint });
19529
- }
19530
- return sources;
19531
- }
19532
- async function readAntigravityUsage(file2, signal) {
19533
- const sessionId = path10.basename(path10.resolve(file2, "..", "..", ".."));
19534
- const requests = /* @__PURE__ */ new Map();
19535
- for await (const record3 of jsonlRecords(file2, '"input_tokens"', signal)) {
19536
- if (record3.type !== "PLANNER_RESPONSE")
19537
- continue;
19538
- const step = count2(record3.step_index);
19539
- const input = count2(record3.input_tokens);
19540
- const output = count2(record3.output_tokens);
19541
- const cached2 = count2(record3.cache_read_tokens);
19542
- const at = nativeTimeMs(record3.created_at);
19543
- if (step === null || input === null || output === null || at === null)
19544
- continue;
19545
- requests.set(step, withUsageSession({
19546
- id: `${String(record3.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
19547
- occurredAtMs: at,
19548
- inputTokens: input + (cached2 ?? 0),
19549
- ...cached2 !== null ? { cachedInputTokens: cached2 } : {},
19550
- outputTokens: output
19551
- }, { sessionId }));
19552
- }
19553
- return [...requests.values()];
19554
- }
19555
- function createAntigravityUsageStatistics(environment) {
19556
- const brainRoot = nativeBrainRoot(antigravityHome(environment));
19557
- let listed = /* @__PURE__ */ new Map();
19558
- return Object.freeze({
19559
- async listSources(signal) {
19560
- const sources = await listTranscripts(brainRoot, signal);
19561
- listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
19562
- return sources;
19563
- },
19564
- async readSource(id, signal) {
19565
- const expected = listed.get(id);
19566
- let entries;
19567
- try {
19568
- entries = await readAntigravityUsage(id, signal);
19569
- } catch (error51) {
19570
- if (expected !== void 0 && isMissing(error51)) {
19571
- throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
19572
- }
19573
- throw error51;
19574
- }
19575
- if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
19576
- throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
19577
- }
19578
- return entries;
19579
- }
19580
- });
19581
- }
19582
-
19583
20022
  // dist/antigravity-adapter.js
19584
20023
  function unstreamedReplyTail(streamed, reply) {
19585
20024
  const shown = streamed.replace(/\s+/gu, "");
@@ -19685,6 +20124,34 @@ var ANTIGRAVITY_WORKSPACE_FILE_INSTRUCTION = "[System Instruction: When creating
19685
20124
  function antigravityWorkingDirectoryInstruction(cwd) {
19686
20125
  return `[System Instruction: The project working directory is ${JSON.stringify(cwd)}. Run terminal commands and resolve relative file paths in this directory unless the task requires another one.]
19687
20126
 
20127
+ `;
20128
+ }
20129
+ function formatRecoveredHistoryContext(turns) {
20130
+ if (turns.length === 0)
20131
+ return "";
20132
+ const formattedTurns = [];
20133
+ for (const [index, turn] of turns.entries()) {
20134
+ const userText = turn.input.map((part) => part.text.trim()).filter(Boolean).join("\n\n");
20135
+ const assistantText = turn.items.flatMap(({ item }) => item.type === "agentMessage" && item.text.trim() ? [item.text.trim()] : []).join("\n\n");
20136
+ if (!userText && !assistantText)
20137
+ continue;
20138
+ const sections = [`Turn ${index + 1}:`];
20139
+ if (userText)
20140
+ sections.push(`User:
20141
+ ${userText}`);
20142
+ if (assistantText)
20143
+ sections.push(`Assistant:
20144
+ ${assistantText}`);
20145
+ formattedTurns.push(sections.join("\n"));
20146
+ }
20147
+ if (formattedTurns.length === 0)
20148
+ return "";
20149
+ return `[System Instruction: The native Antigravity trajectory database for this Conversation was reconstructed from CodexHost history. Use the prior Conversation history below as context for the current user message.]
20150
+
20151
+ <prior_conversation_history>
20152
+ ${formattedTurns.join("\n\n---\n\n")}
20153
+ </prior_conversation_history>
20154
+
19688
20155
  `;
19689
20156
  }
19690
20157
  function formatAntigravityTurnPrompt(text, cwd) {
@@ -19837,6 +20304,25 @@ function normalizedProcessError(detail, fallback, exposeDetail = false) {
19837
20304
  ...diagnostic ? { stderrTail: diagnostic.slice(-4e3) } : {}
19838
20305
  };
19839
20306
  }
20307
+ async function antigravityResumeMismatchError(expectedConversationId, receivedConversationId, homedir2) {
20308
+ const dbPath = nativeConversationDbPath(expectedConversationId, homedir2);
20309
+ const missing = await access2(dbPath).then(() => false, (error51) => error51?.code === "ENOENT");
20310
+ const diagnostic = `expected=${expectedConversationId} received=${receivedConversationId} store=${dbPath} storeEntry=${missing ? "missing" : "present"}`;
20311
+ if (missing) {
20312
+ return {
20313
+ code: "sessionNotFound",
20314
+ message: `Antigravity Conversation ${expectedConversationId} no longer exists (${dbPath} is missing), so agy started a new Conversation ${receivedConversationId} instead of resuming it. Its native history was removed outside CodexHost; start a new Thread to continue.`,
20315
+ retryable: false,
20316
+ diagnostic
20317
+ };
20318
+ }
20319
+ return {
20320
+ code: "sessionNotFound",
20321
+ message: `Antigravity resumed a different Conversation: expected ${expectedConversationId}, agy started ${receivedConversationId}`,
20322
+ retryable: false,
20323
+ diagnostic
20324
+ };
20325
+ }
19840
20326
  async function runBuffered(executable, arguments_, cwd, environment, timeoutMs, signal) {
19841
20327
  const invocation = commandInvocation(executable, arguments_, environment);
19842
20328
  return await new Promise((resolve, reject) => {
@@ -19988,6 +20474,7 @@ var AntigravitySession = class {
19988
20474
  };
19989
20475
  }
19990
20476
  let questions;
20477
+ let includeRecoveredHistory = false;
19991
20478
  const hookDirectory = antigravityHookDirectory(this.#environment);
19992
20479
  const previousTurn = hookDirectory ? this.#questionCleanup : Promise.resolve();
19993
20480
  this.#preparingQuestions = previousTurn.then(() => AntigravityQuestionBridge.create({
@@ -20017,12 +20504,18 @@ var AntigravitySession = class {
20017
20504
  }));
20018
20505
  try {
20019
20506
  questions = await this.#preparingQuestions;
20507
+ if (!this.#closed && this.#nativeRef) {
20508
+ const priorTurns = this.#history.snapshot();
20509
+ const ensured = await ensureNativeConversationDb(this.#nativeRef.nativeSessionId, antigravityHome({ ...this.#environment, ...questions.environment }), priorTurns.length > 0);
20510
+ includeRecoveredHistory = ensured.emptySteps && priorTurns.length > 0;
20511
+ }
20020
20512
  } catch (error51) {
20513
+ await questions?.dispose();
20021
20514
  return {
20022
20515
  ok: false,
20023
20516
  error: {
20024
20517
  code: "nativeFailure",
20025
- message: `Question bridge setup failed: ${errorMessage(error51)}`,
20518
+ message: `Antigravity Turn setup failed: ${errorMessage(error51)}`,
20026
20519
  retryable: true
20027
20520
  }
20028
20521
  };
@@ -20043,8 +20536,9 @@ var AntigravitySession = class {
20043
20536
  "--print-timeout",
20044
20537
  this.#printTimeout
20045
20538
  ];
20046
- if (this.#nativeRef)
20539
+ if (this.#nativeRef) {
20047
20540
  arguments_.unshift("--conversation", this.#nativeRef.nativeSessionId);
20541
+ }
20048
20542
  arguments_.push(...antigravityModelArguments(this.#model, this.#thinkingOptionId));
20049
20543
  arguments_.push("--dangerously-skip-permissions");
20050
20544
  arguments_.push("--add-dir", this.#cwd);
@@ -20157,7 +20651,8 @@ ${line}`).slice(-8e3);
20157
20651
  });
20158
20652
  });
20159
20653
  try {
20160
- const turnPrompt = formatAntigravityTurnPrompt(text, this.#cwd);
20654
+ const promptBody = includeRecoveredHistory && !text.startsWith("/") ? `${formatRecoveredHistoryContext(this.#history.snapshot())}${text}` : text;
20655
+ const turnPrompt = formatAntigravityTurnPrompt(promptBody, this.#cwd);
20161
20656
  if (child.stdin.writable) {
20162
20657
  child.stdin.write(`${JSON.stringify({ event: "user", message: { content: turnPrompt } })}
20163
20658
  `, () => void 0);
@@ -20216,15 +20711,9 @@ ${line}`).slice(-8e3);
20216
20711
  if (event.event === "init") {
20217
20712
  active.nativePermissionMode = event.init?.permission_mode ?? null;
20218
20713
  if (this.#nativeRef && this.#nativeRef.nativeSessionId !== event.conversation_id) {
20219
- this.#completeTurn(active, {
20220
- status: "failed",
20221
- error: {
20222
- code: "sessionNotFound",
20223
- message: "Antigravity resumed a different Conversation",
20224
- retryable: false
20225
- }
20226
- });
20227
20714
  active.process.kill();
20715
+ const error51 = await antigravityResumeMismatchError(this.#nativeRef.nativeSessionId, event.conversation_id, antigravityHome(this.#environment));
20716
+ this.#completeTurn(active, { status: "failed", error: error51 });
20228
20717
  return;
20229
20718
  }
20230
20719
  this.#nativeRef = nativeSessionRefSchema.parse({
@@ -20515,14 +21004,14 @@ ${line}`).slice(-8e3);
20515
21004
  const claimed = active.fileChanges.get(step.step_index);
20516
21005
  if (claimed)
20517
21006
  return claimed;
20518
- const target = toolTargetFile(toolName, step.tool_info?.parameters);
20519
- if (!target)
21007
+ const target2 = toolTargetFile(toolName, step.tool_info?.parameters);
21008
+ if (!target2)
20520
21009
  return null;
20521
21010
  const port = await this.#languageServerPort(active);
20522
21011
  if (port === null)
20523
21012
  return null;
20524
21013
  const actions = await requestAntigravityTrajectorySteps(port, step.conversation_id, TRAJECTORY_TIMEOUT_MS);
20525
- const index = actions.findIndex((action2, at) => at >= active.codeActionCursor && sameFile(action2.absolutePath, target));
21014
+ const index = actions.findIndex((action2, at) => at >= active.codeActionCursor && sameFile(action2.absolutePath, target2));
20526
21015
  const action = index === -1 ? void 0 : actions[index];
20527
21016
  if (!action)
20528
21017
  return null;