pi-spine 2.12.3 → 2.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -55,6 +55,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
|
|
|
55
55
|
- **Do not** execute tasks outside the approved manifest scope
|
|
56
56
|
- **Never** start Phase 4 (execute) without **recorded scope approval** — the release manifest must show `Operator approved scope: yes` from the Phase 2 gate. Refuse the first wave when approval is missing or `no` (F1, [#249](https://github.com/beettlle/pi-spine/issues/249))
|
|
57
57
|
- **Never** mid-release-edit `.spine/spine-config.json` agent pins (`agents.worker.model` / `agents.reviewer.model`) while a batch is running or integrated work is still unpublished. Pin **one worker** per release; escalate models **only** on content/contract failure — never on quota/403 or launch storms, which make releases worse (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). To override mid-release, first record the reason and date in the release manifest
|
|
58
|
+
- **Heed** the doctor/preflight **quota-risk advisory** ([#251](https://github.com/beettlle/pi-spine/issues/251)): `spine doctor` surfaces `ok: true, warning: true` when escalate/hard worker pins target quota-constrained pools without headroom evidence, or recent run-metrics show launch-storm / quota-abort patterns. It is advisory only — never fails preflight — and does not change the mid-release pin-thrash ban above
|
|
58
59
|
- **Always** push/sync `main` to `origin` after each land loop once the post-integrate regression gate is green — do not let `main` drift far ahead of `origin` during a release (F8, [#249](https://github.com/beettlle/pi-spine/issues/249))
|
|
59
60
|
- **Do not** start a second batch while another batch is **running** on this repo
|
|
60
61
|
- **Never** background `spine batch resume --attached` or `resume --attached --force` ([#163](https://github.com/beettlle/pi-spine/issues/163))
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Quota-risk advisory doctor check (GitHub #251, SP-700).
|
|
4
|
+
*
|
|
5
|
+
* Warns when worker pins that matter for escalation (base worker, active
|
|
6
|
+
* profile worker, or the `escalatePolicy.toProfile` target worker) point at
|
|
7
|
+
* known quota-constrained provider pools without live/estimate headroom
|
|
8
|
+
* evidence. Optionally surfaces recent launch-storm / quota-abort patterns
|
|
9
|
+
* from run-metrics when metrics lines are supplied.
|
|
10
|
+
*
|
|
11
|
+
* This check is advisory only: it always returns `ok: true` (with
|
|
12
|
+
* `warning: true` when risk is detected) so doctor/preflight stay
|
|
13
|
+
* non-blocking. Live probes are never run from doctor — probe results are an
|
|
14
|
+
* injectable input; when probes/auth are absent the check degrades closed
|
|
15
|
+
* (warns) instead of claiming headroom it cannot prove.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
|
|
19
|
+
|
|
20
|
+
/** Default window for launch-storm / quota-abort signal detection. */
|
|
21
|
+
const DEFAULT_SIGNAL_WINDOW_MS = 60 * 60 * 1000;
|
|
22
|
+
/** Failed tasks under this duration count toward a launch storm. */
|
|
23
|
+
const LAUNCH_STORM_MAX_DURATION_MS = 5 * 60 * 1000;
|
|
24
|
+
/** Minimum failed short tasks inside the window to flag a launch storm. */
|
|
25
|
+
const LAUNCH_STORM_MIN_FAILURES = 3;
|
|
26
|
+
|
|
27
|
+
export const QUOTA_RISK_CHECK_LABEL = "quota risk: escalate/hard worker pins (#251)";
|
|
28
|
+
export const QUOTA_RISK_SUGGESTED_COMMAND = "spine metrics quota";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @typedef {object} QuotaPinTarget
|
|
32
|
+
* @property {string} model
|
|
33
|
+
* @property {string} poolId
|
|
34
|
+
* @property {string} source Human-readable origin of the pin.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Collect worker model pins that matter for escalation risk: the base
|
|
39
|
+
* worker pin, the active-profile worker pin, and the escalate-policy target
|
|
40
|
+
* profile worker pin. Only pins resolving to a known quota pool are kept.
|
|
41
|
+
*
|
|
42
|
+
* @param {object} [config]
|
|
43
|
+
* @returns {QuotaPinTarget[]}
|
|
44
|
+
*/
|
|
45
|
+
export function collectQuotaPinTargets(config = {}) {
|
|
46
|
+
const agents = config?.agents;
|
|
47
|
+
if (!agents || typeof agents !== "object") return [];
|
|
48
|
+
|
|
49
|
+
/** @type {Array<{ model: unknown, source: string }>} */
|
|
50
|
+
const candidates = [
|
|
51
|
+
{ model: agents.worker?.model, source: "agents.worker.model" },
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
const activeProfile = typeof agents.activeProfile === "string" ? agents.activeProfile.trim() : "";
|
|
55
|
+
if (activeProfile && agents.profiles?.[activeProfile]) {
|
|
56
|
+
candidates.push({
|
|
57
|
+
model: agents.profiles[activeProfile]?.worker?.model,
|
|
58
|
+
source: `agents.profiles.${activeProfile}.worker.model (active profile)`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const escalate = agents.escalatePolicy;
|
|
63
|
+
const escalateTarget =
|
|
64
|
+
escalate && typeof escalate === "object" && escalate.enabled !== false
|
|
65
|
+
? String(escalate.toProfile ?? "").trim()
|
|
66
|
+
: "";
|
|
67
|
+
if (escalateTarget && agents.profiles?.[escalateTarget]) {
|
|
68
|
+
candidates.push({
|
|
69
|
+
model: agents.profiles[escalateTarget]?.worker?.model,
|
|
70
|
+
source: `agents.profiles.${escalateTarget}.worker.model (escalate target)`,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @type {QuotaPinTarget[]} */
|
|
75
|
+
const targets = [];
|
|
76
|
+
const seen = new Set();
|
|
77
|
+
for (const candidate of candidates) {
|
|
78
|
+
if (typeof candidate.model !== "string") continue;
|
|
79
|
+
const model = candidate.model.trim();
|
|
80
|
+
if (!model || model === "inherit") continue;
|
|
81
|
+
const poolId = resolvePoolId(model);
|
|
82
|
+
if (poolId === "unknown") continue;
|
|
83
|
+
const key = `${poolId}::${model}`;
|
|
84
|
+
if (seen.has(key)) continue;
|
|
85
|
+
seen.add(key);
|
|
86
|
+
targets.push({ model, poolId, source: candidate.source });
|
|
87
|
+
}
|
|
88
|
+
return targets;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Evaluate headroom evidence for one pool from an optional probe result.
|
|
93
|
+
* Degrades closed: absent probes/auth mean "no headroom evidence", never an
|
|
94
|
+
* invented remaining percentage.
|
|
95
|
+
*
|
|
96
|
+
* @param {QuotaPinTarget} target
|
|
97
|
+
* @param {import("../metrics/quota-probes.mjs").ProbeResult | undefined} probe
|
|
98
|
+
* @returns {{ hasHeadroom: boolean, reason: string }}
|
|
99
|
+
*/
|
|
100
|
+
function evaluateHeadroom(target, probe) {
|
|
101
|
+
const pin = `${target.source} → ${target.model} (pool: ${target.poolId})`;
|
|
102
|
+
|
|
103
|
+
if (probe?.source === "live") {
|
|
104
|
+
const usage = probe.usage && typeof probe.usage === "object" ? probe.usage : {};
|
|
105
|
+
if (Number.isFinite(probe.limit) && Number.isFinite(usage.tokensOut)) {
|
|
106
|
+
const headroom = probe.limit - usage.tokensOut;
|
|
107
|
+
if (headroom > 0) {
|
|
108
|
+
return { hasHeadroom: true, reason: `${pin} — live probe reports headroom` };
|
|
109
|
+
}
|
|
110
|
+
return { hasHeadroom: false, reason: `${pin} — live probe reports quota exhausted` };
|
|
111
|
+
}
|
|
112
|
+
if (Number.isFinite(usage.estimatedUsd)) {
|
|
113
|
+
if (usage.estimatedUsd > 0) {
|
|
114
|
+
return { hasHeadroom: true, reason: `${pin} — live probe reports positive balance` };
|
|
115
|
+
}
|
|
116
|
+
return { hasHeadroom: false, reason: `${pin} — live probe reports zero/negative balance` };
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
hasHeadroom: true,
|
|
120
|
+
reason: `${pin} — live probe reachable, provider reported no explicit limit`,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
hasHeadroom: false,
|
|
126
|
+
reason: `${pin} — quota-constrained pool with no live/estimate headroom evidence (probe/auth absent)`,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Detect recent launch-storm and quota-abort signals in task metric records.
|
|
132
|
+
* Pure heuristic over injected records; nothing is fabricated when fields are
|
|
133
|
+
* missing.
|
|
134
|
+
*
|
|
135
|
+
* @param {object[]} [metricsLines]
|
|
136
|
+
* @param {object} [options]
|
|
137
|
+
* @param {number | string | Date} [options.now]
|
|
138
|
+
* @param {number} [options.windowMs]
|
|
139
|
+
* @returns {string[]}
|
|
140
|
+
*/
|
|
141
|
+
export function detectQuotaRiskSignals(metricsLines, { now = Date.now(), windowMs = DEFAULT_SIGNAL_WINDOW_MS } = {}) {
|
|
142
|
+
if (!Array.isArray(metricsLines) || metricsLines.length === 0) return [];
|
|
143
|
+
|
|
144
|
+
const nowMs = new Date(now).getTime();
|
|
145
|
+
if (!Number.isFinite(nowMs)) return [];
|
|
146
|
+
|
|
147
|
+
const windowStart = nowMs - windowMs;
|
|
148
|
+
const records = metricsLines.filter(
|
|
149
|
+
(line) => line && typeof line === "object" && line.recordType === "task",
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
let shortFailures = 0;
|
|
153
|
+
let quotaAborts = 0;
|
|
154
|
+
for (const record of records) {
|
|
155
|
+
if (record.outcome !== "failed") continue;
|
|
156
|
+
const startedMs = new Date(record.startedAt ?? 0).getTime();
|
|
157
|
+
if (!Number.isFinite(startedMs) || startedMs < windowStart) continue;
|
|
158
|
+
|
|
159
|
+
const haystack = [record.diagnosis, record.failureKind, record.exitReason]
|
|
160
|
+
.filter((value) => typeof value === "string")
|
|
161
|
+
.join(" ")
|
|
162
|
+
.toLowerCase();
|
|
163
|
+
if (haystack.includes("quota") || haystack.includes("rate limit") || haystack.includes("429")) {
|
|
164
|
+
quotaAborts += 1;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
if (Number.isFinite(record.durationMs) && record.durationMs <= LAUNCH_STORM_MAX_DURATION_MS) {
|
|
168
|
+
shortFailures += 1;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** @type {string[]} */
|
|
173
|
+
const signals = [];
|
|
174
|
+
if (quotaAborts > 0) {
|
|
175
|
+
signals.push(`${quotaAborts} recent quota-abort task failure(s) in run-metrics`);
|
|
176
|
+
}
|
|
177
|
+
if (shortFailures >= LAUNCH_STORM_MIN_FAILURES) {
|
|
178
|
+
signals.push(
|
|
179
|
+
`${shortFailures} short-lived task failure(s) in the last hour — possible launch storm`,
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
return signals;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Build the advisory quota-risk doctor check.
|
|
187
|
+
*
|
|
188
|
+
* @param {object} [options]
|
|
189
|
+
* @param {object} [options.config] Resolved spine config.
|
|
190
|
+
* @param {Record<string, import("../metrics/quota-probes.mjs").ProbeResult>} [options.probeResults]
|
|
191
|
+
* Optional live probe results keyed by pool id; doctor never runs probes itself.
|
|
192
|
+
* @param {object[]} [options.metricsLines] Optional parsed run-metrics records.
|
|
193
|
+
* @param {number | string | Date} [options.now]
|
|
194
|
+
* @returns {{ label: string, ok: true, warning?: boolean, detail: string, suggestedCommand?: string }}
|
|
195
|
+
*/
|
|
196
|
+
export function buildQuotaRiskDoctorCheck({ config = {}, probeResults, metricsLines, now } = {}) {
|
|
197
|
+
const targets = collectQuotaPinTargets(config);
|
|
198
|
+
const probes = probeResults && typeof probeResults === "object" ? probeResults : {};
|
|
199
|
+
|
|
200
|
+
/** @type {string[]} */
|
|
201
|
+
const risks = [];
|
|
202
|
+
for (const target of targets) {
|
|
203
|
+
const { hasHeadroom, reason } = evaluateHeadroom(target, probes[target.poolId]);
|
|
204
|
+
if (!hasHeadroom) risks.push(reason);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const signals = detectQuotaRiskSignals(metricsLines, { now });
|
|
208
|
+
risks.push(...signals);
|
|
209
|
+
|
|
210
|
+
if (risks.length === 0) {
|
|
211
|
+
const detail =
|
|
212
|
+
targets.length === 0
|
|
213
|
+
? "no escalate/hard worker pins on quota-constrained pools"
|
|
214
|
+
: `${targets.length} quota-pool pin(s) with headroom evidence`;
|
|
215
|
+
return {
|
|
216
|
+
label: QUOTA_RISK_CHECK_LABEL,
|
|
217
|
+
ok: true,
|
|
218
|
+
detail,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
label: QUOTA_RISK_CHECK_LABEL,
|
|
224
|
+
ok: true,
|
|
225
|
+
warning: true,
|
|
226
|
+
detail: risks.join("; "),
|
|
227
|
+
suggestedCommand: QUOTA_RISK_SUGGESTED_COMMAND,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
@@ -33,6 +33,8 @@ import { buildAgentModelIdsDoctorCheck } from "./agent-models.mjs";
|
|
|
33
33
|
import { buildPiExtensionConflictDoctorCheck } from "./pi-extension-conflict.mjs";
|
|
34
34
|
import { buildSupervisorConfigDoctorCheck } from "./supervisor.mjs";
|
|
35
35
|
import { buildAttachedOrphanRiskDoctorCheck } from "./attached-orphan-risk.mjs";
|
|
36
|
+
import { buildQuotaRiskDoctorCheck } from "./quota-risk.mjs";
|
|
37
|
+
import { metricsFilePath, readMetricsLines } from "../batch/metrics.mjs";
|
|
36
38
|
import {
|
|
37
39
|
buildCheckoutVersionSkewDoctorCheck,
|
|
38
40
|
buildDuplicateInstallDoctorCheck,
|
|
@@ -408,6 +410,22 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
|
|
|
408
410
|
for (const testingCheck of buildTestingEvidenceDoctorChecks(configResult.config)) {
|
|
409
411
|
checks.push(testingCheck);
|
|
410
412
|
}
|
|
413
|
+
let quotaMetricsLines;
|
|
414
|
+
try {
|
|
415
|
+
quotaMetricsLines = readMetricsLines(
|
|
416
|
+
metricsFilePath(projectRoot, configResult.config),
|
|
417
|
+
{ skipInvalid: true },
|
|
418
|
+
);
|
|
419
|
+
} catch {
|
|
420
|
+
// Unreadable metrics degrade to pin-only evaluation; the check still warns on absent headroom.
|
|
421
|
+
quotaMetricsLines = undefined;
|
|
422
|
+
}
|
|
423
|
+
checks.push(
|
|
424
|
+
buildQuotaRiskDoctorCheck({
|
|
425
|
+
config: configResult.config,
|
|
426
|
+
metricsLines: quotaMetricsLines,
|
|
427
|
+
}),
|
|
428
|
+
);
|
|
411
429
|
const concurrentDevCheck = buildConcurrentDevDoctorCheck({
|
|
412
430
|
projectRoot,
|
|
413
431
|
config: configResult.config,
|
|
@@ -14,6 +14,12 @@
|
|
|
14
14
|
* Cursor is only probed when the auth file contains an explicit admin key
|
|
15
15
|
* (`type: "admin_key"` or a dedicated `adminKey` field). Regular Cursor API
|
|
16
16
|
* keys are not used and no undocumented dashboard HTML is scraped.
|
|
17
|
+
*
|
|
18
|
+
* Anthropic is only probed with an explicit Admin key (`type: "admin_key"`
|
|
19
|
+
* or a dedicated `adminKey` field). Regular inference keys
|
|
20
|
+
* (`sk-ant-api...`) are never sent to the Admin API. GitHub Copilot is only
|
|
21
|
+
* probed when the auth entry carries a PAT plus an explicit org or enterprise
|
|
22
|
+
* context; user-level entries without that scope degrade to `absent`.
|
|
17
23
|
*/
|
|
18
24
|
|
|
19
25
|
import fs from "node:fs";
|
|
@@ -26,12 +32,17 @@ const PROBE_URLS = {
|
|
|
26
32
|
zai: "https://api.z.ai/api/monitor/usage/quota/limit",
|
|
27
33
|
"kimi-coding": "https://api.moonshot.ai/v1/users/me/balance",
|
|
28
34
|
cursor: "https://api.cursor.com/teams/daily-usage-data",
|
|
35
|
+
anthropic: "https://api.anthropic.com/v1/organizations/usage_report/messages",
|
|
29
36
|
};
|
|
30
37
|
|
|
38
|
+
const GITHUB_API_BASE = "https://api.github.com";
|
|
39
|
+
|
|
31
40
|
export const PROBE_POOLS = {
|
|
32
41
|
zai: "zai",
|
|
33
42
|
kimiCoding: "kimi-coding",
|
|
34
43
|
cursor: "cursor",
|
|
44
|
+
anthropic: "anthropic",
|
|
45
|
+
githubCopilot: "github-copilot",
|
|
35
46
|
};
|
|
36
47
|
|
|
37
48
|
/**
|
|
@@ -103,21 +114,59 @@ function hasCursorAdminKey(auth) {
|
|
|
103
114
|
}
|
|
104
115
|
|
|
105
116
|
/**
|
|
106
|
-
*
|
|
107
|
-
*
|
|
117
|
+
* Return the explicit Anthropic Admin key from the auth file, or `undefined`
|
|
118
|
+
* when only a regular inference key is present. The Admin API rejects
|
|
119
|
+
* inference keys, so they are never used for the probe.
|
|
120
|
+
*
|
|
121
|
+
* @param {object | null} auth
|
|
122
|
+
* @returns {string | undefined}
|
|
123
|
+
*/
|
|
124
|
+
function getAnthropicAdminKey(auth) {
|
|
125
|
+
const entry = auth?.anthropic;
|
|
126
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
127
|
+
if (entry.type === "admin_key" && typeof entry.key === "string" && entry.key.length > 0) {
|
|
128
|
+
return entry.key;
|
|
129
|
+
}
|
|
130
|
+
if (typeof entry.adminKey === "string" && entry.adminKey.length > 0) return entry.adminKey;
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Return the GitHub Copilot billing probe context (PAT plus an explicit org
|
|
136
|
+
* or enterprise scope), or `undefined` when either is missing. The billing
|
|
137
|
+
* endpoints are only exposed at org/enterprise level, so user-level entries
|
|
138
|
+
* without that context fail closed.
|
|
139
|
+
*
|
|
140
|
+
* @param {object | null} auth
|
|
141
|
+
* @returns {{ key: string, url: string } | undefined}
|
|
142
|
+
*/
|
|
143
|
+
function getCopilotBillingContext(auth) {
|
|
144
|
+
const entry = auth?.["github-copilot"];
|
|
145
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
146
|
+
const key = typeof entry.key === "string" && entry.key.length > 0 ? entry.key : undefined;
|
|
147
|
+
if (!key) return undefined;
|
|
148
|
+
if (typeof entry.org === "string" && entry.org.length > 0) {
|
|
149
|
+
return { key, url: `${GITHUB_API_BASE}/orgs/${encodeURIComponent(entry.org)}/copilot/billing` };
|
|
150
|
+
}
|
|
151
|
+
if (typeof entry.enterprise === "string" && entry.enterprise.length > 0) {
|
|
152
|
+
return { key, url: `${GITHUB_API_BASE}/enterprises/${encodeURIComponent(entry.enterprise)}/copilot/billing` };
|
|
153
|
+
}
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Make a JSON GET request with arbitrary headers, returning `null` on any
|
|
159
|
+
* failure so adapters remain fail-closed.
|
|
108
160
|
*
|
|
109
161
|
* @param {string} url
|
|
110
|
-
* @param {string}
|
|
162
|
+
* @param {Record<string, string>} headers
|
|
111
163
|
* @param {typeof globalThis.fetch} fetch
|
|
112
164
|
* @returns {Promise<object | null>}
|
|
113
165
|
*/
|
|
114
|
-
async function
|
|
166
|
+
async function fetchJsonWithHeaders(url, headers, fetch) {
|
|
115
167
|
const response = await fetch(url, {
|
|
116
168
|
method: "GET",
|
|
117
|
-
headers: {
|
|
118
|
-
Authorization: `Bearer ${key}`,
|
|
119
|
-
Accept: "application/json",
|
|
120
|
-
},
|
|
169
|
+
headers: { Accept: "application/json", ...headers },
|
|
121
170
|
});
|
|
122
171
|
if (!response.ok) return null;
|
|
123
172
|
const text = await response.text();
|
|
@@ -129,6 +178,19 @@ async function fetchJsonWithBearer(url, key, fetch) {
|
|
|
129
178
|
}
|
|
130
179
|
}
|
|
131
180
|
|
|
181
|
+
/**
|
|
182
|
+
* Make a JSON GET request with a Bearer token, returning `null` on any failure
|
|
183
|
+
* so adapters remain fail-closed.
|
|
184
|
+
*
|
|
185
|
+
* @param {string} url
|
|
186
|
+
* @param {string} key
|
|
187
|
+
* @param {typeof globalThis.fetch} fetch
|
|
188
|
+
* @returns {Promise<object | null>}
|
|
189
|
+
*/
|
|
190
|
+
async function fetchJsonWithBearer(url, key, fetch) {
|
|
191
|
+
return fetchJsonWithHeaders(url, { Authorization: `Bearer ${key}` }, fetch);
|
|
192
|
+
}
|
|
193
|
+
|
|
132
194
|
/**
|
|
133
195
|
* Extract a numeric limit from a provider response when it is explicitly
|
|
134
196
|
* present; otherwise return `undefined` so the snapshot does not invent one.
|
|
@@ -280,6 +342,96 @@ async function probeCursor(auth, fetch) {
|
|
|
280
342
|
}
|
|
281
343
|
}
|
|
282
344
|
|
|
345
|
+
/**
|
|
346
|
+
* Anthropic probe — only runs when an explicit Admin key is present in
|
|
347
|
+
* `auth.json`. Regular inference keys (`type: "api_key"`, `sk-ant-api...`)
|
|
348
|
+
* are never sent to the Admin API.
|
|
349
|
+
*
|
|
350
|
+
* Expected shape (used by mocked tests): `{ used: number }` or a `data`
|
|
351
|
+
* array whose entries carry `tokens` fields. A numeric limit is only
|
|
352
|
+
* attached when the response explicitly includes one.
|
|
353
|
+
*
|
|
354
|
+
* @param {object | null} auth
|
|
355
|
+
* @param {typeof globalThis.fetch} fetch
|
|
356
|
+
* @returns {Promise<ProbeResult>}
|
|
357
|
+
*/
|
|
358
|
+
async function probeAnthropic(auth, fetch) {
|
|
359
|
+
const key = getAnthropicAdminKey(auth);
|
|
360
|
+
if (!key) return { poolId: "anthropic", source: "absent" };
|
|
361
|
+
|
|
362
|
+
try {
|
|
363
|
+
const data = await fetchJsonWithHeaders(
|
|
364
|
+
PROBE_URLS.anthropic,
|
|
365
|
+
{ "x-api-key": key, "anthropic-version": "2023-06-01" },
|
|
366
|
+
fetch,
|
|
367
|
+
);
|
|
368
|
+
if (!data) return { poolId: "anthropic", source: "absent" };
|
|
369
|
+
|
|
370
|
+
/** @type {PoolUsage} */
|
|
371
|
+
const usage = { taskCount: 0, durationMs: 0 };
|
|
372
|
+
const used = extractNumber(data, ["used", "used_tokens", "total_tokens"])
|
|
373
|
+
?? extractNumber(data.data, ["used", "used_tokens", "total_tokens"]);
|
|
374
|
+
if (used !== undefined) usage.tokensOut = used;
|
|
375
|
+
|
|
376
|
+
const limit =
|
|
377
|
+
extractLimit(data, ["total", "limit"]) ??
|
|
378
|
+
extractLimit(data.data, ["total", "limit"]);
|
|
379
|
+
|
|
380
|
+
const result = { poolId: "anthropic", source: "live", usage };
|
|
381
|
+
if (limit !== undefined) result.limit = limit;
|
|
382
|
+
return result;
|
|
383
|
+
} catch (error) {
|
|
384
|
+
return { poolId: "anthropic", source: "absent", error };
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* GitHub Copilot probe — only runs when the auth entry carries a PAT plus
|
|
390
|
+
* an explicit org or enterprise context. User-level entries without that
|
|
391
|
+
* scope fail closed because the billing endpoints are org/enterprise-only.
|
|
392
|
+
*
|
|
393
|
+
* Expected shape (used by mocked tests): `{ used: number }` or
|
|
394
|
+
* `{ usage: { used: number } }`. Seat-only billing payloads still count as
|
|
395
|
+
* live but contribute no usage numbers. A numeric limit is only attached
|
|
396
|
+
* when the response explicitly includes one.
|
|
397
|
+
*
|
|
398
|
+
* @param {object | null} auth
|
|
399
|
+
* @param {typeof globalThis.fetch} fetch
|
|
400
|
+
* @returns {Promise<ProbeResult>}
|
|
401
|
+
*/
|
|
402
|
+
async function probeGitHubCopilot(auth, fetch) {
|
|
403
|
+
const context = getCopilotBillingContext(auth);
|
|
404
|
+
if (!context) return { poolId: "github-copilot", source: "absent" };
|
|
405
|
+
|
|
406
|
+
try {
|
|
407
|
+
const data = await fetchJsonWithHeaders(
|
|
408
|
+
context.url,
|
|
409
|
+
{
|
|
410
|
+
Authorization: `Bearer ${context.key}`,
|
|
411
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
412
|
+
},
|
|
413
|
+
fetch,
|
|
414
|
+
);
|
|
415
|
+
if (!data) return { poolId: "github-copilot", source: "absent" };
|
|
416
|
+
|
|
417
|
+
/** @type {PoolUsage} */
|
|
418
|
+
const usage = { taskCount: 0, durationMs: 0 };
|
|
419
|
+
// Seat counts are deliberately not mapped into taskCount: seats are not
|
|
420
|
+
// tasks and conflating them would invent usage the API never reported.
|
|
421
|
+
const used = extractNumber(data, ["used", "used_premium_requests", "total_used"])
|
|
422
|
+
?? extractNumber(data.usage, ["used", "total"]);
|
|
423
|
+
if (used !== undefined) usage.tokensOut = used;
|
|
424
|
+
|
|
425
|
+
const limit = extractLimit(data, ["limit", "seat_limit"]);
|
|
426
|
+
|
|
427
|
+
const result = { poolId: "github-copilot", source: "live", usage };
|
|
428
|
+
if (limit !== undefined) result.limit = limit;
|
|
429
|
+
return result;
|
|
430
|
+
} catch (error) {
|
|
431
|
+
return { poolId: "github-copilot", source: "absent", error };
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
283
435
|
/**
|
|
284
436
|
* Run the optional provider probes and return a map keyed by pool id.
|
|
285
437
|
*
|
|
@@ -292,7 +444,13 @@ async function probeCursor(auth, fetch) {
|
|
|
292
444
|
export async function runQuotaProbes({
|
|
293
445
|
authPath = DEFAULT_AUTH_PATH,
|
|
294
446
|
fetch = globalThis.fetch,
|
|
295
|
-
providers = [
|
|
447
|
+
providers = [
|
|
448
|
+
PROBE_POOLS.zai,
|
|
449
|
+
PROBE_POOLS.kimiCoding,
|
|
450
|
+
PROBE_POOLS.cursor,
|
|
451
|
+
PROBE_POOLS.anthropic,
|
|
452
|
+
PROBE_POOLS.githubCopilot,
|
|
453
|
+
],
|
|
296
454
|
} = {}) {
|
|
297
455
|
const auth = loadAuthCredentials(authPath);
|
|
298
456
|
/** @type {Record<string, ProbeResult>} */
|
|
@@ -305,6 +463,10 @@ export async function runQuotaProbes({
|
|
|
305
463
|
results["kimi-coding"] = await probeKimi(auth, fetch);
|
|
306
464
|
} else if (provider === PROBE_POOLS.cursor) {
|
|
307
465
|
results.cursor = await probeCursor(auth, fetch);
|
|
466
|
+
} else if (provider === PROBE_POOLS.anthropic) {
|
|
467
|
+
results.anthropic = await probeAnthropic(auth, fetch);
|
|
468
|
+
} else if (provider === PROBE_POOLS.githubCopilot) {
|
|
469
|
+
results["github-copilot"] = await probeGitHubCopilot(auth, fetch);
|
|
308
470
|
}
|
|
309
471
|
}
|
|
310
472
|
|
|
@@ -26,7 +26,7 @@ import { metricsFilePath, readMetricsLines } from "../batch/metrics.mjs";
|
|
|
26
26
|
* pool because provider-level quotas (e.g. Z.ai, Google, Kimi) are typically
|
|
27
27
|
* account- or key-wide, not model-wide.
|
|
28
28
|
*/
|
|
29
|
-
const POOL_PREFIXES = new Set(["zai", "kimi-coding", "google", "cursor"]);
|
|
29
|
+
const POOL_PREFIXES = new Set(["zai", "kimi-coding", "google", "cursor", "anthropic", "github-copilot"]);
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
32
|
* Resolves a model identifier to a shared quota pool id.
|