@indigoai-us/hq-cli 5.345.212 → 5.345.215-beta.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 (161) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +442 -50
  4. package/dist/command-catalog.generated.js +541 -50
  5. package/dist/commands/agent-inbox.d.ts +11 -1
  6. package/dist/commands/agent-inbox.js +128 -38
  7. package/dist/commands/agent-kit.js +2 -2
  8. package/dist/commands/agents.d.ts +51 -1
  9. package/dist/commands/agents.js +154 -2
  10. package/dist/commands/bot-jobs.d.ts +2 -15
  11. package/dist/commands/bot-jobs.js +2 -94
  12. package/dist/commands/bot-runtime.d.ts +46 -5
  13. package/dist/commands/bot-runtime.js +228 -18
  14. package/dist/commands/bot.d.ts +16 -9
  15. package/dist/commands/bot.js +169 -51
  16. package/dist/commands/cloud.d.ts +66 -13
  17. package/dist/commands/cloud.js +120 -39
  18. package/dist/commands/company-restore.d.ts +23 -0
  19. package/dist/commands/company-restore.js +128 -0
  20. package/dist/commands/company.js +2 -0
  21. package/dist/commands/core-handoff.js +1 -0
  22. package/dist/commands/core-hq-session-native.js +2 -2
  23. package/dist/commands/core-pin-native.js +1 -1
  24. package/dist/commands/core-policy.js +1 -1
  25. package/dist/commands/core-resolve-company-native.js +1 -1
  26. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  27. package/dist/commands/core-sentry-report-fast.js +3 -1
  28. package/dist/commands/daemon.js +11 -1
  29. package/dist/commands/integrations-connect.d.ts +17 -4
  30. package/dist/commands/integrations-connect.js +224 -26
  31. package/dist/commands/lanes-link.js +10 -5
  32. package/dist/commands/lanes.js +26 -9
  33. package/dist/commands/rescue.js +13 -0
  34. package/dist/commands/secrets.d.ts +11 -0
  35. package/dist/commands/secrets.js +41 -7
  36. package/dist/commands/sources.js +6 -0
  37. package/dist/commands/storage-offload.d.ts +12 -0
  38. package/dist/commands/storage-offload.js +41 -3
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/index.js +2 -0
  42. package/dist/lazy-commands.js +2 -0
  43. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  44. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  45. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  46. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  47. package/dist/lib/agent-kit/inbox-state.js +261 -4
  48. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  49. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  50. package/dist/lib/agent-kit/run/inbox.js +4 -2
  51. package/dist/lib/agent-kit/skills.js +4 -1
  52. package/dist/lib/agent-kit/wake.d.ts +9 -1
  53. package/dist/lib/agent-kit/wake.js +10 -3
  54. package/dist/lib/bot/config.d.ts +1 -0
  55. package/dist/lib/bot/config.js +10 -0
  56. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  57. package/dist/lib/bot/eventbridge-cron.js +104 -0
  58. package/dist/lib/bot/fleet-cron.js +193 -14
  59. package/dist/lib/bot/fleet-download.d.ts +2 -0
  60. package/dist/lib/bot/fleet-download.js +23 -0
  61. package/dist/lib/bot/fleet-local.d.ts +34 -1
  62. package/dist/lib/bot/fleet-local.js +254 -37
  63. package/dist/lib/bot/fleet-python.d.ts +3 -0
  64. package/dist/lib/bot/fleet-python.js +34 -4
  65. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  66. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  67. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  68. package/dist/lib/bot/legacy-provider-login.js +19 -2
  69. package/dist/lib/bot/prompt.js +1 -1
  70. package/dist/lib/bot/readiness.d.ts +8 -0
  71. package/dist/lib/bot/readiness.js +17 -3
  72. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  73. package/dist/lib/bot/runtime-auth.js +94 -3
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  76. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  77. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  78. package/dist/lib/capacity/collectors/grok.js +56 -5
  79. package/dist/lib/core-utils/session-id.d.ts +1 -1
  80. package/dist/lib/core-utils/session-id.js +4 -0
  81. package/dist/lib/daemon/catalog.js +11 -1
  82. package/dist/lib/daemon/run.js +9 -1
  83. package/dist/lib/daemon/updater.d.ts +34 -2
  84. package/dist/lib/daemon/updater.js +51 -2
  85. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  86. package/dist/lib/db/sqlite-binding.js +1 -1
  87. package/dist/lib/delivery/artifacts.d.ts +99 -0
  88. package/dist/lib/delivery/artifacts.js +548 -0
  89. package/dist/lib/delivery/backup.d.ts +78 -0
  90. package/dist/lib/delivery/backup.js +343 -0
  91. package/dist/lib/delivery/cache.d.ts +29 -0
  92. package/dist/lib/delivery/cache.js +33 -0
  93. package/dist/lib/delivery/contracts.d.ts +142 -0
  94. package/dist/lib/delivery/contracts.js +289 -0
  95. package/dist/lib/delivery/credentials.d.ts +54 -0
  96. package/dist/lib/delivery/credentials.js +119 -0
  97. package/dist/lib/delivery/enrollment.d.ts +142 -0
  98. package/dist/lib/delivery/enrollment.js +382 -0
  99. package/dist/lib/delivery/identity.d.ts +25 -0
  100. package/dist/lib/delivery/identity.js +82 -0
  101. package/dist/lib/delivery/inbox.d.ts +116 -0
  102. package/dist/lib/delivery/inbox.js +260 -0
  103. package/dist/lib/delivery/migrations.d.ts +139 -0
  104. package/dist/lib/delivery/migrations.js +623 -0
  105. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  106. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  107. package/dist/lib/delivery/mqtt.d.ts +61 -0
  108. package/dist/lib/delivery/mqtt.js +112 -0
  109. package/dist/lib/delivery/outbox.d.ts +95 -0
  110. package/dist/lib/delivery/outbox.js +187 -0
  111. package/dist/lib/delivery/provenance.d.ts +129 -0
  112. package/dist/lib/delivery/provenance.js +93 -0
  113. package/dist/lib/delivery/reconciler.d.ts +151 -0
  114. package/dist/lib/delivery/reconciler.js +492 -0
  115. package/dist/lib/delivery/restore.d.ts +35 -0
  116. package/dist/lib/delivery/restore.js +134 -0
  117. package/dist/lib/delivery/store.d.ts +161 -0
  118. package/dist/lib/delivery/store.js +940 -0
  119. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  120. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  121. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  122. package/dist/lib/delivery/workers/macos.js +901 -0
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  124. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  125. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  126. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  127. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  128. package/dist/lib/delivery/workers/windows.js +608 -0
  129. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  130. package/dist/lib/doctor/checks/release-links.js +260 -24
  131. package/dist/lib/doctor/fix/apply.js +24 -8
  132. package/dist/lib/doctor/fix/remediation.js +15 -5
  133. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  134. package/dist/lib/install/provider-wrappers.js +68 -3
  135. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  136. package/dist/lib/lanes/autopilot-registry.js +59 -7
  137. package/dist/lib/lanes/links.d.ts +14 -0
  138. package/dist/lib/lanes/links.js +320 -25
  139. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  140. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  141. package/dist/main.js +3 -1
  142. package/dist/sentry-init.d.ts +2 -0
  143. package/dist/sentry-init.js +13 -2
  144. package/dist/sentry.d.ts +2 -0
  145. package/dist/sentry.js +5 -1
  146. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  147. package/dist/utils/cli-network-lifecycle.js +52 -0
  148. package/dist/utils/cognito-callback-port.d.ts +14 -0
  149. package/dist/utils/cognito-callback-port.js +24 -0
  150. package/dist/utils/cognito-session.js +3 -3
  151. package/dist/utils/deleted-company-notice.d.ts +59 -0
  152. package/dist/utils/deleted-company-notice.js +156 -0
  153. package/dist/utils/login-browser.d.ts +1 -1
  154. package/dist/utils/login-browser.js +7 -5
  155. package/dist/utils/resident-package-preload.js +30 -15
  156. package/dist/utils/safe-link.d.ts +63 -0
  157. package/dist/utils/safe-link.js +246 -0
  158. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  159. package/dist/utils/sentry-keepalive-transport.js +70 -0
  160. package/dist/utils/vault-api.js +7 -0
  161. package/package.json +7 -7
@@ -1,4 +1,5 @@
1
1
  import { type FleetLocalGatewayState } from "./fleet-local.js";
2
+ import { type BotStatusFile } from "./status.js";
2
3
  export type BotReadiness = "creating" | "installing" | "starting" | "ready" | "offline";
3
4
  export declare const BOT_READINESS_VALUES: readonly BotReadiness[];
4
5
  export type BotSetupStep = "identity" | "install" | "starting" | "ready";
@@ -22,7 +23,12 @@ export interface ReadinessFacts {
22
23
  processAlive: boolean;
23
24
  livePid?: number | null;
24
25
  gateway: Pick<FleetLocalGatewayState, "gatewayState" | "ready" | "pid"> | null;
26
+ status?: Pick<BotStatusFile, "pid" | "ready"> | null;
27
+ statusCarriesReady?: boolean;
25
28
  }
29
+ export declare const FLEET_STATUS_READY_MIN_VERSION = "0.4.30";
30
+ export declare function fleetStatusCarriesReady(engineVersion: string | null | undefined): boolean;
31
+ export declare function fleetGatewayReadyForChat(gateway: Pick<FleetLocalGatewayState, "gatewayState" | "ready" | "pid"> | null, status: Pick<BotStatusFile, "pid" | "ready"> | null | undefined, statusCarriesReady: boolean): boolean;
26
32
  export declare function deriveBotReadiness(facts: ReadinessFacts): BotReadiness;
27
33
  export interface BotReadinessReport {
28
34
  readiness: BotReadiness;
@@ -51,6 +57,8 @@ export declare function waitForGatewayReady(agentUid: string, opts: {
51
57
  now?: () => number;
52
58
  sleep?: (ms: number) => Promise<void>;
53
59
  alive?: (pid: number) => boolean;
60
+ botDir?: string;
61
+ statusCarriesReady?: boolean;
54
62
  }): Promise<ReadyWaitResult>;
55
63
  export type SetupStepStatus = "pending" | "active" | "done" | "skipped" | "timeout" | "failed";
56
64
  export interface SetupStepRecord {
@@ -1,7 +1,8 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { readFleetLocalGatewayState } from "./fleet-local.js";
4
- import { isPidAlive } from "./status.js";
4
+ import semver from "semver";
5
+ import { isPidAlive, readBotStatus } from "./status.js";
5
6
  export const BOT_READINESS_VALUES = ["creating", "installing", "starting", "ready", "offline"];
6
7
  export const BOT_SETUP_STEPS = [
7
8
  { step: "install", label: "Installing on this Mac" },
@@ -52,6 +53,18 @@ export function readBotSetupStep(dir, alive = isPidAlive) {
52
53
  return null;
53
54
  return BOT_SETUP_STEPS.some((entry) => entry.step === marker.step) ? marker.step : null;
54
55
  }
56
+ export const FLEET_STATUS_READY_MIN_VERSION = "0.4.30";
57
+ export function fleetStatusCarriesReady(engineVersion) {
58
+ const version = semver.coerce(engineVersion ?? "");
59
+ return version !== null && semver.gte(version, FLEET_STATUS_READY_MIN_VERSION);
60
+ }
61
+ export function fleetGatewayReadyForChat(gateway, status, statusCarriesReady) {
62
+ if (!gateway || gateway.gatewayState !== "running" || !gateway.ready)
63
+ return false;
64
+ if (!statusCarriesReady)
65
+ return true;
66
+ return status !== null && status !== undefined && status.pid === gateway.pid && status.ready === true;
67
+ }
55
68
  export function deriveBotReadiness(facts) {
56
69
  if (facts.setupStep === "identity")
57
70
  return "creating";
@@ -62,7 +75,7 @@ export function deriveBotReadiness(facts) {
62
75
  if (!facts.fleet)
63
76
  return "ready";
64
77
  const current = facts.livePid === undefined || facts.livePid === null || facts.gateway?.pid === facts.livePid;
65
- if (current && facts.gateway?.gatewayState === "running" && facts.gateway.ready)
78
+ if (current && fleetGatewayReadyForChat(facts.gateway, facts.status, facts.statusCarriesReady === true))
66
79
  return "ready";
67
80
  return "starting";
68
81
  }
@@ -86,7 +99,8 @@ export async function waitForGatewayReady(agentUid, opts) {
86
99
  const running = gateway !== null && gateway.pid !== null && alive(gateway.pid);
87
100
  if (running)
88
101
  seenPid = gateway.pid;
89
- if (running && gateway.gatewayState === "running" && gateway.ready) {
102
+ const status = opts.botDir ? readBotStatus(opts.botDir) : null;
103
+ if (running && fleetGatewayReadyForChat(gateway, status, opts.statusCarriesReady === true)) {
90
104
  return { ready: true, readyAt: gateway.readyAt, timedOut: false, failed: null, waitedMs: now() - started };
91
105
  }
92
106
  if (running && gateway.gatewayState === "startup_failed") {
@@ -72,6 +72,12 @@ export type SpawnInteractive = (command: string, args: string[], env: NodeJS.Pro
72
72
  };
73
73
  /** Runs the vendor's own login/logout with the terminal attached. Its output goes to the terminal only, never to HQ's log. */
74
74
  export declare const defaultSpawnInteractive: SpawnInteractive;
75
+ /**
76
+ * A browser sign-in with no terminal (the desktop app's Switch account): the
77
+ * vendor CLI opens the browser itself and exits when the sign-in completes.
78
+ * Nothing it prints is shown or logged. Bounded so an abandoned sign-in ends.
79
+ */
80
+ export declare const defaultSpawnBrowserSignIn: SpawnInteractive;
75
81
  /** Logout runs quietly: nothing it prints is shown or logged. */
76
82
  export declare const defaultSpawnQuiet: SpawnInteractive;
77
83
  /**
@@ -83,6 +89,7 @@ export declare function signInBotRuntime(dir: string, runtime: BotLoginRuntime,
83
89
  spawn?: SpawnInteractive;
84
90
  quietSpawn?: SpawnInteractive;
85
91
  env?: NodeJS.ProcessEnv;
92
+ preserveCredentialOnFailure?: boolean;
86
93
  }): {
87
94
  home: string;
88
95
  created: boolean;
@@ -98,6 +105,29 @@ export declare function signOutBotRuntime(dir: string, runtime: BotLoginRuntime,
98
105
  removed: boolean;
99
106
  vendorLogout: "ok" | "failed" | "skipped";
100
107
  };
108
+ /**
109
+ * Move an existing own login to <auth>/<runtime>.previous. The vendor logout
110
+ * does not run: on macOS the Claude credential is a keychain item keyed by
111
+ * the live path, and logging that path out would delete the login the files
112
+ * are supposed to keep. Returns false when the bot had no login for this runtime.
113
+ *
114
+ * A kill during the later browser sign-in leaves both directories. That is an
115
+ * unfinished sign-in, so the held login is put back. It is deleted only when
116
+ * a commit marker says the new sign-in finished.
117
+ */
118
+ export declare function holdPreviousBotLogin(dir: string, runtime: BotLoginRuntime, _deps?: {
119
+ spawn?: SpawnInteractive;
120
+ env?: NodeJS.ProcessEnv;
121
+ }): boolean;
122
+ /** Put a held login back. Removes whatever the failed sign-in left in the live folder. */
123
+ export declare function restoreHeldBotLogin(dir: string, runtime: BotLoginRuntime): void;
124
+ /**
125
+ * Drop a held login after the new one succeeded. The marker is written first,
126
+ * so a kill while the hold is being removed does not look like an unfinished
127
+ * sign-in and put the old login back over the new one. Does not sign the new
128
+ * login out.
129
+ */
130
+ export declare function discardHeldBotLogin(dir: string, runtime: BotLoginRuntime): void;
101
131
  /** True for the model-session files of a bot dir (owner DM, other DMs, rooms, jobs). */
102
132
  export declare function isBotSessionFile(name: string): boolean;
103
133
  export interface SessionSetAside {
@@ -134,6 +134,15 @@ export const defaultSpawnInteractive = (command, args, env) => {
134
134
  const r = spawnSync(command, args, { stdio: "inherit", env });
135
135
  return { status: r.status, ...(r.error ? { error: r.error } : {}) };
136
136
  };
137
+ /**
138
+ * A browser sign-in with no terminal (the desktop app's Switch account): the
139
+ * vendor CLI opens the browser itself and exits when the sign-in completes.
140
+ * Nothing it prints is shown or logged. Bounded so an abandoned sign-in ends.
141
+ */
142
+ export const defaultSpawnBrowserSignIn = (command, args, env) => {
143
+ const r = spawnSync(command, args, { stdio: ["ignore", "ignore", "ignore"], env, timeout: 8 * 60_000 });
144
+ return { status: r.status, ...(r.error ? { error: r.error } : {}) };
145
+ };
137
146
  /** Logout runs quietly: nothing it prints is shown or logged. */
138
147
  export const defaultSpawnQuiet = (command, args, env) => {
139
148
  const r = spawnSync(command, args, { stdio: ["ignore", "ignore", "ignore"], env, timeout: 30_000 });
@@ -176,9 +185,13 @@ export function signInBotRuntime(dir, runtime, deps = {}) {
176
185
  if (r.error || r.status !== 0) {
177
186
  // A first sign-in that failed leaves nothing behind.
178
187
  if (created) {
179
- // A keychain item keyed by this folder may already exist: sign it out first.
180
- const { command: out, args: outArgs } = VENDOR_LOGOUT[runtime];
181
- (deps.quietSpawn ?? defaultSpawnQuiet)(out, outArgs, withProviderHomeEnv(deps.env ?? process.env, runtime, home));
188
+ // A held previous login's keychain item is keyed by this same path.
189
+ // Logging it out would delete that login. Only a first sign-in, which
190
+ // had nothing to keep, signs the partial folder out.
191
+ if (!deps.preserveCredentialOnFailure) {
192
+ const { command: out, args: outArgs } = VENDOR_LOGOUT[runtime];
193
+ (deps.quietSpawn ?? defaultSpawnQuiet)(out, outArgs, withProviderHomeEnv(deps.env ?? process.env, runtime, home));
194
+ }
182
195
  fs.rmSync(home, { recursive: true, force: true });
183
196
  }
184
197
  const why = r.error?.code === "ENOENT" ? `${command} is not installed` : `${command} ${args.join(" ")} did not finish (exit ${r.status ?? "signal"})`;
@@ -204,6 +217,84 @@ export function signOutBotRuntime(dir, runtime, deps = {}) {
204
217
  fs.rmSync(home, { recursive: true, force: true });
205
218
  return { removed: true, vendorLogout: "ok" };
206
219
  }
220
+ /** Sibling of the live login folder. Never passed to the vendor logout. */
221
+ function heldBotLoginPath(dir, runtime) {
222
+ return `${botOwnAuthHome(dir, runtime)}.previous`;
223
+ }
224
+ function refuseSymlink(p) {
225
+ try {
226
+ if (fs.lstatSync(p).isSymbolicLink())
227
+ throw new Error(`refusing to touch ${p}: it is a symbolic link`);
228
+ }
229
+ catch (err) {
230
+ if (err.code !== "ENOENT" && !(err instanceof Error && err.message.startsWith("refusing to touch")))
231
+ throw err;
232
+ }
233
+ }
234
+ /** Written only after the new sign-in has stored its credential. */
235
+ function heldCommitPath(dir, runtime) {
236
+ return `${heldBotLoginPath(dir, runtime)}.committed`;
237
+ }
238
+ /**
239
+ * Move an existing own login to <auth>/<runtime>.previous. The vendor logout
240
+ * does not run: on macOS the Claude credential is a keychain item keyed by
241
+ * the live path, and logging that path out would delete the login the files
242
+ * are supposed to keep. Returns false when the bot had no login for this runtime.
243
+ *
244
+ * A kill during the later browser sign-in leaves both directories. That is an
245
+ * unfinished sign-in, so the held login is put back. It is deleted only when
246
+ * a commit marker says the new sign-in finished.
247
+ */
248
+ export function holdPreviousBotLogin(dir, runtime, _deps = {}) {
249
+ const home = botOwnAuthHome(dir, runtime);
250
+ const hold = heldBotLoginPath(dir, runtime);
251
+ const marker = heldCommitPath(dir, runtime);
252
+ assertOwnAuthHome(dir, home);
253
+ refuseSymlink(hold);
254
+ refuseSymlink(marker);
255
+ if (fs.existsSync(marker)) {
256
+ if (fs.existsSync(hold))
257
+ fs.rmSync(hold, { recursive: true, force: true });
258
+ fs.rmSync(marker, { force: true });
259
+ }
260
+ else if (fs.existsSync(hold) && fs.existsSync(home)) {
261
+ fs.rmSync(home, { recursive: true, force: true });
262
+ fs.renameSync(hold, home);
263
+ }
264
+ else if (fs.existsSync(hold)) {
265
+ fs.renameSync(hold, home);
266
+ }
267
+ if (!fs.existsSync(home))
268
+ return false;
269
+ fs.renameSync(home, hold);
270
+ return true;
271
+ }
272
+ /** Put a held login back. Removes whatever the failed sign-in left in the live folder. */
273
+ export function restoreHeldBotLogin(dir, runtime) {
274
+ const home = botOwnAuthHome(dir, runtime);
275
+ const hold = heldBotLoginPath(dir, runtime);
276
+ assertOwnAuthHome(dir, home);
277
+ refuseSymlink(hold);
278
+ if (!fs.existsSync(hold))
279
+ return;
280
+ fs.rmSync(home, { recursive: true, force: true });
281
+ fs.renameSync(hold, home);
282
+ }
283
+ /**
284
+ * Drop a held login after the new one succeeded. The marker is written first,
285
+ * so a kill while the hold is being removed does not look like an unfinished
286
+ * sign-in and put the old login back over the new one. Does not sign the new
287
+ * login out.
288
+ */
289
+ export function discardHeldBotLogin(dir, runtime) {
290
+ const hold = heldBotLoginPath(dir, runtime);
291
+ const marker = heldCommitPath(dir, runtime);
292
+ refuseSymlink(hold);
293
+ refuseSymlink(marker);
294
+ fs.writeFileSync(marker, "ok", { mode: 0o600 });
295
+ fs.rmSync(hold, { recursive: true, force: true });
296
+ fs.rmSync(marker, { force: true });
297
+ }
207
298
  /** True for the model-session files of a bot dir (owner DM, other DMs, rooms, jobs). */
208
299
  export function isBotSessionFile(name) {
209
300
  return name === "session.json" || /^session-(dm|room|job)-[A-Za-z0-9._-]+\.json$/.test(name);
@@ -9,6 +9,8 @@ export interface BotStatusFile {
9
9
  pid: number;
10
10
  state: BotState;
11
11
  runtime: BotRuntimeId;
12
+ ready?: boolean | null;
13
+ readyAt?: string | null;
12
14
  startedAt: string;
13
15
  lastActivityAt: string;
14
16
  /** Model-CLI restarts since this process started. */
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Grok access-token renewal for the capacity collector.
3
+ *
4
+ * The grok CLI signs in through xAI OIDC and stores a six-hour access token,
5
+ * a refresh token, and `expires_at` under one entry in `<home>/auth.json`.
6
+ * The CLI renews the token only while it runs. When nobody has run grok for
7
+ * six hours the billing endpoint answers 401, and the collector used to
8
+ * report that as "signed out: auth rejected" even though the stored refresh
9
+ * token still worked.
10
+ *
11
+ * This module renews an expired token with the stored refresh token and
12
+ * writes the new token back into the same entry, keeping every other field.
13
+ *
14
+ * Safety:
15
+ * - It refreshes only when the stored token is expired (or about to be).
16
+ * - It does not refresh while a `grok` process is running. A running CLI
17
+ * renews its own token, and two clients rotating one refresh token can
18
+ * revoke each other. A failed process check skips the refresh.
19
+ * - It sends the refresh token only to an https issuer on x.ai.
20
+ * - Right before writing it re-reads the file and gives up if the stored
21
+ * token changed underneath it (the CLI or a new sign-in wrote first).
22
+ * - Token values are never logged or returned in error text.
23
+ */
24
+ /** Renew this long before `expires_at` so a token does not lapse mid-collect. */
25
+ export declare const GROK_REFRESH_SKEW_MS = 60000;
26
+ export declare const GROK_REFRESH_TIMEOUT_MS = 20000;
27
+ export type GrokRefreshFetch = (url: string, init: {
28
+ method: "POST";
29
+ headers: Record<string, string>;
30
+ body: string;
31
+ redirect: "manual";
32
+ signal?: AbortSignal;
33
+ }) => Promise<{
34
+ status: number;
35
+ text: () => Promise<string>;
36
+ }>;
37
+ /** Lists running process names (basename of the executable). Throws when it cannot tell. */
38
+ export type ListGrokProcesses = () => Promise<readonly string[]>;
39
+ export interface GrokStoredSession {
40
+ /** Key of the entry inside auth.json, e.g. `https://auth.x.ai::<client id>`. */
41
+ entryKey: string;
42
+ accessToken: string;
43
+ refreshToken: string | null;
44
+ expiresAtMs: number | null;
45
+ issuer: string | null;
46
+ clientId: string | null;
47
+ }
48
+ export type GrokRefreshOutcome = {
49
+ outcome: "refreshed";
50
+ accessToken: string;
51
+ } | {
52
+ outcome: "not-needed";
53
+ } | {
54
+ outcome: "no-refresh-token";
55
+ } | {
56
+ outcome: "skipped-process";
57
+ } | {
58
+ outcome: "skipped-process-check-failed";
59
+ } | {
60
+ outcome: "skipped-race";
61
+ } | {
62
+ outcome: "revoked";
63
+ httpStatus: number;
64
+ } | {
65
+ outcome: "error";
66
+ reason: string;
67
+ };
68
+ export interface GrokRefreshContext {
69
+ authFile: string;
70
+ session: GrokStoredSession;
71
+ nowMs: number;
72
+ fetchImpl?: GrokRefreshFetch;
73
+ listProcesses?: ListGrokProcesses;
74
+ }
75
+ export declare function grokTokenExpired(session: Pick<GrokStoredSession, "expiresAtMs">, nowMs: number): boolean;
76
+ export declare function parseGrokExpiresAt(value: unknown): number | null;
77
+ /** Token endpoint for an issuer, or null when the issuer is not an https x.ai host. */
78
+ export declare function grokTokenEndpoint(issuer: string | null): string | null;
79
+ export declare function refreshGrokSession(ctx: GrokRefreshContext): Promise<GrokRefreshOutcome>;
80
+ //# sourceMappingURL=grok-refresh.d.ts.map
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Grok access-token renewal for the capacity collector.
3
+ *
4
+ * The grok CLI signs in through xAI OIDC and stores a six-hour access token,
5
+ * a refresh token, and `expires_at` under one entry in `<home>/auth.json`.
6
+ * The CLI renews the token only while it runs. When nobody has run grok for
7
+ * six hours the billing endpoint answers 401, and the collector used to
8
+ * report that as "signed out: auth rejected" even though the stored refresh
9
+ * token still worked.
10
+ *
11
+ * This module renews an expired token with the stored refresh token and
12
+ * writes the new token back into the same entry, keeping every other field.
13
+ *
14
+ * Safety:
15
+ * - It refreshes only when the stored token is expired (or about to be).
16
+ * - It does not refresh while a `grok` process is running. A running CLI
17
+ * renews its own token, and two clients rotating one refresh token can
18
+ * revoke each other. A failed process check skips the refresh.
19
+ * - It sends the refresh token only to an https issuer on x.ai.
20
+ * - Right before writing it re-reads the file and gives up if the stored
21
+ * token changed underneath it (the CLI or a new sign-in wrote first).
22
+ * - Token values are never logged or returned in error text.
23
+ */
24
+ import { execFile } from "node:child_process";
25
+ import * as fs from "node:fs";
26
+ import * as path from "node:path";
27
+ /** Renew this long before `expires_at` so a token does not lapse mid-collect. */
28
+ export const GROK_REFRESH_SKEW_MS = 60_000;
29
+ export const GROK_REFRESH_TIMEOUT_MS = 20_000;
30
+ export function grokTokenExpired(session, nowMs) {
31
+ return session.expiresAtMs !== null && session.expiresAtMs - GROK_REFRESH_SKEW_MS <= nowMs;
32
+ }
33
+ export function parseGrokExpiresAt(value) {
34
+ if (typeof value !== "string" || value.trim() === "")
35
+ return null;
36
+ // expires_at carries microseconds (2026-11-07T23:00:16.497951Z); Date.parse
37
+ // accepts up to milliseconds on every runtime, so trim the extra digits.
38
+ const trimmed = value.trim().replace(/(\.\d{3})\d+/, "$1");
39
+ const ms = Date.parse(trimmed);
40
+ return Number.isNaN(ms) ? null : ms;
41
+ }
42
+ /** Token endpoint for an issuer, or null when the issuer is not an https x.ai host. */
43
+ export function grokTokenEndpoint(issuer) {
44
+ if (!issuer)
45
+ return null;
46
+ let url;
47
+ try {
48
+ url = new URL(issuer);
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ if (url.protocol !== "https:")
54
+ return null;
55
+ if (url.hostname !== "x.ai" && !url.hostname.endsWith(".x.ai"))
56
+ return null;
57
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}/oauth2/token`;
58
+ }
59
+ export async function refreshGrokSession(ctx) {
60
+ const { session } = ctx;
61
+ if (!grokTokenExpired(session, ctx.nowMs))
62
+ return { outcome: "not-needed" };
63
+ if (!session.refreshToken || !session.clientId)
64
+ return { outcome: "no-refresh-token" };
65
+ const endpoint = grokTokenEndpoint(session.issuer);
66
+ if (!endpoint)
67
+ return { outcome: "error", reason: "grok token issuer is not an https x.ai host" };
68
+ let running;
69
+ try {
70
+ running = await (ctx.listProcesses ?? defaultListGrokProcesses)();
71
+ }
72
+ catch {
73
+ return { outcome: "skipped-process-check-failed" };
74
+ }
75
+ if (running.some((name) => name === "grok"))
76
+ return { outcome: "skipped-process" };
77
+ const fetchImpl = ctx.fetchImpl ?? defaultRefreshFetch;
78
+ let status;
79
+ let text;
80
+ try {
81
+ const response = await fetchImpl(endpoint, {
82
+ method: "POST",
83
+ headers: {
84
+ "content-type": "application/x-www-form-urlencoded",
85
+ Accept: "application/json",
86
+ },
87
+ body: new URLSearchParams({
88
+ grant_type: "refresh_token",
89
+ refresh_token: session.refreshToken,
90
+ client_id: session.clientId,
91
+ }).toString(),
92
+ redirect: "manual",
93
+ signal: AbortSignal.timeout(GROK_REFRESH_TIMEOUT_MS),
94
+ });
95
+ status = response.status;
96
+ try {
97
+ text = await response.text();
98
+ }
99
+ catch {
100
+ text = "";
101
+ }
102
+ }
103
+ catch {
104
+ return { outcome: "error", reason: "grok token refresh request failed" };
105
+ }
106
+ let body = null;
107
+ try {
108
+ const parsed = JSON.parse(text);
109
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
110
+ body = parsed;
111
+ }
112
+ catch {
113
+ body = null;
114
+ }
115
+ if ((status === 400 || status === 401) && body?.error === "invalid_grant") {
116
+ return { outcome: "revoked", httpStatus: status };
117
+ }
118
+ if (status !== 200 || !body)
119
+ return { outcome: "error", reason: `grok token refresh failed: http ${status}` };
120
+ const accessToken = typeof body.access_token === "string" ? body.access_token.trim() : "";
121
+ const expiresIn = typeof body.expires_in === "number" && Number.isFinite(body.expires_in) && body.expires_in > 0
122
+ ? body.expires_in
123
+ : null;
124
+ if (!accessToken || expiresIn === null)
125
+ return { outcome: "error", reason: "grok token refresh response is missing fields" };
126
+ const newRefresh = typeof body.refresh_token === "string" && body.refresh_token.trim()
127
+ ? body.refresh_token.trim()
128
+ : session.refreshToken;
129
+ const written = writeRefreshedSession(ctx.authFile, session, {
130
+ accessToken,
131
+ refreshToken: newRefresh,
132
+ expiresAt: new Date(ctx.nowMs + expiresIn * 1000).toISOString(),
133
+ });
134
+ if (!written)
135
+ return { outcome: "skipped-race" };
136
+ return { outcome: "refreshed", accessToken };
137
+ }
138
+ /**
139
+ * Replace the token fields of one auth.json entry. Returns false, without
140
+ * writing, when the file no longer holds the token this refresh started from.
141
+ */
142
+ function writeRefreshedSession(file, previous, next) {
143
+ let document;
144
+ let mode;
145
+ try {
146
+ mode = fs.statSync(file).mode & 0o777;
147
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
148
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
149
+ return false;
150
+ document = parsed;
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ const entry = document[previous.entryKey];
156
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
157
+ return false;
158
+ const record = entry;
159
+ if (record.key !== previous.accessToken)
160
+ return false;
161
+ document[previous.entryKey] = {
162
+ ...record,
163
+ key: next.accessToken,
164
+ refresh_token: next.refreshToken,
165
+ expires_at: next.expiresAt,
166
+ };
167
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`);
168
+ fs.writeFileSync(tmp, `${JSON.stringify(document, null, 2)}\n`, { mode: mode || 0o600 });
169
+ fs.renameSync(tmp, file);
170
+ return true;
171
+ }
172
+ async function defaultRefreshFetch(url, init) {
173
+ const response = await fetch(url, init);
174
+ return { status: response.status, text: () => response.text() };
175
+ }
176
+ function defaultListGrokProcesses() {
177
+ if (process.platform === "win32")
178
+ return Promise.reject(new Error("no process probe on windows"));
179
+ return new Promise((resolve, reject) => {
180
+ execFile("ps", ["-axo", "comm="], { timeout: 5_000, encoding: "utf8", maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
181
+ if (error) {
182
+ reject(error);
183
+ return;
184
+ }
185
+ resolve(stdout.split("\n").map((line) => path.basename(line.trim())).filter((name) => name.length > 0));
186
+ });
187
+ });
188
+ }
189
+ //# sourceMappingURL=grok-refresh.js.map
@@ -13,6 +13,7 @@
13
13
  * becomes a zero reading.
14
14
  */
15
15
  import { type LedgerOptions, type NowView, type ParserFailureEvent, type ReadingInput } from "../ledger.js";
16
+ import { type GrokRefreshFetch, type ListGrokProcesses } from "./grok-refresh.js";
16
17
  export declare const GROK_PARSER_VERSION = "grok-billing.1";
17
18
  export declare const GROK_PROVIDER = "grok";
18
19
  export declare const GROK_SOURCE: "grok-billing";
@@ -58,6 +59,10 @@ export interface CollectGrokOptions {
58
59
  }[];
59
60
  /** One-shot collect reads while the resident collector stays disabled. */
60
61
  allowDisabled?: boolean;
62
+ /** Replaces the xAI token endpoint call that renews an expired access token. */
63
+ refreshFetch?: GrokRefreshFetch;
64
+ /** Replaces the running-process probe that blocks a renewal while grok runs. */
65
+ listProcesses?: ListGrokProcesses;
61
66
  }
62
67
  interface MapOptions {
63
68
  observedAt: string;
@@ -17,7 +17,8 @@ import * as crypto from "node:crypto";
17
17
  import * as fs from "node:fs";
18
18
  import * as os from "node:os";
19
19
  import * as path from "node:path";
20
- import { DIR_MODE, FILE_MODE, appendReadings, capacityRoot, readCollectorMark, } from "../ledger.js";
20
+ import { DIR_MODE, FILE_MODE, appendReadings, capacityRoot, EXPIRED_REASON, SIGN_IN_REVOKED_REASON, readCollectorMark, } from "../ledger.js";
21
+ import { grokTokenExpired, parseGrokExpiresAt, refreshGrokSession, } from "./grok-refresh.js";
21
22
  export const GROK_PARSER_VERSION = "grok-billing.1";
22
23
  export const GROK_PROVIDER = "grok";
23
24
  export const GROK_SOURCE = "grok-billing";
@@ -221,10 +222,11 @@ export async function collectGrok(options = {}) {
221
222
  writePoll(root, accountId, new Date(nowMs).toISOString());
222
223
  const endpoint = options.endpoint ?? GROK_BILLING_URL;
223
224
  const fetchImpl = options.fetchImpl ?? defaultGrokFetch;
225
+ const renewed = await renewExpiredGrokAuth(loaded.auth, options, nowMs);
224
226
  let status;
225
227
  let text;
226
228
  try {
227
- const response = await fetchImpl(endpoint, grokBillingInit(loaded.auth, cliVersion));
229
+ const response = await fetchImpl(endpoint, grokBillingInit(renewed.auth, cliVersion));
228
230
  status = response.status;
229
231
  text = status === 200 ? await response.text() : "";
230
232
  }
@@ -259,6 +261,44 @@ export async function collectGrok(options = {}) {
259
261
  const view = appendReadings(mapped.readings, mapped.failures, null, scoped);
260
262
  return { readings: mapped.readings, failures: mapped.failures, view, accountId };
261
263
  }
264
+ /** Renew an expired access token before the billing call. Leaves a fresh token untouched. */
265
+ async function renewExpiredGrokAuth(auth, options, nowMs) {
266
+ let refresh;
267
+ try {
268
+ refresh = await refreshGrokSession({
269
+ authFile: auth.file,
270
+ session: auth.session,
271
+ nowMs,
272
+ fetchImpl: options.refreshFetch,
273
+ listProcesses: options.listProcesses,
274
+ });
275
+ }
276
+ catch {
277
+ refresh = { outcome: "error", reason: "grok token refresh failed" };
278
+ }
279
+ if (refresh.outcome !== "refreshed")
280
+ return { auth, refresh };
281
+ return {
282
+ auth: {
283
+ ...auth,
284
+ bearer: refresh.accessToken,
285
+ session: { ...auth.session, accessToken: refresh.accessToken, expiresAtMs: null },
286
+ },
287
+ refresh,
288
+ };
289
+ }
290
+ /**
291
+ * Reason for a 401/403 from the billing endpoint. A lapsed token that still has
292
+ * a refresh token is expired, not signed out: the next collect (or the next
293
+ * grok run) renews it, so the owner is not sent to sign in again.
294
+ */
295
+ function grokRejectedReason(auth, refresh, nowMs) {
296
+ if (refresh.outcome === "revoked")
297
+ return SIGN_IN_REVOKED_REASON;
298
+ if (auth.session.refreshToken && grokTokenExpired(auth.session, nowMs))
299
+ return EXPIRED_REASON;
300
+ return "signed out: auth rejected";
301
+ }
262
302
  function ledgerOptions(options) {
263
303
  return { ...(options.ledger ?? {}) };
264
304
  }
@@ -314,7 +354,7 @@ function readGrokAuth(file, root) {
314
354
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
315
355
  return { error: "grok auth file is not an object" };
316
356
  }
317
- for (const value of Object.values(parsed)) {
357
+ for (const [entryKey, value] of Object.entries(parsed)) {
318
358
  if (!value || typeof value !== "object" || Array.isArray(value))
319
359
  continue;
320
360
  const record = value;
@@ -322,11 +362,21 @@ function readGrokAuth(file, root) {
322
362
  continue;
323
363
  const accountRaw = firstAccountKey(record, `home:${path.resolve(path.dirname(file))}`);
324
364
  const userId = typeof record.user_id === "string" && record.user_id.trim() ? record.user_id.trim() : null;
365
+ const text = (field) => typeof record[field] === "string" && record[field].trim() ? record[field].trim() : null;
325
366
  return {
326
367
  auth: {
327
368
  bearer: record.key,
328
369
  accountId: hashGrokMaterial(accountRaw, root),
329
370
  userId,
371
+ file,
372
+ session: {
373
+ entryKey,
374
+ accessToken: record.key,
375
+ refreshToken: text("refresh_token"),
376
+ expiresAtMs: parseGrokExpiresAt(record.expires_at),
377
+ issuer: text("oidc_issuer"),
378
+ clientId: text("oidc_client_id"),
379
+ },
330
380
  },
331
381
  };
332
382
  }
@@ -543,10 +593,11 @@ async function collectEnumeratedGrok(options) {
543
593
  accountLabels: account.labels,
544
594
  accountHome: account.homes[0],
545
595
  };
596
+ const renewed = await renewExpiredGrokAuth(account.auth, options, nowMs);
546
597
  let status;
547
598
  let text;
548
599
  try {
549
- const response = await fetchImpl(endpoint, grokBillingInit(account.auth, cliVersion));
600
+ const response = await fetchImpl(endpoint, grokBillingInit(renewed.auth, cliVersion));
550
601
  status = response.status;
551
602
  text = status === 200 ? await response.text() : "";
552
603
  }
@@ -555,7 +606,7 @@ async function collectEnumeratedGrok(options) {
555
606
  continue;
556
607
  }
557
608
  if (status === 401 || status === 403) {
558
- failures.push(failure(mapOptions, "signed out: auth rejected"));
609
+ failures.push(failure(mapOptions, grokRejectedReason(renewed.auth, renewed.refresh, nowMs)));
559
610
  continue;
560
611
  }
561
612
  if (status !== 200) {
@@ -1,4 +1,4 @@
1
- export declare const SESSION_ID_ENV_KEYS: readonly ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID"];
1
+ export declare const SESSION_ID_ENV_KEYS: readonly ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID", "HQ_FLEET_SESSION_ID"];
2
2
  export declare function validSessionId(value: string): boolean;
3
3
  export declare function sessionIdFromEnv(env: NodeJS.ProcessEnv): string;
4
4
  /** Resolve the caller's session before using the global, last-writer-wins .current fallback. */