@indigoai-us/hq-cli 5.345.214 → 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.
- package/CHANGELOG.md +29 -0
- package/dist/command-catalog.generated.d.ts +134 -7
- package/dist/command-catalog.generated.js +168 -7
- package/dist/commands/agents.d.ts +51 -1
- package/dist/commands/agents.js +154 -2
- package/dist/commands/bot-jobs.d.ts +2 -15
- package/dist/commands/bot-jobs.js +2 -94
- package/dist/commands/bot-runtime.d.ts +46 -5
- package/dist/commands/bot-runtime.js +228 -18
- package/dist/commands/bot.d.ts +16 -9
- package/dist/commands/bot.js +169 -51
- package/dist/commands/cloud.d.ts +66 -13
- package/dist/commands/cloud.js +120 -39
- package/dist/commands/company-restore.d.ts +23 -0
- package/dist/commands/company-restore.js +128 -0
- package/dist/commands/company.js +2 -0
- package/dist/commands/integrations-connect.d.ts +10 -3
- package/dist/commands/integrations-connect.js +87 -13
- package/dist/commands/lanes.js +26 -9
- package/dist/commands/sources.js +6 -0
- package/dist/commands/storage-offload.d.ts +12 -0
- package/dist/commands/storage-offload.js +41 -3
- package/dist/commands/sync-mode.js +5 -0
- package/dist/commands/whoami.js +4 -0
- package/dist/lib/bot/config.d.ts +1 -0
- package/dist/lib/bot/config.js +10 -0
- package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
- package/dist/lib/bot/eventbridge-cron.js +104 -0
- package/dist/lib/bot/fleet-local.d.ts +33 -1
- package/dist/lib/bot/fleet-local.js +215 -31
- package/dist/lib/bot/fleet-python.d.ts +3 -0
- package/dist/lib/bot/fleet-python.js +34 -4
- package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
- package/dist/lib/bot/fleet-runtime-sources.js +30 -0
- package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
- package/dist/lib/bot/legacy-provider-login.js +19 -2
- package/dist/lib/bot/prompt.js +1 -1
- package/dist/lib/bot/readiness.d.ts +8 -0
- package/dist/lib/bot/readiness.js +17 -3
- package/dist/lib/bot/runtime-auth.d.ts +30 -0
- package/dist/lib/bot/runtime-auth.js +94 -3
- package/dist/lib/bot/status.d.ts +2 -0
- package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
- package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
- package/dist/lib/capacity/collectors/grok.d.ts +5 -0
- package/dist/lib/capacity/collectors/grok.js +56 -5
- package/dist/lib/daemon/catalog.js +11 -1
- package/dist/lib/db/sqlite-binding.d.ts +1 -0
- package/dist/lib/db/sqlite-binding.js +1 -1
- package/dist/lib/delivery/artifacts.d.ts +99 -0
- package/dist/lib/delivery/artifacts.js +548 -0
- package/dist/lib/delivery/backup.d.ts +78 -0
- package/dist/lib/delivery/backup.js +343 -0
- package/dist/lib/delivery/cache.d.ts +29 -0
- package/dist/lib/delivery/cache.js +33 -0
- package/dist/lib/delivery/contracts.d.ts +142 -0
- package/dist/lib/delivery/contracts.js +289 -0
- package/dist/lib/delivery/credentials.d.ts +54 -0
- package/dist/lib/delivery/credentials.js +119 -0
- package/dist/lib/delivery/enrollment.d.ts +142 -0
- package/dist/lib/delivery/enrollment.js +382 -0
- package/dist/lib/delivery/identity.d.ts +25 -0
- package/dist/lib/delivery/identity.js +82 -0
- package/dist/lib/delivery/inbox.d.ts +116 -0
- package/dist/lib/delivery/inbox.js +260 -0
- package/dist/lib/delivery/migrations.d.ts +139 -0
- package/dist/lib/delivery/migrations.js +623 -0
- package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
- package/dist/lib/delivery/mqtt-adapter.js +242 -0
- package/dist/lib/delivery/mqtt.d.ts +61 -0
- package/dist/lib/delivery/mqtt.js +112 -0
- package/dist/lib/delivery/outbox.d.ts +95 -0
- package/dist/lib/delivery/outbox.js +187 -0
- package/dist/lib/delivery/provenance.d.ts +129 -0
- package/dist/lib/delivery/provenance.js +93 -0
- package/dist/lib/delivery/reconciler.d.ts +151 -0
- package/dist/lib/delivery/reconciler.js +492 -0
- package/dist/lib/delivery/restore.d.ts +35 -0
- package/dist/lib/delivery/restore.js +134 -0
- package/dist/lib/delivery/store.d.ts +161 -0
- package/dist/lib/delivery/store.js +940 -0
- package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
- package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
- package/dist/lib/delivery/workers/macos.d.ts +176 -0
- package/dist/lib/delivery/workers/macos.js +901 -0
- package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
- package/dist/lib/delivery/workers/windows-boundary.js +693 -0
- package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
- package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
- package/dist/lib/delivery/workers/windows.d.ts +241 -0
- package/dist/lib/delivery/workers/windows.js +608 -0
- package/dist/lib/install/provider-wrappers.d.ts +2 -0
- package/dist/lib/install/provider-wrappers.js +68 -3
- package/dist/utils/cognito-callback-port.d.ts +14 -0
- package/dist/utils/cognito-callback-port.js +24 -0
- package/dist/utils/cognito-session.js +3 -3
- package/dist/utils/deleted-company-notice.d.ts +59 -0
- package/dist/utils/deleted-company-notice.js +156 -0
- package/dist/utils/login-browser.d.ts +1 -1
- package/dist/utils/login-browser.js +7 -5
- package/dist/utils/resident-package-preload.js +30 -15
- package/dist/utils/vault-api.js +7 -0
- package/package.json +7 -7
|
@@ -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
|
|
180
|
-
|
|
181
|
-
|
|
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);
|
package/dist/lib/bot/status.d.ts
CHANGED
|
@@ -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(
|
|
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.
|
|
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(
|
|
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,
|
|
609
|
+
failures.push(failure(mapOptions, grokRejectedReason(renewed.auth, renewed.refresh, nowMs)));
|
|
559
610
|
continue;
|
|
560
611
|
}
|
|
561
612
|
if (status !== 200) {
|
|
@@ -319,7 +319,17 @@ function planService(service, ctx) {
|
|
|
319
319
|
}
|
|
320
320
|
case "mesh": {
|
|
321
321
|
const args = ["mesh", "daemon", "run", ...(ctx.hqRoot ? ["--hq-root", ctx.hqRoot] : [])];
|
|
322
|
-
return [
|
|
322
|
+
return [
|
|
323
|
+
base(service, {
|
|
324
|
+
command: { type: "hq", args },
|
|
325
|
+
// The capacity collector inside the mesh daemon runs `hq runners ... --json` for the
|
|
326
|
+
// Claude token-refresh gate. Those commands find the HQ folder from $HQ_ROOT or the
|
|
327
|
+
// working directory, and the supervisor starts services outside HQ, so without this
|
|
328
|
+
// every gate read failed and every Claude account stayed expired.
|
|
329
|
+
env: ctx.hqRoot ? { HQ_ROOT: ctx.hqRoot } : {},
|
|
330
|
+
blocked: firstBlock([[!ctx.signedIn, NOT_SIGNED_IN]]),
|
|
331
|
+
}),
|
|
332
|
+
];
|
|
323
333
|
}
|
|
324
334
|
case "heartbeat": {
|
|
325
335
|
if (agentMachine) {
|
|
@@ -10,6 +10,7 @@ export interface LoadBetterSqlite3Options {
|
|
|
10
10
|
repair?: () => boolean;
|
|
11
11
|
}
|
|
12
12
|
export declare function resetSqliteBindingForTests(): void;
|
|
13
|
+
export declare function isNativeBindingError(error: unknown): boolean;
|
|
13
14
|
export declare function clearBetterSqlite3RequireCache(): void;
|
|
14
15
|
/**
|
|
15
16
|
* A `.js` bin runs under this Node. A `.cmd` shim goes through the escaped
|
|
@@ -29,7 +29,7 @@ export function resetSqliteBindingForTests() {
|
|
|
29
29
|
failed = undefined;
|
|
30
30
|
defaultRepairAttempted = false;
|
|
31
31
|
}
|
|
32
|
-
function isNativeBindingError(error) {
|
|
32
|
+
export function isNativeBindingError(error) {
|
|
33
33
|
const record = error;
|
|
34
34
|
const text = error instanceof Error ? `${record?.code ?? ""} ${error.message}` : String(error);
|
|
35
35
|
return /better_sqlite3\.node|could not locate the bindings file|NODE_MODULE_VERSION|was compiled against a different node|not a valid win32 application|dlopen|ERR_DLOPEN_FAILED|MODULE_NOT_FOUND/i.test(text);
|