@codexhost/cli-linux-arm64 0.18.0-beta.4 → 0.18.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 (48) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +98 -55
  4. package/app/console-web.js +276 -188
  5. package/app/desktop-controller.mjs +283 -113
  6. package/app/host-runtime.mjs +2129 -1529
  7. package/app/plugins/antigravity/plugin.mjs +787 -303
  8. package/app/plugins/claude-code/plugin.mjs +85 -45
  9. package/app/plugins/codebuddy/plugin.mjs +99 -59
  10. package/app/plugins/codex-usage/plugin.mjs +85 -45
  11. package/app/plugins/copilot/plugin.mjs +90 -50
  12. package/app/plugins/cursor-cli/plugin.mjs +113 -73
  13. package/app/plugins/deepseek-harness/plugin.mjs +116 -76
  14. package/app/plugins/devin/plugin.mjs +90 -50
  15. package/app/plugins/grok/plugin.mjs +96 -56
  16. package/app/plugins/hermes/plugin.mjs +77 -37
  17. package/app/plugins/kimi-code/plugin.mjs +94 -54
  18. package/app/plugins/kiro-cli/plugin.mjs +90 -50
  19. package/app/plugins/omp/plugin.mjs +81 -41
  20. package/app/plugins/opencode/plugin.mjs +78 -38
  21. package/app/plugins/pi/plugin.mjs +94 -54
  22. package/app/plugins/qoder/plugin.mjs +106 -66
  23. package/app/plugins/qoder-cn/plugin.mjs +106 -66
  24. package/app/plugins/qwen-code/plugin.mjs +101 -61
  25. package/app/plugins/workbuddy/plugin.mjs +99 -59
  26. package/app/plugins/zcode/plugin.mjs +82 -42
  27. package/app/renderer-extension.js +435 -361
  28. package/app/web/assets/{index-D1dOzBMI.js → index-C0aXz2jD.js} +63 -63
  29. package/app/web/codex-agent.png +0 -0
  30. package/app/web/codexhost-settings.js +229 -175
  31. package/app/web/index.html +1 -1
  32. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  33. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +61 -61
  34. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +8 -8
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +2 -2
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +12 -12
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-permission-presets/client.js +1 -1
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +3 -3
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +8 -8
  43. package/app/web/sw.js +41 -6
  44. package/app/web-modules/server.mjs +2079 -1201
  45. package/bin/codexhost +0 -0
  46. package/libexec/codexhost-shim +0 -0
  47. package/libexec/codexhost-updater +0 -0
  48. package/package.json +1 -1
@@ -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({
@@ -16815,6 +16815,44 @@ var remoteSshSetupParamsSchema = external_exports.object({
16815
16815
  }).strict();
16816
16816
  var remoteSshSetupResultSchema = external_exports.object({ state: external_exports.enum(["installed", "not-installed"]) }).strict();
16817
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
+
16818
16856
  // ../../shared-contracts/dist/remote-connections.js
16819
16857
  var hostId = external_exports.string().min(1).max(1024);
16820
16858
  var codexSshConnectionSchema = external_exports.object({
@@ -16835,7 +16873,9 @@ var codexSshDraftSchema = external_exports.strictObject({
16835
16873
  identity: external_exports.string().max(4096).nullable()
16836
16874
  });
16837
16875
  var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
16876
+ external_exports.strictObject({ action: external_exports.literal("session"), operation: remoteSessionOperationSchema }),
16838
16877
  external_exports.strictObject({ action: external_exports.literal("list") }),
16878
+ external_exports.strictObject({ action: external_exports.literal("catalog") }),
16839
16879
  external_exports.strictObject({
16840
16880
  action: external_exports.literal("read-thread"),
16841
16881
  hostId: hostId.refine((id) => id !== "local"),
@@ -17090,9 +17130,9 @@ function resolveAntigravityExecutable(input = {}) {
17090
17130
 
17091
17131
  // dist/fork.js
17092
17132
  import { randomUUID as randomUUID2 } from "node:crypto";
17093
- import { copyFile, cp, mkdir as mkdir2 } from "node:fs/promises";
17094
- import os3 from "node:os";
17095
- 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";
17096
17136
 
17097
17137
  // dist/history.js
17098
17138
  import { randomUUID } from "node:crypto";
@@ -17391,21 +17431,585 @@ var AntigravityHistory = class _AntigravityHistory {
17391
17431
  } finally {
17392
17432
  await rm2(temporary, { force: true }).catch(() => void 0);
17393
17433
  }
17394
- });
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 };
17395
17987
  }
17396
- };
17397
-
17398
- // dist/fork.js
17399
- function nativeConversationDbPath(nativeSessionId, homedir2 = os3.homedir()) {
17400
- return path6.join(homedir2, ".gemini", "antigravity-cli", "conversations", `${nativeSessionId}.db`);
17401
- }
17402
- function nativeBrainRoot(homedir2 = os3.homedir()) {
17403
- return path6.join(homedir2, ".gemini", "antigravity-cli", "brain");
17404
- }
17405
- function nativeBrainDirPath(nativeSessionId, homedir2 = os3.homedir()) {
17406
- 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 };
17407
18011
  }
17408
- async function cloneNativeConversationDb(sourceSessionId, derivedSessionId, retainedTurnsCountOrHomedir, homedirOption = os3.homedir()) {
18012
+ async function cloneNativeConversationDb(sourceSessionId, derivedSessionId, retainedTurnsCountOrHomedir, homedirOption = os4.homedir()) {
17409
18013
  let retainedTurnsCount;
17410
18014
  let homedir2 = homedirOption;
17411
18015
  if (typeof retainedTurnsCountOrHomedir === "string") {
@@ -17415,22 +18019,48 @@ async function cloneNativeConversationDb(sourceSessionId, derivedSessionId, reta
17415
18019
  }
17416
18020
  const sourceDb = nativeConversationDbPath(sourceSessionId, homedir2);
17417
18021
  const targetDb = nativeConversationDbPath(derivedSessionId, homedir2);
18022
+ const summariesDbPath = nativeConversationSummariesDbPath(homedir2);
18023
+ let copiedFromDisk = false;
17418
18024
  try {
17419
- await mkdir2(path6.dirname(targetDb), { recursive: true });
18025
+ await mkdir2(path7.dirname(targetDb), { recursive: true });
17420
18026
  await copyFile(sourceDb, targetDb);
18027
+ copiedFromDisk = true;
17421
18028
  } catch {
17422
- return false;
18029
+ copiedFromDisk = false;
17423
18030
  }
17424
18031
  let DatabaseSync;
17425
18032
  try {
17426
18033
  ({ DatabaseSync } = await import("node:sqlite"));
17427
18034
  } catch {
17428
- 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);
17429
18044
  }
18045
+ let trajectoryId = randomUUID2();
18046
+ let metadataBlob = minimalTrajectoryMetadataBlob(derivedSessionId);
18047
+ let remainingStepCount = 0;
17430
18048
  try {
17431
18049
  const db = new DatabaseSync(targetDb);
17432
18050
  try {
17433
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
+ }
17434
18064
  if (retainedTurnsCount !== void 0) {
17435
18065
  try {
17436
18066
  if (retainedTurnsCount === 0) {
@@ -17461,56 +18091,33 @@ async function cloneNativeConversationDb(sourceSessionId, derivedSessionId, reta
17461
18091
  } catch {
17462
18092
  }
17463
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
+ }
17464
18100
  } finally {
17465
18101
  db.close();
17466
18102
  }
17467
18103
  } catch {
18104
+ return true;
17468
18105
  }
17469
- try {
17470
- const summariesDbPath = path6.join(homedir2, ".gemini", "antigravity-cli", "conversation_summaries.db");
17471
- const sumDb = new DatabaseSync(summariesDbPath);
17472
- try {
17473
- const cur = sumDb.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?");
17474
- const row = cur.get(sourceSessionId);
17475
- if (row) {
17476
- let remainingStepCount = 0;
17477
- try {
17478
- const countDb = new DatabaseSync(targetDb);
17479
- try {
17480
- const countRow = countDb.prepare("SELECT count(*) as c FROM steps").get();
17481
- if (countRow)
17482
- remainingStepCount = countRow.c;
17483
- } finally {
17484
- countDb.close();
17485
- }
17486
- } catch {
17487
- }
17488
- const cols = Object.keys(row);
17489
- const newRow = {
17490
- ...row,
17491
- conversation_id: derivedSessionId,
17492
- last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
17493
- ...retainedTurnsCount !== void 0 ? { step_count: remainingStepCount } : {}
17494
- };
17495
- const placeholders = cols.map(() => "?").join(", ");
17496
- const values = cols.map((col) => newRow[col]);
17497
- sumDb.prepare(`INSERT OR REPLACE INTO conversation_summaries (${cols.map((c) => `\`${c}\``).join(", ")}) VALUES (${placeholders})`).run(...values);
17498
- }
17499
- } finally {
17500
- sumDb.close();
17501
- }
17502
- } 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);
17503
18110
  }
17504
18111
  return true;
17505
18112
  }
17506
18113
  var copyNativeConversationDbIfExists = cloneNativeConversationDb;
17507
- async function copyNativeBrainDirIfExists(sourceSessionId, derivedSessionId, homedir2 = os3.homedir()) {
18114
+ async function copyNativeBrainDirIfExists(sourceSessionId, derivedSessionId, homedir2 = os4.homedir()) {
17508
18115
  const sourceBrain = nativeBrainDirPath(sourceSessionId, homedir2);
17509
18116
  const targetBrain = nativeBrainDirPath(derivedSessionId, homedir2);
17510
18117
  try {
17511
18118
  await cp(sourceBrain, targetBrain, {
17512
18119
  recursive: true,
17513
- filter: (source) => path6.basename(source) !== ".system_generated"
18120
+ filter: (source) => path7.basename(source) !== ".system_generated"
17514
18121
  });
17515
18122
  return true;
17516
18123
  } catch {
@@ -17580,6 +18187,10 @@ async function forkAntigravitySession(options) {
17580
18187
  }
17581
18188
  };
17582
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 };
17583
18194
  const retainedTurns = sourceTurns.slice(0, boundaryIndex + 1);
17584
18195
  const derivedNativeSessionId = randomUUID2();
17585
18196
  const copiedTurns = retainedTurns.map((turn) => ({
@@ -17606,8 +18217,8 @@ async function forkAntigravitySession(options) {
17606
18217
  ...thinkingOptionId ? { thinkingOptionId } : {}
17607
18218
  });
17608
18219
  await Promise.all([
17609
- copyNativeConversationDbIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, retainedTurns.length),
17610
- copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedNativeSessionId)
18220
+ copyNativeConversationDbIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, retainedTurns.length, homedir2),
18221
+ copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, homedir2)
17611
18222
  ]);
17612
18223
  const derivedNativeRef = {
17613
18224
  harnessId,
@@ -17800,6 +18411,10 @@ async function rollbackAntigravityLastTurn(options) {
17800
18411
  }
17801
18412
  };
17802
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 };
17803
18418
  const truncatedTurns = sourceTurns.slice(0, -1);
17804
18419
  const derivedNativeSessionId = randomUUID3();
17805
18420
  const mappedTurns = truncatedTurns.map((turn) => ({
@@ -17826,8 +18441,8 @@ async function rollbackAntigravityLastTurn(options) {
17826
18441
  ...thinkingOptionId ? { thinkingOptionId } : {}
17827
18442
  });
17828
18443
  await Promise.all([
17829
- copyNativeConversationDbIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, mappedTurns.length),
17830
- copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedNativeSessionId)
18444
+ copyNativeConversationDbIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, mappedTurns.length, homedir2),
18445
+ copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedNativeSessionId, homedir2)
17831
18446
  ]);
17832
18447
  const derivedNativeRef = {
17833
18448
  harnessId,
@@ -17974,7 +18589,7 @@ function parseAndFormatAntigravityCommand(command) {
17974
18589
  import https from "node:https";
17975
18590
 
17976
18591
  // dist/tool-projection.js
17977
- import path7 from "node:path";
18592
+ import path8 from "node:path";
17978
18593
  function isRecord(value) {
17979
18594
  return typeof value === "object" && value !== null && !Array.isArray(value);
17980
18595
  }
@@ -17995,10 +18610,10 @@ function displayPath(nativePath, cwd) {
17995
18610
  if (typeof nativePath !== "string" || nativePath.trim().length === 0 || nativePath.includes("\0") || nativePath.includes("\n") || nativePath.includes("\r")) {
17996
18611
  return null;
17997
18612
  }
17998
- const resolvedCwd = path7.resolve(cwd);
17999
- const resolvedPath = path7.isAbsolute(nativePath) ? path7.resolve(nativePath) : path7.resolve(cwd, nativePath);
18000
- const relative = path7.relative(resolvedCwd, resolvedPath);
18001
- 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}`);
18002
18617
  const selected = inside ? relative : resolvedPath;
18003
18618
  const normalized = selected.replaceAll("\\", "/");
18004
18619
  if (normalized.length === 0 || normalized === ".")
@@ -18129,7 +18744,7 @@ function synthesizeAntigravityCommand(toolName, params, cwd) {
18129
18744
  ]);
18130
18745
  let resolvedCwd;
18131
18746
  if (workingDir && workingDir.trim().length > 0) {
18132
- resolvedCwd = cwd && !path7.isAbsolute(workingDir) ? path7.resolve(cwd, workingDir) : workingDir;
18747
+ resolvedCwd = cwd && !path8.isAbsolute(workingDir) ? path8.resolve(cwd, workingDir) : workingDir;
18133
18748
  } else if (cwd) {
18134
18749
  resolvedCwd = cwd;
18135
18750
  }
@@ -18537,8 +19152,8 @@ async function fetchAntigravityQuota(run, now = /* @__PURE__ */ new Date()) {
18537
19152
  import { randomBytes, randomUUID as randomUUID4, timingSafeEqual } from "node:crypto";
18538
19153
  import { mkdir as mkdir3, mkdtemp as mkdtemp2, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
18539
19154
  import { createServer } from "node:http";
18540
- import os4 from "node:os";
18541
- import path8 from "node:path";
19155
+ import os5 from "node:os";
19156
+ import path9 from "node:path";
18542
19157
 
18543
19158
  // dist/question-hook-client.js
18544
19159
  var ANTIGRAVITY_QUESTION_HOOK_CLIENT = String.raw`
@@ -18663,7 +19278,7 @@ var AntigravityQuestionBridge = class _AntigravityQuestionBridge {
18663
19278
  this.#server.on("request", (request, response) => this.#receive(request, response));
18664
19279
  }
18665
19280
  static async create(options) {
18666
- 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-"));
18667
19282
  const bridge = new _AntigravityQuestionBridge(directory, options);
18668
19283
  try {
18669
19284
  await new Promise((resolve, reject) => {
@@ -18678,14 +19293,14 @@ var AntigravityQuestionBridge = class _AntigravityQuestionBridge {
18678
19293
  if (!address || typeof address === "string")
18679
19294
  throw new Error("Question bridge did not bind");
18680
19295
  bridge.environment.CODEXHOST_AGY_QUESTION_URL = `http://127.0.0.1:${address.port}/question`;
18681
- const client = path8.join(directory, "question-hook.cjs");
18682
- 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 });
18683
19298
  await writeFile3(client, ANTIGRAVITY_QUESTION_HOOK_CLIENT, "utf8");
18684
19299
  const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
18685
19300
  bridge.environment.CODEXHOST_AGY_QUESTION_NODE = `"${process.execPath.replaceAll("\\", "/")}"`;
18686
19301
  bridge.environment.CODEXHOST_AGY_QUESTION_CLIENT = `"${client.replaceAll("\\", "/")}"`;
18687
19302
  const command = process.platform === "win32" ? "%CODEXHOST_AGY_QUESTION_NODE% %CODEXHOST_AGY_QUESTION_CLIENT%" : `${quote(process.execPath)} ${quote(client)}`;
18688
- await writeFile3(path8.join(directory, ".agents", "hooks.json"), JSON.stringify({
19303
+ await writeFile3(path9.join(directory, ".agents", "hooks.json"), JSON.stringify({
18689
19304
  "codexhost-question-bridge": {
18690
19305
  PreToolUse: [
18691
19306
  {
@@ -18922,7 +19537,7 @@ import { randomUUID as randomUUID5 } from "node:crypto";
18922
19537
  // dist/subagent-transcript.js
18923
19538
  import { open, realpath } from "node:fs/promises";
18924
19539
  import https2 from "node:https";
18925
- import path9 from "node:path";
19540
+ import path10 from "node:path";
18926
19541
  var nativeSubagentIdSchema = external_exports.uuid();
18927
19542
  var MAX_TRANSCRIPT_BYTES = 8 * 1024 * 1024;
18928
19543
  var transcriptStepSchema = external_exports.object({
@@ -19090,10 +19705,10 @@ async function readSubagentTranscript(input) {
19090
19705
  };
19091
19706
  }
19092
19707
  try {
19093
- const file2 = path9.join(nativeBrainDirPath(input.childId, input.home), ".system_generated", "logs", "transcript.jsonl");
19094
- 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)));
19095
19710
  const resolved = await realpath(file2);
19096
- 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");
19097
19712
  const normalize = (value) => process.platform === "win32" ? value.toLowerCase() : value;
19098
19713
  if (normalize(resolved) !== normalize(expected))
19099
19714
  throw new Error("Subagent log redirects outside its native location");
@@ -19404,187 +20019,6 @@ var AntigravitySubagents = class {
19404
20019
  }
19405
20020
  };
19406
20021
 
19407
- // dist/usage-statistics.js
19408
- import { lstat, opendir } from "node:fs/promises";
19409
- import os5 from "node:os";
19410
- import path10 from "node:path";
19411
-
19412
- // ../../harness-adapter/dist/usage-statistics.js
19413
- import { createReadStream } from "node:fs";
19414
- import { createInterface } from "node:readline";
19415
- var HarnessUsageSourceChangedError = class extends Error {
19416
- code = "HARNESS_USAGE_SOURCE_CHANGED";
19417
- /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
19418
- static is(error51) {
19419
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
19420
- }
19421
- };
19422
- var MAX_SESSION_ID_LENGTH = 512;
19423
- var MAX_CWD_LENGTH = 4096;
19424
- var MAX_SESSION_TITLE_LENGTH = 200;
19425
- function usageSessionTitle(value) {
19426
- if (typeof value !== "string")
19427
- return void 0;
19428
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
19429
- if (!normalized)
19430
- return void 0;
19431
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
19432
- return normalized;
19433
- let title = "";
19434
- for (const character of normalized) {
19435
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
19436
- break;
19437
- title += character;
19438
- }
19439
- return `${title.trimEnd()}…`;
19440
- }
19441
- function sessionIdOk(value) {
19442
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
19443
- }
19444
- function cwdOk(value) {
19445
- 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("\\\\"));
19446
- }
19447
- function withUsageSession(entry, session) {
19448
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
19449
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
19450
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
19451
- if (sessionId === void 0 && cwd === void 0)
19452
- return entry;
19453
- return {
19454
- ...entry,
19455
- ...sessionId !== void 0 ? { sessionId } : {},
19456
- ...cwd !== void 0 ? { cwd } : {},
19457
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
19458
- };
19459
- }
19460
- async function* jsonlRecords(file2, marker, signal) {
19461
- const lines = createInterface({
19462
- input: createReadStream(file2, { encoding: "utf8", signal }),
19463
- crlfDelay: Infinity
19464
- });
19465
- for await (const line of lines) {
19466
- if (!line.includes(marker))
19467
- continue;
19468
- let value;
19469
- try {
19470
- value = JSON.parse(line);
19471
- } catch {
19472
- continue;
19473
- }
19474
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
19475
- yield value;
19476
- }
19477
- }
19478
- }
19479
- function nativeTimeMs(value) {
19480
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
19481
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
19482
- }
19483
-
19484
- // dist/usage-statistics.js
19485
- function count2(value) {
19486
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
19487
- }
19488
- function antigravityHome(environment) {
19489
- return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os5.homedir();
19490
- }
19491
- function transcriptPath(brainRoot, conversationId) {
19492
- return path10.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
19493
- }
19494
- function isMissing(error51) {
19495
- const code = error51?.code;
19496
- return code === "ENOENT" || code === "ENOTDIR";
19497
- }
19498
- async function lstatIfPresent(target) {
19499
- try {
19500
- return await lstat(target);
19501
- } catch (error51) {
19502
- if (isMissing(error51))
19503
- return null;
19504
- throw error51;
19505
- }
19506
- }
19507
- async function transcriptFingerprint(file2) {
19508
- const logs = path10.dirname(file2);
19509
- for (const directory of [path10.dirname(logs), logs]) {
19510
- if (!(await lstatIfPresent(directory))?.isDirectory())
19511
- return null;
19512
- }
19513
- const info = await lstatIfPresent(file2);
19514
- return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
19515
- }
19516
- async function listTranscripts(brainRoot, signal) {
19517
- signal.throwIfAborted();
19518
- const conversations = await opendir(brainRoot).catch((error51) => {
19519
- if (error51.code === "ENOENT")
19520
- return null;
19521
- throw error51;
19522
- });
19523
- if (!conversations)
19524
- return [];
19525
- const sources = [];
19526
- for await (const entry of conversations) {
19527
- signal.throwIfAborted();
19528
- if (!entry.isDirectory())
19529
- continue;
19530
- const file2 = transcriptPath(brainRoot, entry.name);
19531
- const fingerprint = await transcriptFingerprint(file2);
19532
- if (fingerprint)
19533
- sources.push({ id: file2, fingerprint });
19534
- }
19535
- return sources;
19536
- }
19537
- async function readAntigravityUsage(file2, signal) {
19538
- const sessionId = path10.basename(path10.resolve(file2, "..", "..", ".."));
19539
- const requests = /* @__PURE__ */ new Map();
19540
- for await (const record3 of jsonlRecords(file2, '"input_tokens"', signal)) {
19541
- if (record3.type !== "PLANNER_RESPONSE")
19542
- continue;
19543
- const step = count2(record3.step_index);
19544
- const input = count2(record3.input_tokens);
19545
- const output = count2(record3.output_tokens);
19546
- const cached2 = count2(record3.cache_read_tokens);
19547
- const at = nativeTimeMs(record3.created_at);
19548
- if (step === null || input === null || output === null || at === null)
19549
- continue;
19550
- requests.set(step, withUsageSession({
19551
- id: `${String(record3.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
19552
- occurredAtMs: at,
19553
- inputTokens: input + (cached2 ?? 0),
19554
- ...cached2 !== null ? { cachedInputTokens: cached2 } : {},
19555
- outputTokens: output
19556
- }, { sessionId }));
19557
- }
19558
- return [...requests.values()];
19559
- }
19560
- function createAntigravityUsageStatistics(environment) {
19561
- const brainRoot = nativeBrainRoot(antigravityHome(environment));
19562
- let listed = /* @__PURE__ */ new Map();
19563
- return Object.freeze({
19564
- async listSources(signal) {
19565
- const sources = await listTranscripts(brainRoot, signal);
19566
- listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
19567
- return sources;
19568
- },
19569
- async readSource(id, signal) {
19570
- const expected = listed.get(id);
19571
- let entries;
19572
- try {
19573
- entries = await readAntigravityUsage(id, signal);
19574
- } catch (error51) {
19575
- if (expected !== void 0 && isMissing(error51)) {
19576
- throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
19577
- }
19578
- throw error51;
19579
- }
19580
- if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
19581
- throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
19582
- }
19583
- return entries;
19584
- }
19585
- });
19586
- }
19587
-
19588
20022
  // dist/antigravity-adapter.js
19589
20023
  function unstreamedReplyTail(streamed, reply) {
19590
20024
  const shown = streamed.replace(/\s+/gu, "");
@@ -19690,6 +20124,34 @@ var ANTIGRAVITY_WORKSPACE_FILE_INSTRUCTION = "[System Instruction: When creating
19690
20124
  function antigravityWorkingDirectoryInstruction(cwd) {
19691
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.]
19692
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
+
19693
20155
  `;
19694
20156
  }
19695
20157
  function formatAntigravityTurnPrompt(text, cwd) {
@@ -19842,6 +20304,25 @@ function normalizedProcessError(detail, fallback, exposeDetail = false) {
19842
20304
  ...diagnostic ? { stderrTail: diagnostic.slice(-4e3) } : {}
19843
20305
  };
19844
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
+ }
19845
20326
  async function runBuffered(executable, arguments_, cwd, environment, timeoutMs, signal) {
19846
20327
  const invocation = commandInvocation(executable, arguments_, environment);
19847
20328
  return await new Promise((resolve, reject) => {
@@ -19993,6 +20474,7 @@ var AntigravitySession = class {
19993
20474
  };
19994
20475
  }
19995
20476
  let questions;
20477
+ let includeRecoveredHistory = false;
19996
20478
  const hookDirectory = antigravityHookDirectory(this.#environment);
19997
20479
  const previousTurn = hookDirectory ? this.#questionCleanup : Promise.resolve();
19998
20480
  this.#preparingQuestions = previousTurn.then(() => AntigravityQuestionBridge.create({
@@ -20022,12 +20504,18 @@ var AntigravitySession = class {
20022
20504
  }));
20023
20505
  try {
20024
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
+ }
20025
20512
  } catch (error51) {
20513
+ await questions?.dispose();
20026
20514
  return {
20027
20515
  ok: false,
20028
20516
  error: {
20029
20517
  code: "nativeFailure",
20030
- message: `Question bridge setup failed: ${errorMessage(error51)}`,
20518
+ message: `Antigravity Turn setup failed: ${errorMessage(error51)}`,
20031
20519
  retryable: true
20032
20520
  }
20033
20521
  };
@@ -20048,8 +20536,9 @@ var AntigravitySession = class {
20048
20536
  "--print-timeout",
20049
20537
  this.#printTimeout
20050
20538
  ];
20051
- if (this.#nativeRef)
20539
+ if (this.#nativeRef) {
20052
20540
  arguments_.unshift("--conversation", this.#nativeRef.nativeSessionId);
20541
+ }
20053
20542
  arguments_.push(...antigravityModelArguments(this.#model, this.#thinkingOptionId));
20054
20543
  arguments_.push("--dangerously-skip-permissions");
20055
20544
  arguments_.push("--add-dir", this.#cwd);
@@ -20162,7 +20651,8 @@ ${line}`).slice(-8e3);
20162
20651
  });
20163
20652
  });
20164
20653
  try {
20165
- 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);
20166
20656
  if (child.stdin.writable) {
20167
20657
  child.stdin.write(`${JSON.stringify({ event: "user", message: { content: turnPrompt } })}
20168
20658
  `, () => void 0);
@@ -20221,15 +20711,9 @@ ${line}`).slice(-8e3);
20221
20711
  if (event.event === "init") {
20222
20712
  active.nativePermissionMode = event.init?.permission_mode ?? null;
20223
20713
  if (this.#nativeRef && this.#nativeRef.nativeSessionId !== event.conversation_id) {
20224
- this.#completeTurn(active, {
20225
- status: "failed",
20226
- error: {
20227
- code: "sessionNotFound",
20228
- message: "Antigravity resumed a different Conversation",
20229
- retryable: false
20230
- }
20231
- });
20232
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 });
20233
20717
  return;
20234
20718
  }
20235
20719
  this.#nativeRef = nativeSessionRefSchema.parse({
@@ -20520,14 +21004,14 @@ ${line}`).slice(-8e3);
20520
21004
  const claimed = active.fileChanges.get(step.step_index);
20521
21005
  if (claimed)
20522
21006
  return claimed;
20523
- const target = toolTargetFile(toolName, step.tool_info?.parameters);
20524
- if (!target)
21007
+ const target2 = toolTargetFile(toolName, step.tool_info?.parameters);
21008
+ if (!target2)
20525
21009
  return null;
20526
21010
  const port = await this.#languageServerPort(active);
20527
21011
  if (port === null)
20528
21012
  return null;
20529
21013
  const actions = await requestAntigravityTrajectorySteps(port, step.conversation_id, TRAJECTORY_TIMEOUT_MS);
20530
- 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));
20531
21015
  const action = index === -1 ? void 0 : actions[index];
20532
21016
  if (!action)
20533
21017
  return null;