@liberseek/boft-cli-linux-x64 0.7.8 → 0.7.9

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.
@@ -412,7 +412,7 @@ async function readGrokCredentials(environment) {
412
412
  }
413
413
 
414
414
  // dist/grok-adapter.js
415
- import path12 from "node:path";
415
+ import path13 from "node:path";
416
416
 
417
417
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
418
418
  var AGENT_METHODS = {
@@ -1232,10 +1232,10 @@ function mergeDefs(...defs) {
1232
1232
  function cloneDef(schema) {
1233
1233
  return mergeDefs(schema._zod.def);
1234
1234
  }
1235
- function getElementAtPath(obj, path13) {
1236
- if (!path13)
1235
+ function getElementAtPath(obj, path14) {
1236
+ if (!path14)
1237
1237
  return obj;
1238
- return path13.reduce((acc, key) => acc?.[key], obj);
1238
+ return path14.reduce((acc, key) => acc?.[key], obj);
1239
1239
  }
1240
1240
  function promiseAllObject(promisesObj) {
1241
1241
  const keys = Object.keys(promisesObj);
@@ -1644,11 +1644,11 @@ function explicitlyAborted(x, startIndex = 0) {
1644
1644
  }
1645
1645
  return false;
1646
1646
  }
1647
- function prefixIssues(path13, issues) {
1647
+ function prefixIssues(path14, issues) {
1648
1648
  return issues.map((iss) => {
1649
1649
  var _a3;
1650
1650
  (_a3 = iss).path ?? (_a3.path = []);
1651
- iss.path.unshift(path13);
1651
+ iss.path.unshift(path14);
1652
1652
  return iss;
1653
1653
  });
1654
1654
  }
@@ -1795,16 +1795,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1795
1795
  }
1796
1796
  function formatError(error53, mapper = (issue2) => issue2.message) {
1797
1797
  const fieldErrors = { _errors: [] };
1798
- const processError = (error54, path13 = []) => {
1798
+ const processError = (error54, path14 = []) => {
1799
1799
  for (const issue2 of error54.issues) {
1800
1800
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1801
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1801
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1802
1802
  } else if (issue2.code === "invalid_key") {
1803
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1803
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1804
1804
  } else if (issue2.code === "invalid_element") {
1805
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1805
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1806
1806
  } else {
1807
- const fullpath = [...path13, ...issue2.path];
1807
+ const fullpath = [...path14, ...issue2.path];
1808
1808
  if (fullpath.length === 0) {
1809
1809
  fieldErrors._errors.push(mapper(issue2));
1810
1810
  } else {
@@ -1831,17 +1831,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1831
1831
  }
1832
1832
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1833
1833
  const result = { errors: [] };
1834
- const processError = (error54, path13 = []) => {
1834
+ const processError = (error54, path14 = []) => {
1835
1835
  var _a3, _b;
1836
1836
  for (const issue2 of error54.issues) {
1837
1837
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1838
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1838
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1839
1839
  } else if (issue2.code === "invalid_key") {
1840
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1840
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1841
1841
  } else if (issue2.code === "invalid_element") {
1842
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1842
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1843
1843
  } else {
1844
- const fullpath = [...path13, ...issue2.path];
1844
+ const fullpath = [...path14, ...issue2.path];
1845
1845
  if (fullpath.length === 0) {
1846
1846
  result.errors.push(mapper(issue2));
1847
1847
  continue;
@@ -1873,8 +1873,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
1873
1873
  }
1874
1874
  function toDotPath(_path) {
1875
1875
  const segs = [];
1876
- const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1877
- for (const seg of path13) {
1876
+ const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1877
+ for (const seg of path14) {
1878
1878
  if (typeof seg === "number")
1879
1879
  segs.push(`[${seg}]`);
1880
1880
  else if (typeof seg === "symbol")
@@ -14566,13 +14566,13 @@ function resolveRef(ref, ctx) {
14566
14566
  if (!ref.startsWith("#")) {
14567
14567
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14568
14568
  }
14569
- const path13 = ref.slice(1).split("/").filter(Boolean);
14570
- if (path13.length === 0) {
14569
+ const path14 = ref.slice(1).split("/").filter(Boolean);
14570
+ if (path14.length === 0) {
14571
14571
  return ctx.rootSchema;
14572
14572
  }
14573
14573
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14574
- if (path13[0] === defsKey) {
14575
- const key = path13[1];
14574
+ if (path14[0] === defsKey) {
14575
+ const key = path14[1];
14576
14576
  if (!key || !ctx.defs[key]) {
14577
14577
  throw new Error(`Reference not found: ${ref}`);
14578
14578
  }
@@ -19169,6 +19169,10 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
19169
19169
  var hostItemIdSchema = opaqueIdSchema.brand();
19170
19170
  var hostInteractionIdSchema = opaqueIdSchema.brand();
19171
19171
 
19172
+ // ../../shared-contracts/dist/thread-prewarm.js
19173
+ var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
19174
+ var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
19175
+
19172
19176
  // ../../shared-contracts/dist/harness-plugins.js
19173
19177
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
19174
19178
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -19236,6 +19240,9 @@ var consoleOpenResultSchema = external_exports.strictObject({
19236
19240
  url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
19237
19241
  });
19238
19242
  var CONSOLE_HOST_METHODS = Object.freeze([
19243
+ "codexhost/console/remote-connections",
19244
+ "codexhost/runtime/status",
19245
+ "codexhost/remote/ssh-setup",
19239
19246
  "codexhost/harness/plugins/list",
19240
19247
  "codexhost/harness/display-settings/get",
19241
19248
  "codexhost/harness/display-settings/set",
@@ -20181,6 +20188,80 @@ var updateStatusResultSchema = external_exports.strictObject({
20181
20188
  status: updateStatusSchema.nullable()
20182
20189
  });
20183
20190
 
20191
+ // ../../shared-contracts/dist/remote-runtime.js
20192
+ var remoteUpdatePhaseSchema = external_exports.enum([
20193
+ "idle",
20194
+ "installing",
20195
+ "restarting",
20196
+ "succeeded",
20197
+ "failed"
20198
+ ]);
20199
+ var runtimeStatusSchema = external_exports.object({
20200
+ runningVersion: external_exports.string().nullable(),
20201
+ installedVersion: external_exports.string().nullable(),
20202
+ restartRequired: external_exports.boolean(),
20203
+ remote: external_exports.boolean(),
20204
+ updateSupported: external_exports.boolean(),
20205
+ update: external_exports.object({
20206
+ phase: remoteUpdatePhaseSchema,
20207
+ targetVersion: external_exports.string().nullable(),
20208
+ error: external_exports.string().nullable()
20209
+ })
20210
+ });
20211
+ var remoteUpdateParamsSchema = external_exports.object({
20212
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)
20213
+ }).strict();
20214
+ var remoteSshSetupParamsSchema = external_exports.object({
20215
+ hostname: external_exports.string().min(1).max(1024).refine((value) => !value.startsWith("-") && !/\s/u.test(value)),
20216
+ port: external_exports.number().int().min(1).max(65535).nullable(),
20217
+ identity: external_exports.string().max(4096).nullable(),
20218
+ action: external_exports.enum(["inspect", "install", "update", "repair", "uninstall"]),
20219
+ uninstallPackage: external_exports.boolean().optional(),
20220
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+$/u).nullable()
20221
+ }).strict();
20222
+ var remoteSshSetupResultSchema = external_exports.object({ state: external_exports.enum(["installed", "not-installed"]) }).strict();
20223
+
20224
+ // ../../shared-contracts/dist/remote-connections.js
20225
+ var hostId = external_exports.string().min(1).max(1024);
20226
+ var codexSshConnectionSchema = external_exports.object({
20227
+ hostId,
20228
+ displayName: external_exports.string().min(1).max(1024),
20229
+ source: external_exports.enum(["codex-managed", "discovered"]),
20230
+ sshAlias: external_exports.string().max(1024).nullable(),
20231
+ sshHost: external_exports.string().min(1).max(1024),
20232
+ sshPort: external_exports.number().int().min(1).max(65535).nullable(),
20233
+ identity: external_exports.string().max(4096).nullable(),
20234
+ autoConnect: external_exports.boolean(),
20235
+ connectionAnalyticsId: external_exports.string().max(1024).optional()
20236
+ });
20237
+ var codexSshDraftSchema = external_exports.strictObject({
20238
+ displayName: external_exports.string().min(1).max(1024),
20239
+ hostname: external_exports.string().min(1).max(1024),
20240
+ sshPort: external_exports.number().int().min(1).max(65535).nullable(),
20241
+ identity: external_exports.string().max(4096).nullable()
20242
+ });
20243
+ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
20244
+ external_exports.strictObject({ action: external_exports.literal("list") }),
20245
+ external_exports.strictObject({
20246
+ action: external_exports.literal("save"),
20247
+ draft: codexSshDraftSchema,
20248
+ previous: codexSshConnectionSchema.nullable()
20249
+ }),
20250
+ external_exports.strictObject({ action: external_exports.literal("remove"), previous: codexSshConnectionSchema }),
20251
+ external_exports.strictObject({ action: external_exports.literal("connect"), hostId, enabled: external_exports.boolean() }),
20252
+ external_exports.strictObject({ action: external_exports.literal("state"), hostId }),
20253
+ external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
20254
+ external_exports.strictObject({
20255
+ action: external_exports.literal("update"),
20256
+ hostId: hostId.refine((id) => id !== "local"),
20257
+ version: remoteUpdateParamsSchema.shape.version
20258
+ })
20259
+ ]);
20260
+ var remoteConnectionsReplySchema = external_exports.union([
20261
+ external_exports.strictObject({ result: jsonValueSchema }),
20262
+ external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
20263
+ ]);
20264
+
20184
20265
  // ../../shared-contracts/dist/index.js
20185
20266
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
20186
20267
 
@@ -20531,8 +20612,8 @@ function parseGrokAvailableCommands(value) {
20531
20612
  });
20532
20613
  }
20533
20614
  function isGrokSkill(command) {
20534
- const path13 = command.meta?.path;
20535
- return typeof path13 === "string" && /(^|[\\/])SKILL\.md$/u.test(path13) || typeof command.meta?.qualifiedName === "string";
20615
+ const path14 = command.meta?.path;
20616
+ return typeof path14 === "string" && /(^|[\\/])SKILL\.md$/u.test(path14) || typeof command.meta?.qualifiedName === "string";
20536
20617
  }
20537
20618
  function grokLiveCommands(native) {
20538
20619
  return native.map((command) => ({
@@ -20691,16 +20772,16 @@ var Diff = class {
20691
20772
  }
20692
20773
  }
20693
20774
  }
20694
- addToPath(path13, added, removed, oldPosInc, options) {
20695
- const last = path13.lastComponent;
20775
+ addToPath(path14, added, removed, oldPosInc, options) {
20776
+ const last = path14.lastComponent;
20696
20777
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
20697
20778
  return {
20698
- oldPos: path13.oldPos + oldPosInc,
20779
+ oldPos: path14.oldPos + oldPosInc,
20699
20780
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
20700
20781
  };
20701
20782
  } else {
20702
20783
  return {
20703
- oldPos: path13.oldPos + oldPosInc,
20784
+ oldPos: path14.oldPos + oldPosInc,
20704
20785
  lastComponent: { count: 1, added, removed, previousComponent: last }
20705
20786
  };
20706
20787
  }
@@ -23676,6 +23757,323 @@ var GrokAcpTransport = class {
23676
23757
  }
23677
23758
  };
23678
23759
 
23760
+ // dist/session-import.js
23761
+ import { createReadStream } from "node:fs";
23762
+ import { opendir, readFile as readFile3, stat } from "node:fs/promises";
23763
+ import path11 from "node:path";
23764
+ import { createInterface } from "node:readline";
23765
+
23766
+ // ../../harness-adapter/dist/session-import.js
23767
+ import { lstat } from "node:fs/promises";
23768
+ var SessionImportChangedError = class extends Error {
23769
+ constructor(message = "Native Session changed during discovery; refresh and retry") {
23770
+ super(message);
23771
+ this.name = "SessionImportChangedError";
23772
+ }
23773
+ };
23774
+ function isMissingFileError(error53) {
23775
+ return typeof error53 === "object" && error53 !== null && "code" in error53 && error53.code === "ENOENT";
23776
+ }
23777
+ function sameFileFingerprint(left, right) {
23778
+ return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
23779
+ }
23780
+ var STORAGE_ACCESS_ERRORS = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"]);
23781
+ function isStorageAccessError(error53) {
23782
+ return typeof error53 === "object" && error53 !== null && "code" in error53 && typeof error53.code === "string" && STORAGE_ACCESS_ERRORS.has(error53.code);
23783
+ }
23784
+ async function optionalLstat(file2) {
23785
+ try {
23786
+ return await lstat(file2);
23787
+ } catch (error53) {
23788
+ if (isMissingFileError(error53))
23789
+ return null;
23790
+ throw error53;
23791
+ }
23792
+ }
23793
+ async function readStableFiles(files, read) {
23794
+ const before = await Promise.all(files.map(optionalLstat));
23795
+ const value = await read(before);
23796
+ const after = await Promise.all(files.map(optionalLstat));
23797
+ if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
23798
+ throw new SessionImportChangedError();
23799
+ return value;
23800
+ }
23801
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
23802
+ if (typeof value !== "string")
23803
+ return null;
23804
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
23805
+ if (!normalized)
23806
+ return null;
23807
+ if (normalized.length <= maxLength)
23808
+ return normalized;
23809
+ const characters = [...normalized];
23810
+ if (characters.length <= maxLength)
23811
+ return normalized;
23812
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
23813
+ }
23814
+ function sessionImportCandidate(input) {
23815
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
23816
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
23817
+ nativeSessionId: input.nativeSessionId,
23818
+ cwd: input.cwd,
23819
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
23820
+ updatedAt: Math.floor(time3),
23821
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
23822
+ running: typeof input.running === "boolean" ? input.running : null
23823
+ });
23824
+ return parsed.success ? parsed.data : null;
23825
+ }
23826
+ var SessionImportScope = class {
23827
+ #abort = new AbortController();
23828
+ #options;
23829
+ #pending = /* @__PURE__ */ new Set();
23830
+ constructor(options) {
23831
+ this.#options = options;
23832
+ }
23833
+ #closed() {
23834
+ return {
23835
+ ok: false,
23836
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
23837
+ };
23838
+ }
23839
+ read(operation) {
23840
+ const signal = this.#abort.signal;
23841
+ if (signal.aborted)
23842
+ return Promise.resolve(this.#closed());
23843
+ let started;
23844
+ try {
23845
+ started = operation(signal);
23846
+ } catch (error53) {
23847
+ started = Promise.reject(error53 instanceof Error ? error53 : new Error("Session read failed"));
23848
+ }
23849
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
23850
+ ok: false,
23851
+ error: {
23852
+ code: "unavailable",
23853
+ message: this.#options.unavailableMessage,
23854
+ retryable: true
23855
+ }
23856
+ }).finally(() => this.#pending.delete(request));
23857
+ this.#pending.add(request);
23858
+ return request;
23859
+ }
23860
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
23861
+ async resolve(operation) {
23862
+ const result = await this.read(operation);
23863
+ if (!result.ok)
23864
+ return result;
23865
+ return result.value ? { ok: true, value: result.value } : {
23866
+ ok: false,
23867
+ error: {
23868
+ code: "sessionNotFound",
23869
+ message: this.#options.notFoundMessage,
23870
+ retryable: false
23871
+ }
23872
+ };
23873
+ }
23874
+ /** Idempotent. Resolves after every started read has settled. */
23875
+ async close() {
23876
+ this.#abort.abort();
23877
+ await Promise.allSettled(this.#pending);
23878
+ }
23879
+ };
23880
+
23881
+ // dist/session-import.js
23882
+ var MAX_METADATA_BYTES = 4 * 1024 * 1024;
23883
+ var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
23884
+ function isRecord14(value) {
23885
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23886
+ }
23887
+ async function readJson(file2, signal) {
23888
+ return JSON.parse(await readFile3(file2, { encoding: "utf8", signal }));
23889
+ }
23890
+ function processAlive(pid) {
23891
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
23892
+ return false;
23893
+ try {
23894
+ process.kill(pid, 0);
23895
+ return true;
23896
+ } catch (error53) {
23897
+ return isRecord14(error53) && error53.code === "EPERM";
23898
+ }
23899
+ }
23900
+ async function firstUserText(file2, signal) {
23901
+ const stream = createReadStream(file2, { encoding: "utf8", signal });
23902
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
23903
+ try {
23904
+ for await (const line of lines) {
23905
+ signal.throwIfAborted();
23906
+ if (!line.includes("user_message_chunk"))
23907
+ continue;
23908
+ let entry;
23909
+ try {
23910
+ entry = JSON.parse(line);
23911
+ } catch {
23912
+ continue;
23913
+ }
23914
+ const update = isRecord14(entry) && isRecord14(entry.params) ? entry.params.update : null;
23915
+ if (!isRecord14(update) || update.sessionUpdate !== "user_message_chunk")
23916
+ continue;
23917
+ const text = isRecord14(update.content) ? update.content.text : null;
23918
+ return typeof text === "string" ? text : "";
23919
+ }
23920
+ return null;
23921
+ } finally {
23922
+ lines.close();
23923
+ stream.destroy();
23924
+ }
23925
+ }
23926
+ var GrokSessionImport = class {
23927
+ #environment;
23928
+ #scope = new SessionImportScope({
23929
+ closedMessage: "Grok Session import is closed",
23930
+ unavailableMessage: "Grok sessions could not be read; close native clients, check storage access and retry",
23931
+ notFoundMessage: "Grok Session is no longer importable"
23932
+ });
23933
+ constructor(environment) {
23934
+ this.#environment = environment ? { ...environment } : void 0;
23935
+ }
23936
+ listCandidates() {
23937
+ return this.#scope.read(async (signal) => {
23938
+ const active = await this.#activeSessions(signal);
23939
+ const candidates = [];
23940
+ for (const [, directories] of await this.#sessionDirectories(signal)) {
23941
+ if (directories.length !== 1 || !directories[0])
23942
+ continue;
23943
+ try {
23944
+ const candidate = await this.#candidate(directories[0], active, signal);
23945
+ if (candidate)
23946
+ candidates.push(candidate);
23947
+ } catch (error53) {
23948
+ if (!(error53 instanceof SessionImportChangedError))
23949
+ throw error53;
23950
+ }
23951
+ }
23952
+ return candidates;
23953
+ });
23954
+ }
23955
+ resolveCandidate(nativeSessionId) {
23956
+ return this.#scope.resolve(async (signal) => {
23957
+ const directories = (await this.#sessionDirectories(signal)).get(nativeSessionId);
23958
+ if (directories?.length !== 1 || !directories[0])
23959
+ return null;
23960
+ const candidate = await this.#candidate(directories[0], await this.#activeSessions(signal), signal);
23961
+ if (!candidate)
23962
+ return null;
23963
+ return {
23964
+ candidate,
23965
+ nativeRef: nativeSessionRefSchema.parse({
23966
+ harnessId: "grok",
23967
+ nativeSessionId,
23968
+ formatVersion: 1
23969
+ })
23970
+ };
23971
+ });
23972
+ }
23973
+ close() {
23974
+ return this.#scope.close();
23975
+ }
23976
+ #home() {
23977
+ return grokHomeDir(this.#environment ? { environment: this.#environment } : {});
23978
+ }
23979
+ /** IDs a live Grok process currently holds open, from Grok's own registry. */
23980
+ async #activeSessions(signal) {
23981
+ const active = /* @__PURE__ */ new Set();
23982
+ let entries;
23983
+ try {
23984
+ entries = await readJson(path11.join(this.#home(), "active_sessions.json"), signal);
23985
+ } catch (error53) {
23986
+ signal.throwIfAborted();
23987
+ if (isStorageAccessError(error53))
23988
+ throw error53;
23989
+ return active;
23990
+ }
23991
+ if (!Array.isArray(entries))
23992
+ return active;
23993
+ for (const entry of entries) {
23994
+ if (isRecord14(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
23995
+ active.add(entry.session_id);
23996
+ }
23997
+ return active;
23998
+ }
23999
+ /** Session ID to every directory claiming it. Enumerated links are not followed. */
24000
+ async #sessionDirectories(signal) {
24001
+ const root = path11.join(this.#home(), "sessions");
24002
+ const found = /* @__PURE__ */ new Map();
24003
+ const info = await optionalLstat(root);
24004
+ if (!info)
24005
+ return found;
24006
+ if (!info.isDirectory())
24007
+ throw new Error("Grok Session store is not a directory");
24008
+ for await (const workspace of await opendir(root)) {
24009
+ signal.throwIfAborted();
24010
+ if (!workspace.isDirectory())
24011
+ continue;
24012
+ const workspaceDirectory = path11.join(root, workspace.name);
24013
+ const sessions = await opendir(workspaceDirectory).catch((error53) => {
24014
+ if (isMissingFileError(error53))
24015
+ return null;
24016
+ throw error53;
24017
+ });
24018
+ if (!sessions)
24019
+ continue;
24020
+ for await (const session of sessions) {
24021
+ signal.throwIfAborted();
24022
+ if (!session.isDirectory())
24023
+ continue;
24024
+ const directories = found.get(session.name) ?? [];
24025
+ directories.push(path11.join(workspaceDirectory, session.name));
24026
+ found.set(session.name, directories);
24027
+ }
24028
+ }
24029
+ return found;
24030
+ }
24031
+ async #candidate(sessionDirectory, active, signal) {
24032
+ signal.throwIfAborted();
24033
+ const nativeSessionId = path11.basename(sessionDirectory);
24034
+ const files = [
24035
+ path11.join(sessionDirectory, "summary.json"),
24036
+ path11.join(sessionDirectory, "updates.jsonl")
24037
+ ];
24038
+ return readStableFiles(files, async ([summaryInfo, updates]) => {
24039
+ if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
24040
+ return null;
24041
+ try {
24042
+ const summary = await readJson(files[0], signal);
24043
+ if (!isRecord14(summary) || !isRecord14(summary.info) || summary.info.id !== nativeSessionId)
24044
+ return null;
24045
+ if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
24046
+ return null;
24047
+ const nativeCwd = summary.info.cwd;
24048
+ if (typeof nativeCwd !== "string" || !path11.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24049
+ return null;
24050
+ const cwd = path11.resolve(nativeCwd);
24051
+ if (encodeURIComponent(cwd) !== path11.basename(path11.dirname(sessionDirectory)))
24052
+ return null;
24053
+ if (!(await stat(cwd)).isDirectory())
24054
+ return null;
24055
+ const prompt = await firstUserText(files[1], signal);
24056
+ if (prompt === null)
24057
+ return null;
24058
+ const updatedAt = [summary.last_active_at, summary.updated_at].map((value) => typeof value === "string" ? Date.parse(value) : Number.NaN).find((value) => Number.isFinite(value) && value >= 0);
24059
+ return sessionImportCandidate({
24060
+ nativeSessionId,
24061
+ cwd,
24062
+ title: sessionImportTitle(summary.generated_title) ?? sessionImportTitle(summary.session_summary) ?? sessionImportTitle(prompt),
24063
+ updatedAt: updatedAt ?? updates.mtimeMs,
24064
+ // Grok registers open Sessions with their process. Absence is not proof of idleness.
24065
+ running: active.has(nativeSessionId) ? true : null
24066
+ });
24067
+ } catch (error53) {
24068
+ signal.throwIfAborted();
24069
+ if (isStorageAccessError(error53))
24070
+ throw error53;
24071
+ return null;
24072
+ }
24073
+ });
24074
+ }
24075
+ };
24076
+
23679
24077
  // dist/grok-subagent-lifecycle.js
23680
24078
  function subagentFailure() {
23681
24079
  return {
@@ -23869,7 +24267,7 @@ var GrokSubagentLifecycle = class {
23869
24267
  };
23870
24268
 
23871
24269
  // dist/grok-models.js
23872
- function isRecord14(value) {
24270
+ function isRecord15(value) {
23873
24271
  return typeof value === "object" && value !== null && !Array.isArray(value);
23874
24272
  }
23875
24273
  function nonBlank(value) {
@@ -23881,7 +24279,7 @@ function thinkingOptions(value) {
23881
24279
  const seen = /* @__PURE__ */ new Set();
23882
24280
  const options = [];
23883
24281
  for (const candidate of value) {
23884
- if (!isRecord14(candidate) || !nonBlank(candidate.label))
24282
+ if (!isRecord15(candidate) || !nonBlank(candidate.label))
23885
24283
  continue;
23886
24284
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
23887
24285
  if (!id.success || seen.has(id.data))
@@ -23892,7 +24290,7 @@ function thinkingOptions(value) {
23892
24290
  return options;
23893
24291
  }
23894
24292
  function parseGrokModelState(value) {
23895
- if (!isRecord14(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
24293
+ if (!isRecord15(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
23896
24294
  return null;
23897
24295
  }
23898
24296
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -23903,12 +24301,12 @@ function parseGrokModelState(value) {
23903
24301
  const models = [];
23904
24302
  let currentThinkingOptionId;
23905
24303
  for (const candidate of value.availableModels) {
23906
- if (!isRecord14(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
24304
+ if (!isRecord15(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
23907
24305
  continue;
23908
24306
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
23909
24307
  if (!ref.success)
23910
24308
  continue;
23911
- const metadata = isRecord14(candidate._meta) ? candidate._meta : {};
24309
+ const metadata = isRecord15(candidate._meta) ? candidate._meta : {};
23912
24310
  const options2 = thinkingOptions(metadata.reasoningEfforts);
23913
24311
  if (typeof metadata.totalContextTokens === "number" && Number.isSafeInteger(metadata.totalContextTokens) && metadata.totalContextTokens > 0) {
23914
24312
  contextWindowTokensByModel.set(ref.data.id, metadata.totalContextTokens);
@@ -23943,10 +24341,10 @@ function parseGrokModelState(value) {
23943
24341
  };
23944
24342
  }
23945
24343
  function modelStateFromInitialize(response) {
23946
- return parseGrokModelState(isRecord14(response._meta) ? response._meta.modelState : void 0);
24344
+ return parseGrokModelState(isRecord15(response._meta) ? response._meta.modelState : void 0);
23947
24345
  }
23948
24346
  function modelStateFromSessionResponse(response) {
23949
- return parseGrokModelState(isRecord14(response) ? response.models : void 0);
24347
+ return parseGrokModelState(isRecord15(response) ? response.models : void 0);
23950
24348
  }
23951
24349
  function stateForGrokModel(modelState, nativeState, model = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
23952
24350
  const selectedModel = model;
@@ -23965,12 +24363,12 @@ function stateForGrokModel(modelState, nativeState, model = modelState.currentMo
23965
24363
  }
23966
24364
 
23967
24365
  // dist/grok-credits.js
23968
- import { readFile as readFile3 } from "node:fs/promises";
24366
+ import { readFile as readFile4 } from "node:fs/promises";
23969
24367
  import os5 from "node:os";
23970
- import path11 from "node:path";
24368
+ import path12 from "node:path";
23971
24369
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
23972
24370
  var REQUEST_TIMEOUT_MS = 15e3;
23973
- function isRecord15(value) {
24371
+ function isRecord16(value) {
23974
24372
  return typeof value === "object" && value !== null && !Array.isArray(value);
23975
24373
  }
23976
24374
  function finitePercent(value) {
@@ -23979,7 +24377,7 @@ function finitePercent(value) {
23979
24377
  return Math.min(100, Math.max(0, value));
23980
24378
  }
23981
24379
  function nonNegativeCentValue(value) {
23982
- if (!isRecord15(value))
24380
+ if (!isRecord16(value))
23983
24381
  return void 0;
23984
24382
  const amount = value.val === void 0 ? 0 : value.val;
23985
24383
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
@@ -23987,7 +24385,7 @@ function nonNegativeCentValue(value) {
23987
24385
  return amount;
23988
24386
  }
23989
24387
  function grokHome(environment) {
23990
- return environment.GROK_HOME ?? path11.join(environment.HOME ?? environment.USERPROFILE ?? os5.homedir(), ".grok");
24388
+ return environment.GROK_HOME ?? path12.join(environment.HOME ?? environment.USERPROFILE ?? os5.homedir(), ".grok");
23991
24389
  }
23992
24390
  function periodTypeFrom(value) {
23993
24391
  if (typeof value !== "string")
@@ -24003,7 +24401,7 @@ function productUsageFrom(value) {
24003
24401
  if (!Array.isArray(value))
24004
24402
  return void 0;
24005
24403
  const products = value.flatMap((entry) => {
24006
- if (!isRecord15(entry) || typeof entry.product !== "string")
24404
+ if (!isRecord16(entry) || typeof entry.product !== "string")
24007
24405
  return [];
24008
24406
  const usagePercent = finitePercent(entry.usagePercent);
24009
24407
  return usagePercent === void 0 ? [] : [{ product: entry.product, usagePercent }];
@@ -24011,10 +24409,10 @@ function productUsageFrom(value) {
24011
24409
  return products.length > 0 ? products : void 0;
24012
24410
  }
24013
24411
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
24014
- if (!isRecord15(value) || !isRecord15(value.config))
24412
+ if (!isRecord16(value) || !isRecord16(value.config))
24015
24413
  return null;
24016
24414
  const config2 = value.config;
24017
- const period = isRecord15(config2.currentPeriod) ? config2.currentPeriod : void 0;
24415
+ const period = isRecord16(config2.currentPeriod) ? config2.currentPeriod : void 0;
24018
24416
  const periodType = periodTypeFrom(period?.type);
24019
24417
  const resetsAt = (typeof period?.end === "string" && period.end.length > 0 ? period.end : void 0) ?? (typeof config2.billingPeriodEnd === "string" && config2.billingPeriodEnd.length > 0 ? config2.billingPeriodEnd : void 0);
24020
24418
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -24041,11 +24439,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
24041
24439
  };
24042
24440
  }
24043
24441
  function selectAccessToken(auth, now) {
24044
- if (!isRecord15(auth))
24442
+ if (!isRecord16(auth))
24045
24443
  return null;
24046
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord15(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
24444
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord16(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
24047
24445
  for (const [, value] of entries) {
24048
- if (!isRecord15(value) || typeof value.key !== "string")
24446
+ if (!isRecord16(value) || typeof value.key !== "string")
24049
24447
  continue;
24050
24448
  if (typeof value.expires_at === "string") {
24051
24449
  const expiresAt = Date.parse(value.expires_at);
@@ -24066,8 +24464,8 @@ async function fetchGrokAccount(input = {}) {
24066
24464
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
24067
24465
  return null;
24068
24466
  const now = input.now ?? /* @__PURE__ */ new Date();
24069
- const authPath = path11.join(grokHome(environment), "auth.json");
24070
- const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile3(authPath, "utf8");
24467
+ const authPath = path12.join(grokHome(environment), "auth.json");
24468
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile4(authPath, "utf8");
24071
24469
  const token = selectAccessToken(JSON.parse(raw), now);
24072
24470
  if (!token)
24073
24471
  return null;
@@ -24117,7 +24515,7 @@ async function fetchGrokCredits(input = {}) {
24117
24515
 
24118
24516
  // dist/grok-usage.js
24119
24517
  var USD_TICKS_PER_DOLLAR = 1e10;
24120
- function isRecord16(value) {
24518
+ function isRecord17(value) {
24121
24519
  return typeof value === "object" && value !== null && !Array.isArray(value);
24122
24520
  }
24123
24521
  function optionalToken(value) {
@@ -24134,7 +24532,7 @@ function combineUsage(base, next) {
24134
24532
  return base === null ? next : parseHostUsage({ ...base, ...next });
24135
24533
  }
24136
24534
  function usageFromNative(value) {
24137
- if (!isRecord16(value))
24535
+ if (!isRecord17(value))
24138
24536
  return null;
24139
24537
  const nativeInputTokens = optionalToken(value.inputTokens);
24140
24538
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -24163,7 +24561,7 @@ function usageFromPrompt(response) {
24163
24561
  return response.usage ? usageFromNative(response.usage) : null;
24164
24562
  }
24165
24563
  function usageFromSignals(value) {
24166
- if (!isRecord16(value))
24564
+ if (!isRecord17(value))
24167
24565
  return null;
24168
24566
  try {
24169
24567
  return parseHostUsage({
@@ -24183,7 +24581,7 @@ var summedUsageFields = [
24183
24581
  "totalTokens"
24184
24582
  ];
24185
24583
  function nativeCostTicks(value) {
24186
- if (!isRecord16(value))
24584
+ if (!isRecord17(value))
24187
24585
  return void 0;
24188
24586
  const ticks = value.costUsdTicks;
24189
24587
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -24260,7 +24658,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
24260
24658
  function usageFromUpdate(update, metadata, contextWindowTokens) {
24261
24659
  try {
24262
24660
  if (update?.sessionUpdate === "usage_update") {
24263
- const cost = isRecord16(update.cost) ? update.cost : null;
24661
+ const cost = isRecord17(update.cost) ? update.cost : null;
24264
24662
  return parseHostUsage({
24265
24663
  contextUsedTokens: update.used,
24266
24664
  contextWindowTokens: update.size,
@@ -25367,6 +25765,7 @@ var GrokAdapter = class {
25367
25765
  commandCatalog = grokCommandCatalog;
25368
25766
  liveCommandCatalog = true;
25369
25767
  harnessId = grokHarnessId;
25768
+ sessionImport;
25370
25769
  subagents = {
25371
25770
  readSnapshot: async (input) => {
25372
25771
  if (input.parent.harnessId !== this.harnessId || input.nativeSubagentId.trim().length === 0) {
@@ -25415,6 +25814,7 @@ var GrokAdapter = class {
25415
25814
  constructor(options = {}, dependencies) {
25416
25815
  this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
25417
25816
  this.#environment = options.environment;
25817
+ this.sessionImport = new GrokSessionImport(options.environment);
25418
25818
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_GROK_TOOL_OUTPUT_LIMIT;
25419
25819
  this.#dependencies = dependencies ?? {
25420
25820
  randomUUID,
@@ -25463,7 +25863,7 @@ var GrokAdapter = class {
25463
25863
  async inspect(input = {}) {
25464
25864
  if (this.#closePromise)
25465
25865
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
25466
- const cwd = path12.resolve(input.cwd ?? process.cwd());
25866
+ const cwd = path13.resolve(input.cwd ?? process.cwd());
25467
25867
  if (!input.refresh) {
25468
25868
  const cached2 = this.#inspectionCache.get(cwd);
25469
25869
  if (cached2)
@@ -25525,7 +25925,7 @@ var GrokAdapter = class {
25525
25925
  }
25526
25926
  };
25527
25927
  }
25528
- const cwd = path12.resolve(input.cwd);
25928
+ const cwd = path13.resolve(input.cwd);
25529
25929
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
25530
25930
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
25531
25931
  return {
@@ -25696,7 +26096,10 @@ var GrokAdapter = class {
25696
26096
  if (!this.#closePromise) {
25697
26097
  this.#accountAbort.abort();
25698
26098
  this.#inspectionCache.clear();
25699
- this.#closePromise = Promise.all([...this.#sessions].map((session) => session.close())).then(() => void 0);
26099
+ this.#closePromise = Promise.all([
26100
+ this.sessionImport.close(),
26101
+ ...[...this.#sessions].map((session) => session.close())
26102
+ ]).then(() => void 0);
25700
26103
  }
25701
26104
  return this.#closePromise;
25702
26105
  }