@indigoai-us/hq-cli 5.345.215-beta.0 → 5.345.217
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 +206 -1
- package/README.md +45 -0
- package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
- package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
- package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
- package/dist/command-catalog.generated.d.ts +105 -10
- package/dist/command-catalog.generated.js +127 -10
- package/dist/command-help.js +3 -1
- package/dist/command-registration-plan.d.ts +6 -0
- package/dist/command-registration-plan.js +1 -0
- package/dist/commands/auth.d.ts +1 -1
- package/dist/commands/auth.js +11 -52
- package/dist/commands/bot.js +75 -10
- package/dist/commands/capacity.d.ts +4 -1
- package/dist/commands/capacity.js +46 -10
- package/dist/commands/cloud-demote.d.ts +19 -4
- package/dist/commands/cloud-demote.js +85 -12
- package/dist/commands/cloud-provision.d.ts +5 -1
- package/dist/commands/cloud-provision.js +6 -2
- package/dist/commands/cloud.d.ts +36 -0
- package/dist/commands/cloud.js +110 -27
- package/dist/commands/core-delegate-w1b.js +15 -1
- package/dist/commands/core-policy.js +67 -8
- package/dist/commands/core.js +1 -0
- package/dist/commands/daemon.js +9 -1
- package/dist/commands/dm.js +7 -0
- package/dist/commands/doctor-usage.d.ts +8 -0
- package/dist/commands/doctor-usage.js +20 -0
- package/dist/commands/doctor.js +7 -1
- package/dist/commands/env.d.ts +18 -0
- package/dist/commands/env.js +82 -0
- package/dist/commands/files-browse.d.ts +11 -4
- package/dist/commands/files-browse.js +21 -4
- package/dist/commands/files.d.ts +1 -1
- package/dist/commands/files.js +25 -11
- package/dist/commands/install-global.js +2 -2
- package/dist/commands/integrations-auth-rules.d.ts +27 -0
- package/dist/commands/integrations-auth-rules.js +79 -0
- package/dist/commands/integrations-import.js +124 -12
- package/dist/commands/lanes.js +102 -26
- package/dist/commands/logout.d.ts +7 -0
- package/dist/commands/logout.js +41 -34
- package/dist/commands/mesh.d.ts +2 -0
- package/dist/commands/mesh.js +60 -35
- package/dist/commands/sources.d.ts +8 -2
- package/dist/commands/sources.js +65 -9
- package/dist/commands/sync-held.js +5 -2
- package/dist/commands/whoami.js +26 -1
- package/dist/data/command-states.json +15 -0
- package/dist/index.js +52 -4
- package/dist/lazy-commands.js +5 -6
- package/dist/lib/anywhere-person-setting.d.ts +2 -0
- package/dist/lib/anywhere-person-setting.js +6 -3
- package/dist/lib/billing/usage-card.d.ts +25 -4
- package/dist/lib/billing/usage-card.js +76 -9
- package/dist/lib/billing/usage-cost.d.ts +3 -3
- package/dist/lib/billing/usage-cost.js +35 -13
- package/dist/lib/billing/usage-only.js +4 -2
- package/dist/lib/billing/usage-rate-card.d.ts +2 -2
- package/dist/lib/billing/usage-rate-card.js +3 -0
- package/dist/lib/bot/fleet-cron.d.ts +8 -0
- package/dist/lib/bot/fleet-cron.js +126 -7
- package/dist/lib/bot/fleet-daemon.d.ts +46 -0
- package/dist/lib/bot/fleet-daemon.js +99 -1
- package/dist/lib/bot/inflight.d.ts +9 -0
- package/dist/lib/bot/inflight.js +10 -0
- package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
- package/dist/lib/bot/probe.js +7 -1
- package/dist/lib/bot/run.js +20 -1
- package/dist/lib/bot/runtime/codex.js +1 -1
- package/dist/lib/bot/runtime/grok-acp.d.ts +6 -1
- package/dist/lib/bot/runtime/grok-acp.js +32 -14
- package/dist/lib/bot/runtime/grok.js +1 -1
- package/dist/lib/bot/runtime/index.js +19 -9
- package/dist/lib/bot/runtime/messages-stream.js +2 -2
- package/dist/lib/bot/runtime/types.d.ts +15 -0
- package/dist/lib/bot/runtime/types.js +9 -0
- package/dist/lib/bot/runtime-failure.d.ts +23 -0
- package/dist/lib/bot/runtime-failure.js +43 -1
- package/dist/lib/capacity/accounts.d.ts +8 -0
- package/dist/lib/capacity/accounts.js +19 -0
- package/dist/lib/capacity/available.d.ts +154 -0
- package/dist/lib/capacity/available.js +905 -0
- package/dist/lib/capacity/codex-availability.d.ts +14 -1
- package/dist/lib/capacity/codex-availability.js +26 -1
- package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
- package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
- package/dist/lib/capacity/collectors/codex.js +10 -7
- package/dist/lib/capacity/ledger.d.ts +37 -1
- package/dist/lib/capacity/ledger.js +207 -30
- package/dist/lib/capacity/project.d.ts +26 -0
- package/dist/lib/capacity/project.js +137 -8
- package/dist/lib/capacity/refusal-rows.d.ts +31 -0
- package/dist/lib/capacity/refusal-rows.js +61 -0
- package/dist/lib/capacity/refusal.d.ts +53 -2
- package/dist/lib/capacity/refusal.js +284 -65
- package/dist/lib/capacity/route.js +46 -11
- package/dist/lib/capacity/widget.d.ts +12 -1
- package/dist/lib/capacity/widget.js +91 -3
- package/dist/lib/daemon/flag-monitor.d.ts +8 -0
- package/dist/lib/daemon/flag-monitor.js +17 -6
- package/dist/lib/daemon/flag.d.ts +65 -1
- package/dist/lib/daemon/flag.js +190 -40
- package/dist/lib/daemon/ops/policy.js +62 -5
- package/dist/lib/daemon/paths.d.ts +72 -2
- package/dist/lib/daemon/paths.js +154 -3
- package/dist/lib/daemon/resolver.d.ts +2 -0
- package/dist/lib/daemon/resolver.js +3 -0
- package/dist/lib/daemon/run.d.ts +9 -0
- package/dist/lib/daemon/run.js +79 -21
- package/dist/lib/daemon/selfcheck.d.ts +22 -0
- package/dist/lib/daemon/selfcheck.js +40 -1
- package/dist/lib/daemon/server.d.ts +5 -1
- package/dist/lib/daemon/server.js +17 -23
- package/dist/lib/daemon/state-file-switch.d.ts +57 -0
- package/dist/lib/daemon/state-file-switch.js +88 -0
- package/dist/lib/daemon/state-file.d.ts +198 -0
- package/dist/lib/daemon/state-file.js +419 -0
- package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
- package/dist/lib/daemon/tcc-eperm.js +310 -0
- package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
- package/dist/lib/daemon/timed-flag-monitors.js +75 -0
- package/dist/lib/delivery/admission.d.ts +86 -0
- package/dist/lib/delivery/admission.js +148 -0
- package/dist/lib/delivery/artifacts.d.ts +7 -1
- package/dist/lib/delivery/artifacts.js +29 -10
- package/dist/lib/delivery/attempt-id.d.ts +13 -0
- package/dist/lib/delivery/attempt-id.js +16 -0
- package/dist/lib/delivery/disposable-target.d.ts +42 -0
- package/dist/lib/delivery/disposable-target.js +111 -0
- package/dist/lib/delivery/effects.d.ts +136 -0
- package/dist/lib/delivery/effects.js +541 -0
- package/dist/lib/delivery/enrollment.d.ts +21 -17
- package/dist/lib/delivery/enrollment.js +83 -5
- package/dist/lib/delivery/escalations.d.ts +51 -0
- package/dist/lib/delivery/escalations.js +60 -0
- package/dist/lib/delivery/lease.d.ts +80 -0
- package/dist/lib/delivery/lease.js +134 -0
- package/dist/lib/delivery/migrations.d.ts +120 -4
- package/dist/lib/delivery/migrations.js +215 -15
- package/dist/lib/delivery/mqtt.d.ts +2 -0
- package/dist/lib/delivery/mqtt.js +7 -0
- package/dist/lib/delivery/reconciler.d.ts +65 -1
- package/dist/lib/delivery/reconciler.js +224 -13
- package/dist/lib/delivery/rpc/client.d.ts +22 -0
- package/dist/lib/delivery/rpc/client.js +159 -0
- package/dist/lib/delivery/rpc/port.d.ts +40 -0
- package/dist/lib/delivery/rpc/port.js +16 -0
- package/dist/lib/delivery/rpc/server.d.ts +30 -0
- package/dist/lib/delivery/rpc/server.js +205 -0
- package/dist/lib/delivery/rpc/wire.d.ts +85 -0
- package/dist/lib/delivery/rpc/wire.js +143 -0
- package/dist/lib/delivery/store.d.ts +2 -0
- package/dist/lib/delivery/store.js +4 -0
- package/dist/lib/delivery/windows-service-install.d.ts +262 -0
- package/dist/lib/delivery/windows-service-install.js +892 -0
- package/dist/lib/delivery/workers/macos.d.ts +16 -1
- package/dist/lib/delivery/workers/macos.js +54 -12
- package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
- package/dist/lib/delivery/workers/windows-service-live.js +711 -0
- package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
- package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
- package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
- package/dist/lib/delivery/workers/windows-service.js +584 -0
- package/dist/lib/delivery/workers/windows.d.ts +32 -22
- package/dist/lib/delivery/workers/windows.js +50 -64
- package/dist/lib/doctor/checks/host-core.d.ts +50 -0
- package/dist/lib/doctor/checks/host-core.js +269 -0
- package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
- package/dist/lib/doctor/checks/replay-recorder.js +261 -0
- package/dist/lib/doctor/registry.js +4 -0
- package/dist/lib/environment/profile.d.ts +239 -0
- package/dist/lib/environment/profile.js +251 -0
- package/dist/lib/hook-engine/reconcile.js +39 -13
- package/dist/lib/hook-engine/registration.d.ts +9 -0
- package/dist/lib/hook-engine/registration.js +19 -0
- package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
- package/dist/lib/hot-channels/adapters/meetings.js +36 -3
- package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
- package/dist/lib/hot-channels/adapters/slack.js +64 -21
- package/dist/lib/hot-channels/alert.d.ts +2 -0
- package/dist/lib/hot-channels/alert.js +8 -1
- package/dist/lib/hot-channels/contract.d.ts +12 -0
- package/dist/lib/hot-channels/contract.js +7 -0
- package/dist/lib/hot-channels/loop.js +1 -0
- package/dist/lib/hot-channels/run.d.ts +6 -0
- package/dist/lib/hot-channels/run.js +4 -0
- package/dist/lib/hot-channels/signals-pass.d.ts +74 -1
- package/dist/lib/hot-channels/signals-pass.js +82 -41
- package/dist/lib/hot-channels/signals-redo.js +10 -2
- package/dist/lib/install/claude-targets.d.ts +12 -1
- package/dist/lib/install/claude-targets.js +57 -5
- package/dist/lib/install/codex-targets.d.ts +2 -2
- package/dist/lib/install/codex-targets.js +36 -6
- package/dist/lib/install/hook-target.d.ts +3 -0
- package/dist/lib/install/hook-target.js +11 -0
- package/dist/lib/lanes/canonical-host.d.ts +35 -0
- package/dist/lib/lanes/canonical-host.js +65 -0
- package/dist/lib/lanes/host-capacity.d.ts +30 -0
- package/dist/lib/lanes/host-capacity.js +29 -3
- package/dist/lib/lanes/watcher.js +35 -0
- package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
- package/dist/lib/mesh/live/daemon/run.js +5 -2
- package/dist/lib/mesh/live/flush.d.ts +5 -1
- package/dist/lib/mesh/live/flush.js +12 -6
- package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
- package/dist/lib/mesh/live/reporting-privacy.js +56 -1
- package/dist/lib/mesh/live/spool.d.ts +7 -0
- package/dist/lib/mesh/live/spool.js +25 -0
- package/dist/lib/person-setting-cache.d.ts +38 -0
- package/dist/lib/person-setting-cache.js +98 -0
- package/dist/lib/safe-store.d.ts +245 -0
- package/dist/lib/safe-store.js +777 -0
- package/dist/lib/signals/engine.d.ts +29 -2
- package/dist/lib/signals/engine.js +103 -4
- package/dist/lib/signals/reply.js +73 -18
- package/dist/lib/signals/steps/adapters.js +7 -2
- package/dist/lib/signals/steps/extract.d.ts +13 -0
- package/dist/lib/signals/steps/extract.js +122 -6
- package/dist/main.js +46 -3
- package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
- package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
- package/dist/utils/auth-expiry.d.ts +8 -0
- package/dist/utils/auth-expiry.js +53 -0
- package/dist/utils/catalog-runtime-paths.d.ts +34 -0
- package/dist/utils/catalog-runtime-paths.js +53 -0
- package/dist/utils/cli-telemetry.d.ts +21 -0
- package/dist/utils/cli-telemetry.js +34 -0
- package/dist/utils/command-usage.d.ts +275 -0
- package/dist/utils/command-usage.js +797 -0
- package/dist/utils/files-browse-acl.js +1 -1
- package/dist/utils/hook-trust.d.ts +7 -0
- package/dist/utils/hook-trust.js +31 -4
- package/dist/utils/host-registration.d.ts +126 -0
- package/dist/utils/host-registration.js +378 -0
- package/dist/utils/resident-package-preload.js +2 -0
- package/package.json +10 -8
- package/scripts/bench-core.mjs +1096 -0
- package/scripts/check-function-manifest.mjs +702 -0
- package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
- package/dist/lib/delivery/workers/windows-boundary.js +0 -693
|
@@ -0,0 +1,905 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hq-available-ai.v1: one local, token-free answer to what AI can run now.
|
|
3
|
+
*
|
|
4
|
+
* Each rebuild writes available.json next to now.json, under the same lock.
|
|
5
|
+
* `hq capacity available --json` prints the same document. The schema has no
|
|
6
|
+
* error state: failure classes stay in `hq capacity doctor` and logs.
|
|
7
|
+
*
|
|
8
|
+
* Ranking is route.ts's. `best` comes only from accounts enabled for work and
|
|
9
|
+
* never from a paid tranche. Nothing here reads a credential: with no ledger
|
|
10
|
+
* the rows come from each tool's own status command, and only its yes or no is
|
|
11
|
+
* kept.
|
|
12
|
+
*/
|
|
13
|
+
import { execFile, spawn } from "node:child_process";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import * as fs from "node:fs";
|
|
16
|
+
import * as path from "node:path";
|
|
17
|
+
import { LANE_PROVIDERS } from "../lanes/types.js";
|
|
18
|
+
import { homesOffForWork, listCapacityAccounts } from "./accounts.js";
|
|
19
|
+
import { lanesConfigPath } from "../lanes/config.js";
|
|
20
|
+
import { resolveLanesHqRoot } from "../lanes/hq-root.js";
|
|
21
|
+
import { isHqRoot } from "../../utils/hq-roots-core.js";
|
|
22
|
+
import { canonicalCodexAccountId, hasCodexCreditRoom } from "./codex-availability.js";
|
|
23
|
+
import { CAPACITY_STALE_MS } from "./freshness.js";
|
|
24
|
+
import { LedgerRejected, PROVIDER_TOKEN_LEAK, capacityRoot, readCollectorMark, readCurrentNow, readNow, } from "./ledger.js";
|
|
25
|
+
import { projectCapacityView } from "./project.js";
|
|
26
|
+
import { isRefusalHold, refusalEnded } from "./refusal-rows.js";
|
|
27
|
+
import { DEFAULT_FLOOR, SKIP_STALE_READING, hasExtraUsageRoom, labelLimit, pickAccount } from "./route.js";
|
|
28
|
+
export const AVAILABLE_SCHEMA_VERSION = "hq-available-ai.v1";
|
|
29
|
+
export const AVAILABLE_FILE_NAME = "available.json";
|
|
30
|
+
export const FRESH_WAIT_MS = 3_000;
|
|
31
|
+
export const STATUS_PROBE_TIMEOUT_MS = 2_500;
|
|
32
|
+
export const COLLECT_MARK = ".available-collect.lock";
|
|
33
|
+
export const COLLECT_MARK_TTL_MS = 60_000;
|
|
34
|
+
const FRESH_POLL_MS = 100;
|
|
35
|
+
/**
|
|
36
|
+
* Which engines may run a tranche. model_cli follows `hq bot switch-account`,
|
|
37
|
+
* which takes all three runtimes. Fleet excludes Grok, because switch-account
|
|
38
|
+
* refuses it there, and Claude plan logins, which the owner parked on
|
|
39
|
+
* 2026-11-05: no new offer, no removal, a running Fleet Claude bot is untouched.
|
|
40
|
+
* `lane` is added per account, when a lane account is enabled on its home.
|
|
41
|
+
*/
|
|
42
|
+
export const USABLE_BY = {
|
|
43
|
+
claude: {
|
|
44
|
+
plan: ["model_cli"],
|
|
45
|
+
scoped_model: ["model_cli"],
|
|
46
|
+
extra_usage: ["model_cli"],
|
|
47
|
+
credits: ["model_cli"],
|
|
48
|
+
api_key: ["model_cli", "fleet"],
|
|
49
|
+
},
|
|
50
|
+
codex: {
|
|
51
|
+
plan: ["model_cli", "fleet"],
|
|
52
|
+
scoped_model: ["model_cli", "fleet"],
|
|
53
|
+
extra_usage: ["model_cli", "fleet"],
|
|
54
|
+
credits: ["model_cli", "fleet"],
|
|
55
|
+
api_key: ["model_cli", "fleet"],
|
|
56
|
+
},
|
|
57
|
+
grok: {
|
|
58
|
+
plan: ["model_cli"],
|
|
59
|
+
scoped_model: ["model_cli"],
|
|
60
|
+
extra_usage: ["model_cli"],
|
|
61
|
+
credits: ["model_cli"],
|
|
62
|
+
api_key: ["model_cli"],
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
const AVAILABILITY_ORDER = {
|
|
66
|
+
ready: 0,
|
|
67
|
+
likely_ready: 1,
|
|
68
|
+
low: 2,
|
|
69
|
+
used_up: 3,
|
|
70
|
+
needs_sign_in: 4,
|
|
71
|
+
not_installed: 5,
|
|
72
|
+
};
|
|
73
|
+
function usableBy(provider, kind, lane) {
|
|
74
|
+
const engines = [...USABLE_BY[provider][kind]];
|
|
75
|
+
return lane ? [...engines, "lane"] : engines;
|
|
76
|
+
}
|
|
77
|
+
function canonical(home) {
|
|
78
|
+
const resolved = path.resolve(home);
|
|
79
|
+
try {
|
|
80
|
+
return fs.realpathSync(resolved);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return resolved;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function capitalized(text) {
|
|
87
|
+
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
88
|
+
}
|
|
89
|
+
function roleFor(provider, homes, accounts) {
|
|
90
|
+
const wanted = new Set(homes.map(canonical));
|
|
91
|
+
const matches = accounts.filter((account) => account.provider === provider && wanted.has(canonical(account.home)));
|
|
92
|
+
if (matches.length === 0)
|
|
93
|
+
return null;
|
|
94
|
+
return {
|
|
95
|
+
work: matches.some((account) => account.lanes !== false),
|
|
96
|
+
lane: matches.some((account) => account.source !== "default" && account.lanes !== false),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** Every account counts as a lane account for scoring, so a row can state its own room. */
|
|
100
|
+
function scoringConfig(accounts) {
|
|
101
|
+
const providers = {};
|
|
102
|
+
for (const provider of LANE_PROVIDERS)
|
|
103
|
+
providers[provider] = { accounts: {} };
|
|
104
|
+
for (const account of accounts) {
|
|
105
|
+
providers[account.provider].accounts[account.label] = { home: account.home, enabled: true };
|
|
106
|
+
}
|
|
107
|
+
return { providers };
|
|
108
|
+
}
|
|
109
|
+
function ageSeconds(observedAt, nowMs) {
|
|
110
|
+
const at = observedAt ? Date.parse(observedAt) : Number.NaN;
|
|
111
|
+
return Number.isFinite(at) ? Math.max(0, Math.round((nowMs - at) / 1000)) : null;
|
|
112
|
+
}
|
|
113
|
+
function confidenceOf(limit) {
|
|
114
|
+
if (!limit)
|
|
115
|
+
return "unknown";
|
|
116
|
+
return limit.confidence === "fetched" || limit.confidence === "observed" ? limit.confidence : "unknown";
|
|
117
|
+
}
|
|
118
|
+
function baseRow(context, kind, scope) {
|
|
119
|
+
const { provider, account, role } = context;
|
|
120
|
+
const suffix = kind === "plan" ? "plan" : scope ? `${kind}:${scope}` : kind;
|
|
121
|
+
return {
|
|
122
|
+
optionId: `${provider}:${account.accountId}:${suffix}`,
|
|
123
|
+
provider,
|
|
124
|
+
account: {
|
|
125
|
+
id: account.accountId,
|
|
126
|
+
label: account.labels[0] ?? account.accountId,
|
|
127
|
+
organization: account.organization ?? null,
|
|
128
|
+
},
|
|
129
|
+
tranche: { kind, scope, paid: kind === "extra_usage" || kind === "credits" || kind === "api_key" },
|
|
130
|
+
usableBy: usableBy(provider, kind, role.lane),
|
|
131
|
+
holder: "cli_home",
|
|
132
|
+
models: [],
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** What the account's own readings leave on its plan, with no refusal counted. */
|
|
136
|
+
function realLeftPercent(account, nowMs) {
|
|
137
|
+
const used = account.limits
|
|
138
|
+
.filter((limit) => !isRefusalHold(limit) && (limit.kind === "session" || limit.kind === "weekly_all"))
|
|
139
|
+
.filter((limit) => !limit.resetsAt || Date.parse(limit.resetsAt) > nowMs)
|
|
140
|
+
.map((limit) => limit.usedPercent)
|
|
141
|
+
.filter((value) => typeof value === "number");
|
|
142
|
+
return used.length > 0 ? Math.max(0, 100 - Math.max(...used)) : null;
|
|
143
|
+
}
|
|
144
|
+
function planRow(context, result) {
|
|
145
|
+
const { account, nowMs } = context;
|
|
146
|
+
const name = account.labels[0] ?? account.accountId;
|
|
147
|
+
const base = baseRow(context, "plan", null);
|
|
148
|
+
const weekly = account.limits.find((limit) => limit.kind === "weekly_all" && !isRefusalHold(limit));
|
|
149
|
+
const reading = { ageSeconds: ageSeconds(account.observedAt, nowMs), confidence: confidenceOf(weekly ?? account.limits[0]) };
|
|
150
|
+
const ranked = result.ranked[0];
|
|
151
|
+
const spent = lastUsedUp(account, nowMs);
|
|
152
|
+
const usedUpRow = (limit) => ({
|
|
153
|
+
...base,
|
|
154
|
+
availability: "used_up",
|
|
155
|
+
leftPercent: 0,
|
|
156
|
+
backAt: limit.resetsAt,
|
|
157
|
+
reading,
|
|
158
|
+
reason: `Last reading showed ${labelLimit(limit)} used up.`,
|
|
159
|
+
nextStep: { kind: "wait", label: "Wait for the reset" },
|
|
160
|
+
});
|
|
161
|
+
if (ranked && ranked.extra_usage !== true) {
|
|
162
|
+
if (ranked.usage_unknown) {
|
|
163
|
+
if (spent)
|
|
164
|
+
return usedUpRow(spent);
|
|
165
|
+
return {
|
|
166
|
+
...base,
|
|
167
|
+
availability: "likely_ready",
|
|
168
|
+
leftPercent: null,
|
|
169
|
+
backAt: null,
|
|
170
|
+
reading: { ageSeconds: reading.ageSeconds, confidence: "unknown" },
|
|
171
|
+
reason: "Signed in. Reading usage.",
|
|
172
|
+
nextStep: { kind: "use", label: `Use ${name}` },
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
const low = ranked.headroom < DEFAULT_FLOOR;
|
|
176
|
+
return {
|
|
177
|
+
...base,
|
|
178
|
+
availability: low ? "low" : "ready",
|
|
179
|
+
leftPercent: ranked.headroom,
|
|
180
|
+
backAt: low ? ranked.binding.resets_at : null,
|
|
181
|
+
reading,
|
|
182
|
+
reason: low
|
|
183
|
+
? `${ranked.headroom}% left on ${ranked.binding.limit}.`
|
|
184
|
+
: `${ranked.headroom}% left.`,
|
|
185
|
+
nextStep: { kind: "use", label: `Use ${name}` },
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
if (ranked?.extra_usage === true) {
|
|
189
|
+
return {
|
|
190
|
+
...base,
|
|
191
|
+
availability: "used_up",
|
|
192
|
+
leftPercent: 0,
|
|
193
|
+
backAt: ranked.binding.resets_at,
|
|
194
|
+
reading,
|
|
195
|
+
reason: `${capitalized(ranked.binding.limit)} limit used up.`,
|
|
196
|
+
nextStep: { kind: "wait", label: "Wait for the reset" },
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
const skip = result.skipped[0];
|
|
200
|
+
const reasonText = skip?.reason ?? "";
|
|
201
|
+
if (account.signedOut || account.authState === "signed_out") {
|
|
202
|
+
return {
|
|
203
|
+
...base,
|
|
204
|
+
holder: "none",
|
|
205
|
+
availability: "needs_sign_in",
|
|
206
|
+
leftPercent: null,
|
|
207
|
+
backAt: null,
|
|
208
|
+
reading,
|
|
209
|
+
reason: "Signed out on this computer.",
|
|
210
|
+
nextStep: { kind: "sign_in", label: `Sign in to ${name}` },
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
if (/nearly used up$/.test(reasonText)) {
|
|
214
|
+
return {
|
|
215
|
+
...base,
|
|
216
|
+
availability: "low",
|
|
217
|
+
leftPercent: null,
|
|
218
|
+
backAt: skip?.resets_at ?? null,
|
|
219
|
+
reading,
|
|
220
|
+
reason: `${capitalized(reasonText)}.`,
|
|
221
|
+
nextStep: { kind: "use", label: `Use ${name}` },
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
if (/used up|^rate limited$/.test(reasonText)) {
|
|
225
|
+
// A rate limit says nothing about the plan, so the real figure stands, and it
|
|
226
|
+
// clears in minutes. Any other refusal says the account stopped, not how much
|
|
227
|
+
// of the plan is left.
|
|
228
|
+
const rateLimited = reasonText === "rate limited";
|
|
229
|
+
const backAt = skip?.resets_at ?? null;
|
|
230
|
+
const refused = account.limits.some((limit) => isRefusalHold(limit) && !refusalEnded(limit, nowMs) && limit.resetsAt === backAt)
|
|
231
|
+
&& !account.limits.some((limit) => !isRefusalHold(limit) && limit.resetsAt === backAt && (limit.usedPercent ?? 0) >= 100);
|
|
232
|
+
return {
|
|
233
|
+
...base,
|
|
234
|
+
availability: "used_up",
|
|
235
|
+
leftPercent: rateLimited ? realLeftPercent(account, nowMs) : refused ? null : 0,
|
|
236
|
+
backAt,
|
|
237
|
+
reading,
|
|
238
|
+
reason: `${capitalized(reasonText.split(";")[0] ?? reasonText)}.`,
|
|
239
|
+
nextStep: { kind: "wait", label: rateLimited ? "Try again shortly" : "Wait for the reset" },
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
// The route has no current number. An old used-up reading still stands until
|
|
243
|
+
// its reset. Anything else is a sign-in with no usable number, not a failure,
|
|
244
|
+
// and `best` stays with the route's pick.
|
|
245
|
+
if (spent)
|
|
246
|
+
return usedUpRow(spent);
|
|
247
|
+
return {
|
|
248
|
+
...base,
|
|
249
|
+
availability: "likely_ready",
|
|
250
|
+
leftPercent: null,
|
|
251
|
+
backAt: null,
|
|
252
|
+
reading: { ageSeconds: reading.ageSeconds, confidence: "unknown" },
|
|
253
|
+
reason: reasonText === SKIP_STALE_READING
|
|
254
|
+
? "No usage reading in the last 24 hours."
|
|
255
|
+
: account.authState === "expired"
|
|
256
|
+
? "Sign-in expired, and it renews on next use. Usage has not been read since."
|
|
257
|
+
: "Signed in. Reading usage.",
|
|
258
|
+
nextStep: { kind: "use", label: `Use ${name}` },
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
/** The newest plan-limit reading that says used up, while its reset is still ahead. */
|
|
262
|
+
function lastUsedUp(account, nowMs) {
|
|
263
|
+
for (const limit of account.limits) {
|
|
264
|
+
if (limit.kind !== "session" && limit.kind !== "weekly_all")
|
|
265
|
+
continue;
|
|
266
|
+
if (refusalEnded(limit, nowMs))
|
|
267
|
+
continue;
|
|
268
|
+
const used = typeof limit.usedPercent === "number" && limit.usedPercent >= 100;
|
|
269
|
+
if (!used && limit.state !== "exhausted")
|
|
270
|
+
continue;
|
|
271
|
+
const reset = limit.resetsAt ? Date.parse(limit.resetsAt) : Number.NaN;
|
|
272
|
+
if (!Number.isFinite(reset) || reset > nowMs)
|
|
273
|
+
return limit;
|
|
274
|
+
}
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
function scopedRows(context, plan) {
|
|
278
|
+
const { provider, account, nowMs } = context;
|
|
279
|
+
// weekly_all applies to every model, so a plan the route would refuse takes
|
|
280
|
+
// its scoped rows with it.
|
|
281
|
+
const planOpen = plan.availability === "ready" || plan.availability === "low";
|
|
282
|
+
// Grok's scoped limit is its plan limit, which the plan row already reads.
|
|
283
|
+
if (provider === "grok")
|
|
284
|
+
return [];
|
|
285
|
+
const name = account.labels[0] ?? account.accountId;
|
|
286
|
+
// A refusal on one model stays on that model.
|
|
287
|
+
const refusedScopes = account.limits.filter((limit) => limit.kind === "weekly_scoped" && limit.scope && isRefusalHold(limit) && !refusalEnded(limit, nowMs));
|
|
288
|
+
const refusedFor = (scope) => refusedScopes.find((limit) => limit.scope === (scope ?? "").toLowerCase());
|
|
289
|
+
const realScoped = account.limits.filter((limit) => limit.kind === "weekly_scoped" && limit.scope && typeof limit.usedPercent === "number" && !isRefusalHold(limit));
|
|
290
|
+
const onlyRefused = refusedScopes.filter((hold) => !realScoped.some((limit) => (limit.scope ?? "").toLowerCase() === hold.scope));
|
|
291
|
+
return [...realScoped, ...onlyRefused]
|
|
292
|
+
.map((limit) => {
|
|
293
|
+
const left = Math.max(0, 100 - (limit.usedPercent ?? 0));
|
|
294
|
+
const refused = refusedFor(limit.scope);
|
|
295
|
+
const usedUp = left === 0 || refused !== undefined;
|
|
296
|
+
if (planOpen && refused) {
|
|
297
|
+
return {
|
|
298
|
+
...baseRow(context, "scoped_model", limit.scope),
|
|
299
|
+
availability: "used_up",
|
|
300
|
+
leftPercent: null,
|
|
301
|
+
backAt: refused.resetsAt,
|
|
302
|
+
reading: { ageSeconds: ageSeconds(refused.observedAt, nowMs), confidence: confidenceOf(refused) },
|
|
303
|
+
reason: `${capitalized(limit.scope ?? "This model")} limit reached.`,
|
|
304
|
+
nextStep: { kind: "wait", label: "Wait for the reset" },
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
if (!planOpen) {
|
|
308
|
+
return {
|
|
309
|
+
...plan,
|
|
310
|
+
...baseRow(context, "scoped_model", limit.scope),
|
|
311
|
+
holder: plan.holder,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
return {
|
|
315
|
+
...baseRow(context, "scoped_model", limit.scope),
|
|
316
|
+
availability: usedUp ? "used_up" : left < DEFAULT_FLOOR ? "low" : "ready",
|
|
317
|
+
leftPercent: left,
|
|
318
|
+
backAt: usedUp || left < DEFAULT_FLOOR ? limit.resetsAt : null,
|
|
319
|
+
reading: { ageSeconds: ageSeconds(limit.observedAt, nowMs), confidence: confidenceOf(limit) },
|
|
320
|
+
reason: usedUp ? `${capitalized(labelLimit(limit))} limit used up.` : `${left}% left on ${labelLimit(limit)}.`,
|
|
321
|
+
nextStep: usedUp
|
|
322
|
+
? { kind: "wait", label: "Wait for the reset" }
|
|
323
|
+
: { kind: "use", label: `Use ${name} for ${limit.scope}` },
|
|
324
|
+
};
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
function paidRows(context) {
|
|
328
|
+
const { provider, account, nowMs } = context;
|
|
329
|
+
const name = account.labels[0] ?? account.accountId;
|
|
330
|
+
const rows = [];
|
|
331
|
+
const paid = (kind, limit, reason) => ({
|
|
332
|
+
...baseRow(context, kind, null),
|
|
333
|
+
availability: "ready",
|
|
334
|
+
leftPercent: null,
|
|
335
|
+
backAt: null,
|
|
336
|
+
reading: { ageSeconds: ageSeconds(limit?.observedAt ?? account.observedAt, nowMs), confidence: confidenceOf(limit) },
|
|
337
|
+
reason,
|
|
338
|
+
nextStep: { kind: "use", label: `Use ${name} on paid usage` },
|
|
339
|
+
});
|
|
340
|
+
if (provider === "claude" && hasExtraUsageRoom(account)) {
|
|
341
|
+
rows.push(paid("extra_usage", account.limits.find((limit) => limit.limitId === "extra_usage"), "Paid extra usage is on."));
|
|
342
|
+
}
|
|
343
|
+
if (provider === "codex" && hasCodexCreditRoom(account.limits, nowMs)) {
|
|
344
|
+
rows.push(paid("credits", account.limits.find((limit) => limit.limitId.endsWith(":credits")), "Codex credits are available."));
|
|
345
|
+
}
|
|
346
|
+
return rows;
|
|
347
|
+
}
|
|
348
|
+
function pickerFor(view, provider, account, input, config) {
|
|
349
|
+
return pickAccount({
|
|
350
|
+
view: provider && account
|
|
351
|
+
? { ...view, providers: [{ ...provider, accounts: [account] }] }
|
|
352
|
+
: view,
|
|
353
|
+
lanes: [],
|
|
354
|
+
lanesConfig: config,
|
|
355
|
+
now: input.now,
|
|
356
|
+
collectorEnabled: input.collectorEnabled,
|
|
357
|
+
capacityStale: false,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
function sortOptions(options) {
|
|
361
|
+
return options.sort((a, b) => Number(a.tranche.paid) - Number(b.tranche.paid)
|
|
362
|
+
|| AVAILABILITY_ORDER[a.availability] - AVAILABILITY_ORDER[b.availability]
|
|
363
|
+
|| (a.backAt ?? "").localeCompare(b.backAt ?? "")
|
|
364
|
+
|| (b.leftPercent ?? -1) - (a.leftPercent ?? -1)
|
|
365
|
+
|| a.optionId.localeCompare(b.optionId));
|
|
366
|
+
}
|
|
367
|
+
function nextBackAt(options) {
|
|
368
|
+
return options
|
|
369
|
+
.filter((option) => option.availability === "used_up" && option.backAt)
|
|
370
|
+
.map((option) => option.backAt)
|
|
371
|
+
.sort()[0] ?? null;
|
|
372
|
+
}
|
|
373
|
+
/** First unpaid row that can run. Rows are already in preference order. */
|
|
374
|
+
function firstRunnable(options) {
|
|
375
|
+
return options.find((option) => !option.tranche.paid
|
|
376
|
+
&& (option.availability === "ready" || option.availability === "likely_ready" || option.availability === "low"));
|
|
377
|
+
}
|
|
378
|
+
export function buildAvailableDocument(input) {
|
|
379
|
+
const nowMs = input.now.getTime();
|
|
380
|
+
// The rebuild already merged by identity under its rules. This only applies
|
|
381
|
+
// the registry: labels, and accounts that no longer exist.
|
|
382
|
+
const projected = projectCapacityView(input.view, { accounts: input.accounts });
|
|
383
|
+
const config = scoringConfig(input.accounts);
|
|
384
|
+
const options = [];
|
|
385
|
+
const workProviders = [];
|
|
386
|
+
for (const provider of projected.providers) {
|
|
387
|
+
const providerId = provider.provider;
|
|
388
|
+
if (!LANE_PROVIDERS.includes(providerId))
|
|
389
|
+
continue;
|
|
390
|
+
const workAccounts = [];
|
|
391
|
+
for (const account of provider.accounts ?? []) {
|
|
392
|
+
const role = roleFor(providerId, account.homes, input.accounts);
|
|
393
|
+
if (!role)
|
|
394
|
+
continue;
|
|
395
|
+
if (role.work)
|
|
396
|
+
workAccounts.push(account);
|
|
397
|
+
else if (input.includeOther !== true)
|
|
398
|
+
continue;
|
|
399
|
+
const context = { provider: providerId, account, role, nowMs };
|
|
400
|
+
const plan = planRow(context, pickerFor(projected, provider, account, input, config));
|
|
401
|
+
options.push(plan, ...scopedRows(context, plan), ...(plan.availability === "needs_sign_in" ? [] : paidRows(context)));
|
|
402
|
+
}
|
|
403
|
+
workProviders.push({ ...provider, accounts: workAccounts });
|
|
404
|
+
}
|
|
405
|
+
sortOptions(options);
|
|
406
|
+
// best is only ever an account enabled for work on an unpaid tranche, and
|
|
407
|
+
// agrees with the route. An unregistered default home has no lane account, so
|
|
408
|
+
// it is considered only when no lane account can run.
|
|
409
|
+
const hasLane = (provider, account) => roleFor(provider.provider, account.homes, input.accounts)?.lane === true;
|
|
410
|
+
const laneProviders = workProviders.map((provider) => ({
|
|
411
|
+
...provider,
|
|
412
|
+
accounts: (provider.accounts ?? []).filter((account) => hasLane(provider, account)),
|
|
413
|
+
}));
|
|
414
|
+
const bestAmong = (providers) => {
|
|
415
|
+
const route = pickerFor({ ...projected, providers }, null, null, input, config);
|
|
416
|
+
for (const row of [route.pick, ...route.ranked]) {
|
|
417
|
+
if (!row || row.extra_usage === true)
|
|
418
|
+
continue;
|
|
419
|
+
const account = providers.find((provider) => provider.provider === row.provider)?.accounts
|
|
420
|
+
?.find((candidate) => (candidate.labels[0] ?? candidate.accountId) === row.label);
|
|
421
|
+
const id = account ? `${row.provider}:${account.accountId}:plan` : null;
|
|
422
|
+
const option = id ? options.find((candidate) => candidate.optionId === id) : undefined;
|
|
423
|
+
if (id && option && firstRunnable([option]))
|
|
424
|
+
return id;
|
|
425
|
+
}
|
|
426
|
+
return null;
|
|
427
|
+
};
|
|
428
|
+
const best = bestAmong(laneProviders) ?? bestAmong(workProviders);
|
|
429
|
+
return {
|
|
430
|
+
schemaVersion: AVAILABLE_SCHEMA_VERSION,
|
|
431
|
+
generatedAt: input.now.toISOString(),
|
|
432
|
+
freshness: input.freshness ?? "fresh",
|
|
433
|
+
best,
|
|
434
|
+
nextBackAt: nextBackAt(options),
|
|
435
|
+
options,
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
/** The bytes for available.json. Refuses any value shaped like a provider token. */
|
|
439
|
+
export function serializeAvailable(document) {
|
|
440
|
+
const body = `${JSON.stringify(document, null, 2)}\n`;
|
|
441
|
+
if (PROVIDER_TOKEN_LEAK.test(body)) {
|
|
442
|
+
throw new LedgerRejected("available.json refused: provider token shape");
|
|
443
|
+
}
|
|
444
|
+
return body;
|
|
445
|
+
}
|
|
446
|
+
/** The account list, with a default home the registry turned off marked off. */
|
|
447
|
+
function rosterFor(options) {
|
|
448
|
+
const off = homesOffForWork(options).map((entry) => `${entry.provider}\0${canonical(entry.home)}`);
|
|
449
|
+
return listCapacityAccounts(options).map((account) => account.source === "default" && off.includes(`${account.provider}\0${canonical(account.home)}`)
|
|
450
|
+
? { ...account, lanes: false }
|
|
451
|
+
: account);
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Raised by a rebuild that cannot read the account registry or the HQ root. Its
|
|
455
|
+
* message is fixed text: no path, no config content.
|
|
456
|
+
*/
|
|
457
|
+
export class RosterUnavailable extends Error {
|
|
458
|
+
constructor() {
|
|
459
|
+
super("the account registry or HQ root could not be read, so the last file was kept");
|
|
460
|
+
this.name = "RosterUnavailable";
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* The HQ tree whose registry a resolved root reads. Walks up from the root and
|
|
465
|
+
* returns the nearest folder that has a lanes config, so an explicit root with
|
|
466
|
+
* a lanes config always wins. A folder that only looks like an HQ tree
|
|
467
|
+
* (`isHqRoot`) is not enough to stop the walk: a copy of the hq-core template
|
|
468
|
+
* inside HQ (repos/public/hq-core, an hq-core-staging worktree) or a route
|
|
469
|
+
* folder named companies/ has the same markers but no registry, and reading it
|
|
470
|
+
* would drop the registry accounts and bring back a default home the registry
|
|
471
|
+
* turned off. When no folder on the way has a lanes config, the outermost HQ
|
|
472
|
+
* tree on the path is used (a fresh install, an empty registry). Null when no
|
|
473
|
+
* folder on the way is an HQ tree.
|
|
474
|
+
*/
|
|
475
|
+
export function registryHqRoot(resolved) {
|
|
476
|
+
let outermostHq = null;
|
|
477
|
+
for (let dir = resolved;;) {
|
|
478
|
+
if (fs.existsSync(lanesConfigPath(dir)))
|
|
479
|
+
return dir;
|
|
480
|
+
if (isHqRoot(dir))
|
|
481
|
+
outermostHq = dir;
|
|
482
|
+
const parent = path.dirname(dir);
|
|
483
|
+
if (parent === dir)
|
|
484
|
+
return outermostHq;
|
|
485
|
+
dir = parent;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* The account roster from the registry, or null when the HQ root cannot be
|
|
490
|
+
* found or the registry cannot be read. Null is not "no registry": a resolved
|
|
491
|
+
* HQ root with no lanes config is a known, empty registry and returns the
|
|
492
|
+
* default homes. Callers must not stand the default homes in for null, because
|
|
493
|
+
* that drops registry accounts on custom homes and brings back a default home
|
|
494
|
+
* the registry turned off for work.
|
|
495
|
+
*
|
|
496
|
+
* HQ_ROOT or CLAUDE_PROJECT_DIR is trusted when it names any existing folder.
|
|
497
|
+
* A folder with no lanes config is often a subfolder of an HQ tree (a session
|
|
498
|
+
* opened in `repos/...`, `companies/x` or a template copy such as
|
|
499
|
+
* `repos/public/hq-core`), so the registry is read from the nearest enclosing
|
|
500
|
+
* folder with a lanes config, else the outermost enclosing HQ tree
|
|
501
|
+
* (registryHqRoot). A folder with no enclosing HQ tree is a wrong root, not an
|
|
502
|
+
* empty registry, so it is null too.
|
|
503
|
+
*/
|
|
504
|
+
export function registryRoster(options = {}) {
|
|
505
|
+
const env = options.env ?? process.env;
|
|
506
|
+
const home = options.home ?? env.HOME;
|
|
507
|
+
let resolved;
|
|
508
|
+
try {
|
|
509
|
+
resolved = resolveLanesHqRoot({ env });
|
|
510
|
+
}
|
|
511
|
+
catch {
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
try {
|
|
515
|
+
const hqRoot = registryHqRoot(resolved);
|
|
516
|
+
if (hqRoot === null)
|
|
517
|
+
return null;
|
|
518
|
+
return rosterFor({ env, hqRoot, home });
|
|
519
|
+
}
|
|
520
|
+
catch {
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* The document a rebuild writes. Called under the now.json lock. Throws
|
|
526
|
+
* RosterUnavailable when the registry or HQ root cannot be read: a writer that
|
|
527
|
+
* cannot see the registry would write a partial roster marked fresh, so it
|
|
528
|
+
* keeps the last file instead. Readers rebuild from a newer now.json when they
|
|
529
|
+
* can read the registry themselves (readAvailable).
|
|
530
|
+
*/
|
|
531
|
+
export function availableForRebuild(view, root, now, options = {}) {
|
|
532
|
+
const env = options.env ?? process.env;
|
|
533
|
+
const accounts = registryRoster({ ...options, env });
|
|
534
|
+
if (!accounts)
|
|
535
|
+
throw new RosterUnavailable();
|
|
536
|
+
return serializeAvailable(buildAvailableDocument({
|
|
537
|
+
view,
|
|
538
|
+
accounts,
|
|
539
|
+
now,
|
|
540
|
+
collectorEnabled: readCollectorMark({ ...options, root })?.enabled ?? null,
|
|
541
|
+
}));
|
|
542
|
+
}
|
|
543
|
+
const STATUS_COMMANDS = {
|
|
544
|
+
claude: ["auth", "status", "--json"],
|
|
545
|
+
codex: ["login", "status"],
|
|
546
|
+
grok: ["models"],
|
|
547
|
+
};
|
|
548
|
+
const HOME_ENV = {
|
|
549
|
+
claude: "CLAUDE_CONFIG_DIR",
|
|
550
|
+
codex: "CODEX_HOME",
|
|
551
|
+
grok: "GROK_HOME",
|
|
552
|
+
};
|
|
553
|
+
export const defaultStatusProbe = (provider, home) => new Promise((resolve) => {
|
|
554
|
+
execFile(provider, [...STATUS_COMMANDS[provider]], {
|
|
555
|
+
timeout: STATUS_PROBE_TIMEOUT_MS,
|
|
556
|
+
env: { ...process.env, [HOME_ENV[provider]]: home, HQ_NO_ENSURE_HQ_DESKTOP: "1" },
|
|
557
|
+
windowsHide: true,
|
|
558
|
+
}, (error, stdout) => {
|
|
559
|
+
const code = error?.code;
|
|
560
|
+
if (code === "ENOENT")
|
|
561
|
+
return resolve("not_installed");
|
|
562
|
+
if (error && error.killed)
|
|
563
|
+
return resolve("no_answer");
|
|
564
|
+
if (provider === "claude") {
|
|
565
|
+
try {
|
|
566
|
+
const parsed = JSON.parse(String(stdout).slice(String(stdout).indexOf("{")));
|
|
567
|
+
if (typeof parsed.loggedIn === "boolean")
|
|
568
|
+
return resolve(parsed.loggedIn ? "signed_in" : "signed_out");
|
|
569
|
+
}
|
|
570
|
+
catch {
|
|
571
|
+
// Not the expected output: no answer.
|
|
572
|
+
}
|
|
573
|
+
return resolve("no_answer");
|
|
574
|
+
}
|
|
575
|
+
if (provider === "codex")
|
|
576
|
+
return resolve(error ? "signed_out" : "signed_in");
|
|
577
|
+
// `grok models` lists models signed in or not, so it shows the tool runs.
|
|
578
|
+
return resolve(error ? "no_answer" : "signed_in");
|
|
579
|
+
});
|
|
580
|
+
});
|
|
581
|
+
/** Rows with no ledger at all, from each tool's status command. */
|
|
582
|
+
export async function buildAvailableFromStatus(input) {
|
|
583
|
+
const seen = new Set();
|
|
584
|
+
const wanted = input.accounts.filter((account) => {
|
|
585
|
+
const key = `${account.provider}\0${canonical(account.home)}`;
|
|
586
|
+
if (seen.has(key))
|
|
587
|
+
return false;
|
|
588
|
+
seen.add(key);
|
|
589
|
+
return input.includeOther === true || account.lanes !== false;
|
|
590
|
+
});
|
|
591
|
+
const options = await Promise.all(wanted.map(async (account) => {
|
|
592
|
+
let answer;
|
|
593
|
+
try {
|
|
594
|
+
answer = await input.probe(account.provider, account.home);
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
answer = "no_answer";
|
|
598
|
+
}
|
|
599
|
+
const lane = account.source !== "default" && account.lanes !== false;
|
|
600
|
+
const id = canonicalCodexAccountId(account.home);
|
|
601
|
+
const base = {
|
|
602
|
+
optionId: `${account.provider}:${id}:plan`,
|
|
603
|
+
provider: account.provider,
|
|
604
|
+
account: { id, label: account.label, organization: null },
|
|
605
|
+
tranche: { kind: "plan", scope: null, paid: false },
|
|
606
|
+
leftPercent: null,
|
|
607
|
+
backAt: null,
|
|
608
|
+
reading: { ageSeconds: null, confidence: answer === "signed_in" ? "inferred" : "unknown" },
|
|
609
|
+
usableBy: usableBy(account.provider, "plan", lane),
|
|
610
|
+
models: [],
|
|
611
|
+
};
|
|
612
|
+
if (answer === "not_installed") {
|
|
613
|
+
return {
|
|
614
|
+
...base,
|
|
615
|
+
availability: "not_installed",
|
|
616
|
+
holder: "none",
|
|
617
|
+
reason: "Not installed on this computer.",
|
|
618
|
+
nextStep: { kind: "install", label: `Install ${account.provider}` },
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
if (answer === "signed_out") {
|
|
622
|
+
return {
|
|
623
|
+
...base,
|
|
624
|
+
availability: "needs_sign_in",
|
|
625
|
+
holder: "none",
|
|
626
|
+
reason: "Not signed in on this computer.",
|
|
627
|
+
nextStep: { kind: "sign_in", label: `Sign in to ${account.provider}` },
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
return {
|
|
631
|
+
...base,
|
|
632
|
+
availability: "likely_ready",
|
|
633
|
+
holder: "cli_home",
|
|
634
|
+
reason: answer === "signed_in" ? "Signed in. Reading usage." : "Could not confirm the sign-in yet.",
|
|
635
|
+
nextStep: { kind: "use", label: `Use ${account.label}` },
|
|
636
|
+
};
|
|
637
|
+
}));
|
|
638
|
+
sortOptions(options);
|
|
639
|
+
const work = options.filter((option) => wanted.some((account) => account.lanes !== false && `${account.provider}:${canonicalCodexAccountId(account.home)}:plan` === option.optionId));
|
|
640
|
+
return {
|
|
641
|
+
schemaVersion: AVAILABLE_SCHEMA_VERSION,
|
|
642
|
+
generatedAt: input.now.toISOString(),
|
|
643
|
+
freshness: "stale",
|
|
644
|
+
best: firstRunnable(work)?.optionId ?? null,
|
|
645
|
+
nextBackAt: null,
|
|
646
|
+
options,
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
export const defaultStartCollect = (options, token) => {
|
|
650
|
+
// A test must never start a real provider read from a real binary path.
|
|
651
|
+
if (process.env.VITEST || !process.argv[1])
|
|
652
|
+
return;
|
|
653
|
+
const child = spawn(process.execPath, [process.argv[1], "capacity", "collect-once"], {
|
|
654
|
+
detached: true,
|
|
655
|
+
stdio: "ignore",
|
|
656
|
+
windowsHide: true,
|
|
657
|
+
env: { ...(options.env ?? process.env), HQ_NO_UPDATE_CHECK: "1", [COLLECT_TOKEN_ENV]: token },
|
|
658
|
+
});
|
|
659
|
+
child.on("error", () => undefined);
|
|
660
|
+
child.unref();
|
|
661
|
+
};
|
|
662
|
+
function rootOf(options) {
|
|
663
|
+
return options.root ?? capacityRoot(options.env ?? process.env, options.home);
|
|
664
|
+
}
|
|
665
|
+
function readFileDocument(root) {
|
|
666
|
+
try {
|
|
667
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(root, AVAILABLE_FILE_NAME), "utf8"));
|
|
668
|
+
return parsed?.schemaVersion === AVAILABLE_SCHEMA_VERSION && Array.isArray(parsed.options) ? parsed : null;
|
|
669
|
+
}
|
|
670
|
+
catch {
|
|
671
|
+
return null;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
/** The env variable that hands a collect its mark's token, so it frees only its own mark. */
|
|
675
|
+
export const COLLECT_TOKEN_ENV = "HQ_CAPACITY_COLLECT_TOKEN";
|
|
676
|
+
function readMarkToken(file) {
|
|
677
|
+
try {
|
|
678
|
+
return fs.readFileSync(file, "utf8").trim() || null;
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
return null;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* One background collect at a time across callers, by an exclusive mark that
|
|
686
|
+
* holds a random token and expires. A collector the owner turned off stays off.
|
|
687
|
+
*/
|
|
688
|
+
function startOneCollect(options, nowMs, deps) {
|
|
689
|
+
if (readCollectorMark(options)?.enabled === false)
|
|
690
|
+
return false;
|
|
691
|
+
const root = rootOf(options);
|
|
692
|
+
const mark = path.join(root, COLLECT_MARK);
|
|
693
|
+
try {
|
|
694
|
+
fs.mkdirSync(root, { recursive: true });
|
|
695
|
+
}
|
|
696
|
+
catch {
|
|
697
|
+
// The claim below reports the real failure if the directory cannot be made.
|
|
698
|
+
}
|
|
699
|
+
const token = randomUUID();
|
|
700
|
+
const claim = () => {
|
|
701
|
+
let fd;
|
|
702
|
+
try {
|
|
703
|
+
fd = fs.openSync(mark, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
|
|
704
|
+
}
|
|
705
|
+
catch {
|
|
706
|
+
return false;
|
|
707
|
+
}
|
|
708
|
+
try {
|
|
709
|
+
fs.writeSync(fd, token);
|
|
710
|
+
}
|
|
711
|
+
finally {
|
|
712
|
+
fs.closeSync(fd);
|
|
713
|
+
}
|
|
714
|
+
return true;
|
|
715
|
+
};
|
|
716
|
+
const isStale = (file) => nowMs - fs.statSync(file).mtimeMs > COLLECT_MARK_TTL_MS;
|
|
717
|
+
let claimed = claim();
|
|
718
|
+
if (!claimed) {
|
|
719
|
+
// The holder may have crashed. Rename is atomic, so only one caller moves a
|
|
720
|
+
// given mark away. A caller that saw the old stale mark can still rename a
|
|
721
|
+
// fresh mark another caller has just claimed, so the moved file is checked
|
|
722
|
+
// again: a fresh one is put back (link fails if a newer mark exists) and
|
|
723
|
+
// this caller gives up.
|
|
724
|
+
try {
|
|
725
|
+
if (isStale(mark)) {
|
|
726
|
+
const moved = path.join(root, `${COLLECT_MARK}.${process.pid}.${token}`);
|
|
727
|
+
fs.renameSync(mark, moved);
|
|
728
|
+
let stillStale = true;
|
|
729
|
+
try {
|
|
730
|
+
stillStale = isStale(moved);
|
|
731
|
+
if (!stillStale) {
|
|
732
|
+
try {
|
|
733
|
+
fs.linkSync(moved, mark);
|
|
734
|
+
}
|
|
735
|
+
catch {
|
|
736
|
+
// A newer claim already holds the mark.
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
finally {
|
|
741
|
+
try {
|
|
742
|
+
fs.unlinkSync(moved);
|
|
743
|
+
}
|
|
744
|
+
catch {
|
|
745
|
+
// Already gone.
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
claimed = stillStale && claim();
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
catch {
|
|
752
|
+
claimed = false;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
if (!claimed)
|
|
756
|
+
return false;
|
|
757
|
+
try {
|
|
758
|
+
(deps.startCollect ?? defaultStartCollect)(options, token);
|
|
759
|
+
return true;
|
|
760
|
+
}
|
|
761
|
+
catch {
|
|
762
|
+
// The collect never launched, so free the mark for the next caller.
|
|
763
|
+
releaseCollectMark(options, token);
|
|
764
|
+
return false;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Remove the single-flight mark once a collect finishes, so the next read need
|
|
769
|
+
* not wait out the TTL. The collect subprocess calls this with the token it was
|
|
770
|
+
* started with. A mark with another token belongs to a later collect (this one
|
|
771
|
+
* outlived the TTL and was reclaimed), so it is left alone. With no token
|
|
772
|
+
* nothing is removed.
|
|
773
|
+
*/
|
|
774
|
+
export function releaseCollectMark(options, token) {
|
|
775
|
+
if (!token)
|
|
776
|
+
return;
|
|
777
|
+
const mark = path.join(rootOf(options), COLLECT_MARK);
|
|
778
|
+
if (readMarkToken(mark) !== token)
|
|
779
|
+
return;
|
|
780
|
+
try {
|
|
781
|
+
fs.unlinkSync(mark);
|
|
782
|
+
}
|
|
783
|
+
catch {
|
|
784
|
+
// Already gone; the TTL still covers a crashed collect.
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
function withFreshness(document, nowMs) {
|
|
788
|
+
const at = Date.parse(document.generatedAt);
|
|
789
|
+
const stale = !Number.isFinite(at) || nowMs - at > CAPACITY_STALE_MS;
|
|
790
|
+
return stale ? { ...document, freshness: "stale" } : document;
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* True when now.json carries a strictly newer reading than the cached
|
|
794
|
+
* available.json. Reads now.json raw (no rebuild) and never throws: a missing or
|
|
795
|
+
* unreadable now.json leaves the cached file in charge.
|
|
796
|
+
*/
|
|
797
|
+
function nowIsNewerThan(options, root, fileGeneratedAt) {
|
|
798
|
+
let nowGeneratedAt;
|
|
799
|
+
try {
|
|
800
|
+
nowGeneratedAt = Date.parse(readNow({ ...options, root }).generatedAt);
|
|
801
|
+
}
|
|
802
|
+
catch {
|
|
803
|
+
return false;
|
|
804
|
+
}
|
|
805
|
+
const fileAt = Date.parse(fileGeneratedAt);
|
|
806
|
+
if (!Number.isFinite(nowGeneratedAt))
|
|
807
|
+
return false;
|
|
808
|
+
if (!Number.isFinite(fileAt))
|
|
809
|
+
return true;
|
|
810
|
+
return nowGeneratedAt > fileAt;
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* A document built from now.json, or null. Null when now.json cannot be read,
|
|
814
|
+
* and when the registry cannot be read: a roster of only the default homes would
|
|
815
|
+
* drop registry accounts and could make a turned-off default home best.
|
|
816
|
+
*/
|
|
817
|
+
function buildFromNow(options, now, includeOther) {
|
|
818
|
+
const root = rootOf(options);
|
|
819
|
+
const accounts = registryRoster(options);
|
|
820
|
+
if (!accounts)
|
|
821
|
+
return null;
|
|
822
|
+
let view;
|
|
823
|
+
try {
|
|
824
|
+
view = readCurrentNow({ ...options, root });
|
|
825
|
+
}
|
|
826
|
+
catch {
|
|
827
|
+
return null;
|
|
828
|
+
}
|
|
829
|
+
return buildAvailableDocument({
|
|
830
|
+
view,
|
|
831
|
+
accounts,
|
|
832
|
+
now: new Date(Date.parse(view.generatedAt) || now.getTime()),
|
|
833
|
+
collectorEnabled: readCollectorMark({ ...options, root })?.enabled ?? null,
|
|
834
|
+
includeOther,
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
/** What `hq capacity available` prints. Never throws for a bad or missing ledger. */
|
|
838
|
+
export async function readAvailable(input, deps = {}) {
|
|
839
|
+
const { options } = input;
|
|
840
|
+
const now = options.now ? options.now() : new Date();
|
|
841
|
+
const nowMs = now.getTime();
|
|
842
|
+
const root = rootOf(options);
|
|
843
|
+
const includeOther = input.includeOther === true;
|
|
844
|
+
// now.json is the source of truth; available.json is its cache. A rebuild
|
|
845
|
+
// that cannot read the registry keeps the last file, so the file can lag
|
|
846
|
+
// behind now.json. A reader that can read the registry builds from now.json
|
|
847
|
+
// whenever now.json is newer. One that cannot keeps the file, which still has
|
|
848
|
+
// every account, and marks it stale because newer figures exist.
|
|
849
|
+
const load = () => {
|
|
850
|
+
const file = includeOther ? null : readFileDocument(root);
|
|
851
|
+
if (file && !nowIsNewerThan(options, root, file.generatedAt))
|
|
852
|
+
return file;
|
|
853
|
+
const built = buildFromNow(options, now, includeOther);
|
|
854
|
+
if (built)
|
|
855
|
+
return built;
|
|
856
|
+
return file ? { ...file, freshness: "stale" } : null;
|
|
857
|
+
};
|
|
858
|
+
const document = load();
|
|
859
|
+
if (!document) {
|
|
860
|
+
// No ledger yet: kick off one background collect so the next read has data,
|
|
861
|
+
// then answer now from each tool's own status command.
|
|
862
|
+
startOneCollect(options, nowMs, deps);
|
|
863
|
+
const roster = registryRoster(options);
|
|
864
|
+
const answer = await buildAvailableFromStatus({
|
|
865
|
+
accounts: roster ?? listCapacityAccounts({ env: options.env ?? process.env, home: options.home ?? (options.env ?? process.env).HOME, config: null }),
|
|
866
|
+
now,
|
|
867
|
+
probe: deps.probe ?? defaultStatusProbe,
|
|
868
|
+
includeOther,
|
|
869
|
+
});
|
|
870
|
+
// Without the registry, a default home may be one the owner turned off for
|
|
871
|
+
// work, so none of them is named best.
|
|
872
|
+
return roster ? answer : { ...answer, best: null };
|
|
873
|
+
}
|
|
874
|
+
const at = Date.parse(document.generatedAt);
|
|
875
|
+
const stale = !Number.isFinite(at) || nowMs - at > CAPACITY_STALE_MS;
|
|
876
|
+
if (!stale && input.fresh !== true)
|
|
877
|
+
return document;
|
|
878
|
+
const started = startOneCollect(options, nowMs, deps);
|
|
879
|
+
if (input.fresh !== true)
|
|
880
|
+
return withFreshness(document, nowMs);
|
|
881
|
+
const clock = deps.clock ?? Date.now;
|
|
882
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
883
|
+
const deadline = clock() + FRESH_WAIT_MS;
|
|
884
|
+
while (clock() < deadline) {
|
|
885
|
+
await sleep(FRESH_POLL_MS);
|
|
886
|
+
const next = load();
|
|
887
|
+
if (next && next.generatedAt !== document.generatedAt)
|
|
888
|
+
return withFreshness(next, nowMs);
|
|
889
|
+
}
|
|
890
|
+
// The wait ran out. The collect may still land, so say so if it is running.
|
|
891
|
+
return { ...document, freshness: started ? "refreshing" : stale ? "stale" : document.freshness };
|
|
892
|
+
}
|
|
893
|
+
export function formatAvailableText(document) {
|
|
894
|
+
if (document.options.length === 0)
|
|
895
|
+
return "No AI found on this computer.";
|
|
896
|
+
const lines = document.options.map((option) => {
|
|
897
|
+
const mark = option.optionId === document.best ? "*" : " ";
|
|
898
|
+
const left = option.leftPercent === null ? "" : ` ${option.leftPercent}% left`;
|
|
899
|
+
const org = option.account.organization ? ` (${option.account.organization})` : "";
|
|
900
|
+
const paid = option.tranche.paid ? " [paid]" : "";
|
|
901
|
+
return `${mark} ${option.provider} ${option.account.label}${org}${paid}: ${option.availability}${left}. ${option.reason}`;
|
|
902
|
+
});
|
|
903
|
+
return lines.join("\n");
|
|
904
|
+
}
|
|
905
|
+
//# sourceMappingURL=available.js.map
|