@indigoai-us/hq-cli 5.345.214 → 5.345.215

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 (200) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  3. package/dist/command-catalog.generated.d.ts +180 -13
  4. package/dist/command-catalog.generated.js +221 -13
  5. package/dist/commands/agents.d.ts +51 -1
  6. package/dist/commands/agents.js +154 -2
  7. package/dist/commands/bot-jobs.d.ts +2 -15
  8. package/dist/commands/bot-jobs.js +2 -94
  9. package/dist/commands/bot-runtime.d.ts +46 -5
  10. package/dist/commands/bot-runtime.js +228 -18
  11. package/dist/commands/bot.d.ts +16 -9
  12. package/dist/commands/bot.js +231 -55
  13. package/dist/commands/capacity.d.ts +4 -1
  14. package/dist/commands/capacity.js +46 -10
  15. package/dist/commands/cloud.d.ts +66 -13
  16. package/dist/commands/cloud.js +121 -40
  17. package/dist/commands/company-restore.d.ts +23 -0
  18. package/dist/commands/company-restore.js +128 -0
  19. package/dist/commands/company.js +2 -0
  20. package/dist/commands/core-delegate-w1b.js +15 -1
  21. package/dist/commands/core-policy.js +67 -8
  22. package/dist/commands/daemon.js +5 -0
  23. package/dist/commands/files-browse.d.ts +11 -4
  24. package/dist/commands/files-browse.js +21 -4
  25. package/dist/commands/files.d.ts +1 -1
  26. package/dist/commands/files.js +25 -11
  27. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  28. package/dist/commands/integrations-auth-rules.js +79 -0
  29. package/dist/commands/integrations-connect.d.ts +10 -3
  30. package/dist/commands/integrations-connect.js +87 -13
  31. package/dist/commands/integrations-import.js +124 -12
  32. package/dist/commands/lanes.js +28 -11
  33. package/dist/commands/mesh.d.ts +2 -0
  34. package/dist/commands/mesh.js +60 -35
  35. package/dist/commands/sources.js +6 -0
  36. package/dist/commands/storage-offload.d.ts +12 -0
  37. package/dist/commands/storage-offload.js +41 -3
  38. package/dist/commands/sync-held.js +5 -2
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/lazy-commands.js +3 -5
  42. package/dist/lib/bot/config.d.ts +1 -0
  43. package/dist/lib/bot/config.js +10 -0
  44. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  45. package/dist/lib/bot/eventbridge-cron.js +104 -0
  46. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  47. package/dist/lib/bot/fleet-cron.js +35 -3
  48. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  49. package/dist/lib/bot/fleet-daemon.js +99 -1
  50. package/dist/lib/bot/fleet-local.d.ts +33 -1
  51. package/dist/lib/bot/fleet-local.js +215 -31
  52. package/dist/lib/bot/fleet-python.d.ts +3 -0
  53. package/dist/lib/bot/fleet-python.js +34 -4
  54. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  55. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  56. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  57. package/dist/lib/bot/legacy-provider-login.js +19 -2
  58. package/dist/lib/bot/probe.js +7 -1
  59. package/dist/lib/bot/prompt.js +1 -1
  60. package/dist/lib/bot/readiness.d.ts +8 -0
  61. package/dist/lib/bot/readiness.js +17 -3
  62. package/dist/lib/bot/run.js +20 -1
  63. package/dist/lib/bot/runtime/codex.js +1 -1
  64. package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
  65. package/dist/lib/bot/runtime/grok-acp.js +6 -3
  66. package/dist/lib/bot/runtime/index.js +19 -9
  67. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  68. package/dist/lib/bot/runtime/types.d.ts +15 -0
  69. package/dist/lib/bot/runtime/types.js +9 -0
  70. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  71. package/dist/lib/bot/runtime-auth.js +94 -3
  72. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  73. package/dist/lib/bot/runtime-failure.js +43 -1
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/accounts.d.ts +8 -0
  76. package/dist/lib/capacity/accounts.js +19 -0
  77. package/dist/lib/capacity/available.d.ts +154 -0
  78. package/dist/lib/capacity/available.js +905 -0
  79. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  80. package/dist/lib/capacity/codex-availability.js +26 -1
  81. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  82. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  83. package/dist/lib/capacity/collectors/codex.js +10 -7
  84. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  85. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  86. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  87. package/dist/lib/capacity/collectors/grok.js +56 -5
  88. package/dist/lib/capacity/ledger.d.ts +37 -1
  89. package/dist/lib/capacity/ledger.js +207 -30
  90. package/dist/lib/capacity/project.d.ts +26 -0
  91. package/dist/lib/capacity/project.js +137 -8
  92. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  93. package/dist/lib/capacity/refusal-rows.js +61 -0
  94. package/dist/lib/capacity/refusal.d.ts +53 -2
  95. package/dist/lib/capacity/refusal.js +284 -65
  96. package/dist/lib/capacity/route.js +46 -11
  97. package/dist/lib/capacity/widget.d.ts +12 -1
  98. package/dist/lib/capacity/widget.js +91 -3
  99. package/dist/lib/daemon/catalog.js +11 -1
  100. package/dist/lib/daemon/resolver.d.ts +2 -0
  101. package/dist/lib/daemon/resolver.js +3 -0
  102. package/dist/lib/daemon/run.d.ts +9 -0
  103. package/dist/lib/daemon/run.js +54 -1
  104. package/dist/lib/daemon/server.d.ts +2 -0
  105. package/dist/lib/daemon/server.js +10 -1
  106. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  107. package/dist/lib/daemon/tcc-eperm.js +310 -0
  108. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  109. package/dist/lib/db/sqlite-binding.js +1 -1
  110. package/dist/lib/delivery/admission.d.ts +86 -0
  111. package/dist/lib/delivery/admission.js +148 -0
  112. package/dist/lib/delivery/artifacts.d.ts +105 -0
  113. package/dist/lib/delivery/artifacts.js +567 -0
  114. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  115. package/dist/lib/delivery/attempt-id.js +16 -0
  116. package/dist/lib/delivery/backup.d.ts +78 -0
  117. package/dist/lib/delivery/backup.js +343 -0
  118. package/dist/lib/delivery/cache.d.ts +29 -0
  119. package/dist/lib/delivery/cache.js +33 -0
  120. package/dist/lib/delivery/contracts.d.ts +142 -0
  121. package/dist/lib/delivery/contracts.js +289 -0
  122. package/dist/lib/delivery/credentials.d.ts +54 -0
  123. package/dist/lib/delivery/credentials.js +119 -0
  124. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  125. package/dist/lib/delivery/disposable-target.js +111 -0
  126. package/dist/lib/delivery/effects.d.ts +136 -0
  127. package/dist/lib/delivery/effects.js +541 -0
  128. package/dist/lib/delivery/enrollment.d.ts +146 -0
  129. package/dist/lib/delivery/enrollment.js +460 -0
  130. package/dist/lib/delivery/escalations.d.ts +51 -0
  131. package/dist/lib/delivery/escalations.js +60 -0
  132. package/dist/lib/delivery/identity.d.ts +25 -0
  133. package/dist/lib/delivery/identity.js +82 -0
  134. package/dist/lib/delivery/inbox.d.ts +116 -0
  135. package/dist/lib/delivery/inbox.js +260 -0
  136. package/dist/lib/delivery/lease.d.ts +80 -0
  137. package/dist/lib/delivery/lease.js +134 -0
  138. package/dist/lib/delivery/migrations.d.ts +255 -0
  139. package/dist/lib/delivery/migrations.js +823 -0
  140. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  141. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  142. package/dist/lib/delivery/mqtt.d.ts +63 -0
  143. package/dist/lib/delivery/mqtt.js +119 -0
  144. package/dist/lib/delivery/outbox.d.ts +95 -0
  145. package/dist/lib/delivery/outbox.js +187 -0
  146. package/dist/lib/delivery/provenance.d.ts +129 -0
  147. package/dist/lib/delivery/provenance.js +93 -0
  148. package/dist/lib/delivery/reconciler.d.ts +215 -0
  149. package/dist/lib/delivery/reconciler.js +703 -0
  150. package/dist/lib/delivery/restore.d.ts +35 -0
  151. package/dist/lib/delivery/restore.js +134 -0
  152. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  153. package/dist/lib/delivery/rpc/client.js +159 -0
  154. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  155. package/dist/lib/delivery/rpc/port.js +16 -0
  156. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  157. package/dist/lib/delivery/rpc/server.js +205 -0
  158. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  159. package/dist/lib/delivery/rpc/wire.js +143 -0
  160. package/dist/lib/delivery/store.d.ts +163 -0
  161. package/dist/lib/delivery/store.js +944 -0
  162. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  163. package/dist/lib/delivery/windows-service-install.js +892 -0
  164. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  165. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  166. package/dist/lib/delivery/workers/macos.d.ts +191 -0
  167. package/dist/lib/delivery/workers/macos.js +943 -0
  168. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  169. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  170. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  171. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  172. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  173. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  174. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  175. package/dist/lib/delivery/workers/windows-service.js +584 -0
  176. package/dist/lib/delivery/workers/windows.d.ts +251 -0
  177. package/dist/lib/delivery/workers/windows.js +594 -0
  178. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  179. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  180. package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
  181. package/dist/lib/hot-channels/signals-pass.js +71 -2
  182. package/dist/lib/hot-channels/signals-redo.js +10 -2
  183. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  184. package/dist/lib/install/provider-wrappers.js +68 -3
  185. package/dist/lib/lanes/watcher.js +35 -0
  186. package/dist/lib/signals/steps/extract.js +40 -4
  187. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  188. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  189. package/dist/utils/catalog-runtime-paths.js +53 -0
  190. package/dist/utils/cognito-callback-port.d.ts +14 -0
  191. package/dist/utils/cognito-callback-port.js +24 -0
  192. package/dist/utils/cognito-session.js +3 -3
  193. package/dist/utils/deleted-company-notice.d.ts +59 -0
  194. package/dist/utils/deleted-company-notice.js +156 -0
  195. package/dist/utils/files-browse-acl.js +1 -1
  196. package/dist/utils/login-browser.d.ts +1 -1
  197. package/dist/utils/login-browser.js +7 -5
  198. package/dist/utils/resident-package-preload.js +30 -15
  199. package/dist/utils/vault-api.js +7 -0
  200. package/package.json +7 -7
@@ -1,5 +1,18 @@
1
1
  import type { NowLimit } from "./ledger.js";
2
- /** A newer snapshot supersedes omitted windows within the same account. */
2
+ /**
3
+ * The raw account string for a Codex home, before hashing. win32 paths are
4
+ * case-insensitive, so the same home reached with different casing folds to one
5
+ * id; on other platforms the resolved path is used as-is. Every id built from a
6
+ * home must go through here so both Codex collectors agree on the account.
7
+ */
8
+ export declare function codexHomeAccountRaw(home: string): string;
9
+ /** The one account id for a Codex home. Same value the collectors hash for that home. */
10
+ export declare function canonicalCodexAccountId(home: string): string;
11
+ /**
12
+ * A newer snapshot supersedes omitted windows within the same account. The
13
+ * rebuild has already moved every reading of a home to its canonical id, so
14
+ * this compares one login's readings across both Codex collectors.
15
+ */
3
16
  export declare function codexSnapshotStale(limit: NowLimit, limits: readonly NowLimit[]): boolean;
4
17
  /** Credits can keep Codex serving after a plan window runs out. */
5
18
  export declare function hasCodexCreditRoom(limits: readonly NowLimit[], nowMs: number): boolean;
@@ -1,6 +1,31 @@
1
+ import * as crypto from "node:crypto";
2
+ import * as path from "node:path";
3
+ import { isRefusalHold } from "./refusal-rows.js";
1
4
  const MAX_CREDIT_AGE_MS = 24 * 36e5;
2
- /** A newer snapshot supersedes omitted windows within the same account. */
5
+ /**
6
+ * The raw account string for a Codex home, before hashing. win32 paths are
7
+ * case-insensitive, so the same home reached with different casing folds to one
8
+ * id; on other platforms the resolved path is used as-is. Every id built from a
9
+ * home must go through here so both Codex collectors agree on the account.
10
+ */
11
+ export function codexHomeAccountRaw(home) {
12
+ const resolved = path.resolve(home);
13
+ return `home:${process.platform === "win32" ? resolved.toLowerCase() : resolved}`;
14
+ }
15
+ /** The one account id for a Codex home. Same value the collectors hash for that home. */
16
+ export function canonicalCodexAccountId(home) {
17
+ const digest = crypto.createHash("sha256").update(codexHomeAccountRaw(home), "utf8").digest("hex").slice(0, 16);
18
+ return `acct_${digest}`;
19
+ }
20
+ /**
21
+ * A newer snapshot supersedes omitted windows within the same account. The
22
+ * rebuild has already moved every reading of a home to its canonical id, so
23
+ * this compares one login's readings across both Codex collectors.
24
+ */
3
25
  export function codexSnapshotStale(limit, limits) {
26
+ // A refusal hold has its own end: holdsInForce and its reset.
27
+ if (isRefusalHold(limit))
28
+ return false;
4
29
  if (limit.source !== "codex-jsonl" && limit.source !== "codex-app-server" && limit.source !== "refusal")
5
30
  return false;
6
31
  const at = Date.parse(limit.observedAt);
@@ -29,11 +29,17 @@
29
29
  * observedAt is the response time. One collect appends every account's
30
30
  * readings and failures in one rebuild.
31
31
  */
32
- import { type LedgerOptions, type NowView, type ParserFailureEvent, type ReadingInput } from "../ledger.js";
32
+ import { type LedgerOptions, type RateLimitResetCredits, type NowView, type ParserFailureEvent, type ReadingInput } from "../ledger.js";
33
33
  export declare const CLAUDE_OAUTH_PARSER_VERSION = "claude-oauth-usage.1";
34
34
  export declare const CLAUDE_OAUTH_PROVIDER = "claude";
35
35
  export declare const CLAUDE_OAUTH_SOURCE: "oauth-usage";
36
- export declare const CLAUDE_OAUTH_URL = "https://api.anthropic.com/api/oauth/usage";
36
+ /**
37
+ * `cedar_ember=1` adds the account's banked limit resets (a `cedar_ember` block with
38
+ * `grants[]`) to the usual usage body. Claude Code reads the same block to offer a
39
+ * reset at the limit wall. Without it an account that is at 100% but holds a reset
40
+ * looks used up for the week.
41
+ */
42
+ export declare const CLAUDE_OAUTH_URL = "https://api.anthropic.com/api/oauth/usage?cedar_ember=1";
37
43
  export declare const CLAUDE_OAUTH_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
38
44
  export declare const CLAUDE_OAUTH_BETA = "oauth-2025-04-20";
39
45
  export declare const CLAUDE_ORG_CACHE_MS: number;
@@ -251,6 +257,20 @@ export declare function parseClaudeCliVersion(text: string): string | null;
251
257
  export declare function mapClaudeOAuthUsage(body: unknown, options: MapOptions): {
252
258
  readings: ReadingInput[];
253
259
  failures: ParserFailureEvent[];
260
+ /** Undefined when the body has no reset block (older server or flag off): leave the last count alone. */
261
+ resetCredits?: RateLimitResetCredits | null;
262
+ };
263
+ /**
264
+ * Map the `cedar_ember` block to banked reset credits. `null` means the server
265
+ * answered with no reset block for this account. One credit row per grant;
266
+ * `remaining` carries how many resets that grant still holds, and
267
+ * `availableCount` sums them. A grant can be scoped: `clears` names the limits it
268
+ * resets (a Fable-only grant clears only that model's weekly limit).
269
+ */
270
+ export declare function mapClaudeResetGrants(value: unknown): {
271
+ value: RateLimitResetCredits | null;
272
+ } | {
273
+ error: string;
254
274
  };
255
275
  export declare function collectClaudeOAuth(inputOptions?: CollectClaudeOAuthOptions): Promise<ClaudeOAuthCollectResult>;
256
276
  /**
@@ -266,6 +286,13 @@ export declare function claudeIdentityKeys(root: string): ReadonlyMap<string, st
266
286
  */
267
287
  export declare function displayOrganization(name: string): string | null;
268
288
  export declare function claudeSeatAccountId(seat: string, orgId: string | null): string;
289
+ /**
290
+ * The usage endpoint fills the `cedar_ember` reset block only for a Claude Code
291
+ * client: any other user agent gets `eligible: false, ineligible_reason: "surface"`
292
+ * and no grants. The token is a Claude Code sign-in, so name the installed CLI
293
+ * version the way Claude Code does.
294
+ */
295
+ export declare function claudeUsageUserAgent(cliVersion: string | undefined): string;
269
296
  export declare function readInstalledClaudeVersion(readVersion?: () => string): string;
270
297
  /** Async `claude --version` for the daemon. The sync reader stays for one-shot callers. */
271
298
  export declare function readInstalledClaudeVersionAsync(): Promise<string>;
@@ -40,7 +40,13 @@ import { REMOTE_LANE_READ_ENV } from "../../lanes/outpost-dispatch.js";
40
40
  export const CLAUDE_OAUTH_PARSER_VERSION = "claude-oauth-usage.1";
41
41
  export const CLAUDE_OAUTH_PROVIDER = "claude";
42
42
  export const CLAUDE_OAUTH_SOURCE = "oauth-usage";
43
- export const CLAUDE_OAUTH_URL = "https://api.anthropic.com/api/oauth/usage";
43
+ /**
44
+ * `cedar_ember=1` adds the account's banked limit resets (a `cedar_ember` block with
45
+ * `grants[]`) to the usual usage body. Claude Code reads the same block to offer a
46
+ * reset at the limit wall. Without it an account that is at 100% but holds a reset
47
+ * looks used up for the week.
48
+ */
49
+ export const CLAUDE_OAUTH_URL = "https://api.anthropic.com/api/oauth/usage?cedar_ember=1";
44
50
  export const CLAUDE_OAUTH_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
45
51
  export const CLAUDE_OAUTH_BETA = "oauth-2025-04-20";
46
52
  export const CLAUDE_ORG_CACHE_MS = 24 * 60 * 60 * 1000;
@@ -135,7 +141,81 @@ export function mapClaudeOAuthUsage(body, options) {
135
141
  else
136
142
  readings.push(spend.reading);
137
143
  }
138
- return { readings, failures };
144
+ if (!("cedar_ember" in root))
145
+ return { readings, failures };
146
+ const resets = mapClaudeResetGrants(root.cedar_ember);
147
+ if ("error" in resets) {
148
+ failures.push(failure(options, resets.error));
149
+ return { readings, failures };
150
+ }
151
+ return { readings, failures, resetCredits: resets.value };
152
+ }
153
+ const CLAUDE_RESET_DRIFT = "claude oauth usage field drift: cedar_ember";
154
+ /**
155
+ * Map the `cedar_ember` block to banked reset credits. `null` means the server
156
+ * answered with no reset block for this account. One credit row per grant;
157
+ * `remaining` carries how many resets that grant still holds, and
158
+ * `availableCount` sums them. A grant can be scoped: `clears` names the limits it
159
+ * resets (a Fable-only grant clears only that model's weekly limit).
160
+ */
161
+ export function mapClaudeResetGrants(value) {
162
+ if (value === null)
163
+ return { value: null };
164
+ if (!value || typeof value !== "object" || Array.isArray(value))
165
+ return { error: CLAUDE_RESET_DRIFT };
166
+ const block = value;
167
+ if (block.grants === undefined || block.grants === null)
168
+ return { value: { availableCount: 0, credits: [] } };
169
+ if (!Array.isArray(block.grants))
170
+ return { error: CLAUDE_RESET_DRIFT };
171
+ const credits = [];
172
+ let available = 0;
173
+ for (const raw of block.grants) {
174
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
175
+ return { error: CLAUDE_RESET_DRIFT };
176
+ const grant = raw;
177
+ if (typeof grant.id !== "string" || !grant.id.trim())
178
+ return { error: CLAUDE_RESET_DRIFT };
179
+ const left = grant.resets_left;
180
+ if (typeof left !== "number" || !Number.isInteger(left) || left < 0)
181
+ return { error: CLAUDE_RESET_DRIFT };
182
+ const paused = grant.paused === true;
183
+ const reason = typeof grant.unavailable_reason === "string" && grant.unavailable_reason ? grant.unavailable_reason : null;
184
+ const clears = Array.isArray(grant.clears) ? grant.clears.filter((id) => typeof id === "string") : [];
185
+ available += left;
186
+ credits.push({
187
+ id: grant.id,
188
+ resetType: typeof grant.type === "string" ? grant.type : null,
189
+ status: paused ? "paused" : reason ?? (left > 0 ? "available" : "used"),
190
+ grantedAt: isoToMs(grant.starts_at),
191
+ expiresAt: isoToMs(grant.ends_at),
192
+ title: typeof grant.label === "string" && grant.label.trim() ? grant.label.trim() : null,
193
+ description: null,
194
+ remaining: left,
195
+ usableNow: typeof grant.usable_now === "boolean" ? grant.usable_now : null,
196
+ clears,
197
+ });
198
+ }
199
+ return { value: { availableCount: available, credits } };
200
+ }
201
+ function isoToMs(value) {
202
+ if (typeof value !== "string" || !value.trim())
203
+ return null;
204
+ const ms = Date.parse(value);
205
+ return Number.isNaN(ms) ? null : ms;
206
+ }
207
+ function resetMeta(context, credits) {
208
+ const event = {
209
+ event: "provider_meta",
210
+ observedAt: context.observedAt,
211
+ provider: CLAUDE_OAUTH_PROVIDER,
212
+ source: "oauth-usage",
213
+ ordinaryUsageAllowed: null,
214
+ rateLimitResetCredits: credits,
215
+ accountId: context.accountId,
216
+ cliVersion: context.cliVersion,
217
+ };
218
+ return event;
139
219
  }
140
220
  export async function collectClaudeOAuth(inputOptions = {}) {
141
221
  const options = {
@@ -206,6 +286,7 @@ export async function collectClaudeOAuth(inputOptions = {}) {
206
286
  const endpoint = options.endpoint ?? CLAUDE_OAUTH_URL;
207
287
  const fetchImpl = options.fetchImpl ?? defaultClaudeFetch;
208
288
  const readings = [];
289
+ const metas = [];
209
290
  const failures = [...loaded.failures];
210
291
  const accountIds = [];
211
292
  let httpStatus = null;
@@ -279,7 +360,7 @@ export async function collectClaudeOAuth(inputOptions = {}) {
279
360
  let text;
280
361
  let retryAfter;
281
362
  try {
282
- const response = await fetchImpl(endpoint, usageInit(currentToken));
363
+ const response = await fetchImpl(endpoint, usageInit(currentToken, cliVersion));
283
364
  status = response.status;
284
365
  retryAfter = response.headers?.get("retry-after") ?? null;
285
366
  text = status === 200 ? await response.text() : "";
@@ -318,6 +399,8 @@ export async function collectClaudeOAuth(inputOptions = {}) {
318
399
  const mapped = mapClaudeOAuthUsage(parsed, mapContext);
319
400
  readings.push(...mapped.readings);
320
401
  failures.push(...mapped.failures);
402
+ if (mapped.resetCredits !== undefined)
403
+ metas.push(resetMeta(mapContext, mapped.resetCredits));
321
404
  }
322
405
  if (!fetched && failures.length === 0) {
323
406
  return empty({
@@ -336,7 +419,7 @@ export async function collectClaudeOAuth(inputOptions = {}) {
336
419
  accountIds,
337
420
  };
338
421
  }
339
- const view = appendReadings(readings, failures, null, scoped);
422
+ const view = appendReadings(readings, failures, metas, scoped);
340
423
  return { readings, failures, view, keychain: loaded.keychain, httpStatus, accountIds };
341
424
  }
342
425
  async function collectEnumeratedClaude(options, scoped, root, clock, cliVersion) {
@@ -360,6 +443,7 @@ async function collectEnumeratedClaude(options, scoped, root, clock, cliVersion)
360
443
  const endpoint = options.endpoint ?? CLAUDE_OAUTH_URL;
361
444
  const fetchImpl = options.fetchImpl ?? defaultClaudeFetch;
362
445
  const readings = [];
446
+ const metas = [];
363
447
  const failures = [];
364
448
  const accountIds = [];
365
449
  let httpStatus = null;
@@ -455,7 +539,7 @@ async function collectEnumeratedClaude(options, scoped, root, clock, cliVersion)
455
539
  let text;
456
540
  let retryAfter;
457
541
  try {
458
- const response = await fetchImpl(endpoint, usageInit(token));
542
+ const response = await fetchImpl(endpoint, usageInit(token, cliVersion));
459
543
  status = response.status;
460
544
  retryAfter = response.headers?.get("retry-after") ?? null;
461
545
  text = status === 200 ? await response.text() : "";
@@ -494,6 +578,8 @@ async function collectEnumeratedClaude(options, scoped, root, clock, cliVersion)
494
578
  const mapped = mapClaudeOAuthUsage(parsed, mapContext);
495
579
  readings.push(...mapped.readings);
496
580
  failures.push(...mapped.failures);
581
+ if (mapped.resetCredits !== undefined)
582
+ metas.push(resetMeta(mapContext, mapped.resetCredits));
497
583
  }
498
584
  if (!fetched && failures.length === 0) {
499
585
  return {
@@ -509,7 +595,7 @@ async function collectEnumeratedClaude(options, scoped, root, clock, cliVersion)
509
595
  if (readings.length === 0 && failures.length === 0) {
510
596
  return { readings, failures, view: null, keychain, httpStatus, accountIds };
511
597
  }
512
- const view = appendReadings(readings, failures, null, scoped);
598
+ const view = appendReadings(readings, failures, metas, scoped);
513
599
  return { readings, failures, view, keychain, httpStatus, accountIds };
514
600
  }
515
601
  function groupHomes(accounts) {
@@ -1066,10 +1152,21 @@ function classifySecurity(result) {
1066
1152
  return "error";
1067
1153
  return "no-prompt";
1068
1154
  }
1069
- function usageInit(token) {
1155
+ /**
1156
+ * The usage endpoint fills the `cedar_ember` reset block only for a Claude Code
1157
+ * client: any other user agent gets `eligible: false, ineligible_reason: "surface"`
1158
+ * and no grants. The token is a Claude Code sign-in, so name the installed CLI
1159
+ * version the way Claude Code does.
1160
+ */
1161
+ export function claudeUsageUserAgent(cliVersion) {
1162
+ const version = cliVersion && /^[0-9][0-9A-Za-z.+-]*$/.test(cliVersion) ? cliVersion : "unknown";
1163
+ return `claude-cli/${version} (external, cli)`;
1164
+ }
1165
+ function usageInit(token, cliVersion) {
1070
1166
  return {
1071
1167
  method: "GET",
1072
1168
  headers: {
1169
+ "User-Agent": claudeUsageUserAgent(cliVersion),
1073
1170
  Authorization: `Bearer ${token}`,
1074
1171
  "anthropic-beta": CLAUDE_OAUTH_BETA,
1075
1172
  Accept: "application/json",
@@ -15,6 +15,7 @@ import { spawn } from "node:child_process";
15
15
  import * as fs from "node:fs";
16
16
  import * as path from "node:path";
17
17
  import { appendReadings, BURN_WINDOW_MS, redactProviderTokens, } from "../ledger.js";
18
+ import { codexHomeAccountRaw } from "../codex-availability.js";
18
19
  export const CODEX_PARSER_VERSION = "codex.1";
19
20
  export const CODEX_IDLE_MS = 30 * 60 * 1000;
20
21
  export const CODEX_APP_SERVER_TIMEOUT_MS = 20_000;
@@ -123,7 +124,7 @@ export function tailCodexSessions(options) {
123
124
  const latest = new Map();
124
125
  const emittedAt = new Map();
125
126
  let bestEventMs = Number.NEGATIVE_INFINITY;
126
- const accountId = hashAccountId(options.accountId ?? (options.accountHome ? `home:${path.resolve(options.accountHome)}` : LOCAL_ACCOUNT));
127
+ const accountId = hashAccountId(options.accountId ?? (options.accountHome ? codexHomeAccountRaw(options.accountHome) : LOCAL_ACCOUNT));
127
128
  const consider = (parsed, emit) => {
128
129
  if (emit) {
129
130
  readings.push(...parsed.readings);
@@ -208,6 +209,7 @@ export function tailCodexSessions(options) {
208
209
  export function mapCodexAppServerBody(body, options) {
209
210
  const now = options.now ?? new Date();
210
211
  const observedAt = now.toISOString();
212
+ const homeAccount = options.accountId ?? (options.accountHome ? codexHomeAccountRaw(options.accountHome) : null);
211
213
  if (!body || typeof body !== "object" || Array.isArray(body)) {
212
214
  return {
213
215
  readings: [],
@@ -215,16 +217,17 @@ export function mapCodexAppServerBody(body, options) {
215
217
  observedAt,
216
218
  source: "codex-app-server",
217
219
  cliVersion: options.cliVersion,
218
- accountId: hashAccountId(options.accountId ?? LOCAL_ACCOUNT),
220
+ accountId: hashAccountId(homeAccount ?? LOCAL_ACCOUNT),
219
221
  error: "codex app-server rate limit payload drifted",
220
222
  })],
221
223
  providerMeta: null,
222
224
  };
223
225
  }
224
226
  const record = body;
225
- const rawAccount = typeof record.accountId === "string" && record.accountId.trim()
226
- ? record.accountId
227
- : options.accountId ?? (options.accountHome ? `home:${path.resolve(options.accountHome)}` : LOCAL_ACCOUNT);
227
+ // One home is one account id on every Codex path. The provider's own id is
228
+ // used only when no home is known, as on the JSONL path.
229
+ const rawAccount = homeAccount
230
+ ?? (typeof record.accountId === "string" && record.accountId.trim() ? record.accountId : LOCAL_ACCOUNT);
228
231
  const accountId = hashAccountId(rawAccount);
229
232
  const mapped = mapRateLimitCarrier(record, {
230
233
  source: "codex-app-server",
@@ -271,7 +274,7 @@ export function mapCodexAppServerBody(body, options) {
271
274
  }
272
275
  export async function readCodexAppServer(options) {
273
276
  const timeoutMs = options.timeoutMs ?? CODEX_APP_SERVER_TIMEOUT_MS;
274
- const accountId = options.accountId ?? (options.home ? `home:${path.resolve(options.home)}` : undefined);
277
+ const accountId = options.accountId ?? (options.home ? codexHomeAccountRaw(options.home) : undefined);
275
278
  const spawnImpl = options.spawn ?? defaultCodexSpawn;
276
279
  const command = options.command ?? "codex";
277
280
  let child = null;
@@ -320,7 +323,7 @@ export function ingestCodexResult(result, options) {
320
323
  return appendReadings(result.readings, result.failures, meta, options);
321
324
  }
322
325
  function transportFailure(reason, options) {
323
- const raw = options?.accountId ?? (options?.home ? `home:${path.resolve(options.home)}` : undefined);
326
+ const raw = options?.accountId ?? (options?.home ? codexHomeAccountRaw(options.home) : undefined);
324
327
  const failures = [];
325
328
  if (raw && options?.cliVersion) {
326
329
  failures.push(failureEvent({
@@ -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;