@moxt-ai/mobius 0.0.455 → 0.0.456
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/dist/{chunk-TPFOWHSZ.js → chunk-GUE7ZQI6.js} +2433 -201
- package/dist/{chunk-TPFOWHSZ.js.map → chunk-GUE7ZQI6.js.map} +4 -4
- package/dist/{chunk-ZNK44CJT.js → chunk-H3JQ3BX5.js} +2 -2
- package/dist/{chunk-ZNK44CJT.js.map → chunk-H3JQ3BX5.js.map} +1 -1
- package/dist/{cli-LYAYRPGJ.js → cli-E4GLG6NB.js} +3 -3
- package/dist/cli.js +2 -2
- package/dist/engine/acp/adapter/antigravity/adapter.d.ts +53 -0
- package/dist/engine/acp/adapter/antigravity/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/antigravity/adapter.js +7 -0
- package/dist/engine/acp/adapter/antigravity/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/claude/adapter.d.ts +53 -0
- package/dist/engine/acp/adapter/claude/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/claude/adapter.js +8 -1
- package/dist/engine/acp/adapter/claude/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/claude/agent-connection.d.ts.map +1 -1
- package/dist/engine/acp/adapter/claude/agent-connection.js +1 -0
- package/dist/engine/acp/adapter/claude/agent-connection.js.map +1 -1
- package/dist/engine/acp/adapter/codex/adapter.d.ts +53 -0
- package/dist/engine/acp/adapter/codex/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/codex/adapter.js +8 -1
- package/dist/engine/acp/adapter/codex/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/codex/agent-connection.d.ts.map +1 -1
- package/dist/engine/acp/adapter/codex/agent-connection.js +1 -0
- package/dist/engine/acp/adapter/codex/agent-connection.js.map +1 -1
- package/dist/engine/acp/adapter/execution-connections.d.ts +2 -1
- package/dist/engine/acp/adapter/execution-connections.d.ts.map +1 -1
- package/dist/engine/acp/adapter/execution-connections.js +6 -1
- package/dist/engine/acp/adapter/execution-connections.js.map +1 -1
- package/dist/engine/acp/adapter/pi/adapter.d.ts +10 -0
- package/dist/engine/acp/adapter/pi/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/pi/adapter.js +9 -0
- package/dist/engine/acp/adapter/pi/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/session-events.d.ts +2 -1
- package/dist/engine/acp/adapter/session-events.d.ts.map +1 -1
- package/dist/engine/acp/adapter/session-events.js +5 -0
- package/dist/engine/acp/adapter/session-events.js.map +1 -1
- package/dist/engine/acp/agent/in-process-endpoint.d.ts +12 -1
- package/dist/engine/acp/agent/in-process-endpoint.d.ts.map +1 -1
- package/dist/engine/acp/agent/in-process-endpoint.js.map +1 -1
- package/dist/engine/acp/connection/agent-connection.d.ts +2 -1
- package/dist/engine/acp/connection/agent-connection.d.ts.map +1 -1
- package/dist/engine/acp/harness/antigravity/usage-quota.d.ts +13 -0
- package/dist/engine/acp/harness/antigravity/usage-quota.d.ts.map +1 -0
- package/dist/engine/acp/harness/antigravity/usage-quota.js +457 -0
- package/dist/engine/acp/harness/antigravity/usage-quota.js.map +1 -0
- package/dist/engine/acp/harness/claude/endpoint.d.ts.map +1 -1
- package/dist/engine/acp/harness/claude/endpoint.js +9 -0
- package/dist/engine/acp/harness/claude/endpoint.js.map +1 -1
- package/dist/engine/acp/harness/claude/usage-quota.d.ts +30 -0
- package/dist/engine/acp/harness/claude/usage-quota.d.ts.map +1 -0
- package/dist/engine/acp/harness/claude/usage-quota.js +900 -0
- package/dist/engine/acp/harness/claude/usage-quota.js.map +1 -0
- package/dist/engine/acp/harness/codex/agent.d.ts.map +1 -1
- package/dist/engine/acp/harness/codex/agent.js +9 -0
- package/dist/engine/acp/harness/codex/agent.js.map +1 -1
- package/dist/engine/acp/harness/codex/usage-quota.d.ts +16 -0
- package/dist/engine/acp/harness/codex/usage-quota.d.ts.map +1 -0
- package/dist/engine/acp/harness/codex/usage-quota.js +360 -0
- package/dist/engine/acp/harness/codex/usage-quota.js.map +1 -0
- package/dist/engine/acp/native-history/preview-contract.d.ts +9 -1
- package/dist/engine/acp/native-history/preview-contract.d.ts.map +1 -1
- package/dist/engine/agent/runtime-agents.d.ts +1 -1
- package/dist/engine/agent/runtime-agents.d.ts.map +1 -1
- package/dist/engine/agent/runtime-agents.js +6 -2
- package/dist/engine/agent/runtime-agents.js.map +1 -1
- package/dist/engine/runtime/command/context.d.ts +2 -0
- package/dist/engine/runtime/command/context.d.ts.map +1 -1
- package/dist/engine/runtime/command/registry/index.d.ts.map +1 -1
- package/dist/engine/runtime/command/registry/index.js +2 -1
- package/dist/engine/runtime/command/registry/index.js.map +1 -1
- package/dist/engine/runtime/command/registry/runtime.d.ts +1 -0
- package/dist/engine/runtime/command/registry/runtime.d.ts.map +1 -1
- package/dist/engine/runtime/command/registry/runtime.js +52 -1
- package/dist/engine/runtime/command/registry/runtime.js.map +1 -1
- package/dist/engine/runtime/relay/run-relay-connection.d.ts +3 -1
- package/dist/engine/runtime/relay/run-relay-connection.d.ts.map +1 -1
- package/dist/engine/runtime/relay/run-relay-connection.js +2 -1
- package/dist/engine/runtime/relay/run-relay-connection.js.map +1 -1
- package/dist/engine/runtime/run.d.ts.map +1 -1
- package/dist/engine/runtime/run.js +9 -1
- package/dist/engine/runtime/run.js.map +1 -1
- package/dist/engine/session/usage/runtime-usage-service.d.ts +29 -0
- package/dist/engine/session/usage/runtime-usage-service.d.ts.map +1 -0
- package/dist/engine/session/usage/runtime-usage-service.js +248 -0
- package/dist/engine/session/usage/runtime-usage-service.js.map +1 -0
- package/dist/engine/storage/antigravity-usage-credentials.d.ts +26 -0
- package/dist/engine/storage/antigravity-usage-credentials.d.ts.map +1 -0
- package/dist/engine/storage/antigravity-usage-credentials.js +147 -0
- package/dist/engine/storage/antigravity-usage-credentials.js.map +1 -0
- package/dist/engine.js +2 -2
- package/package.json +2 -2
- /package/dist/{cli-LYAYRPGJ.js.map → cli-E4GLG6NB.js.map} +0 -0
|
@@ -0,0 +1,900 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { captureProcessTree, executableLaunch, platformSpawnOptions, stopProcessTree, } from "../../../util/process/executable.js";
|
|
5
|
+
import { spawnClaudeWithParentLifeline } from "./parent-lifeline.js";
|
|
6
|
+
const CLAUDE_AUTH_TIMEOUT_MILLISECONDS = 10_000;
|
|
7
|
+
const CLAUDE_USAGE_TIMEOUT_MILLISECONDS = 20_000;
|
|
8
|
+
const MAX_CLI_OUTPUT_BYTES = 256 * 1_024;
|
|
9
|
+
const SESSION_WINDOW_MINUTES = 5 * 60;
|
|
10
|
+
const WEEKLY_WINDOW_MINUTES = 7 * 24 * 60;
|
|
11
|
+
const authStatusSchema = z.object({
|
|
12
|
+
loggedIn: z.boolean(),
|
|
13
|
+
authMethod: z.string().nullish(),
|
|
14
|
+
apiProvider: z.string().nullish(),
|
|
15
|
+
email: z.string().nullish(),
|
|
16
|
+
subscriptionType: z.string().nullish(),
|
|
17
|
+
planTier: z.string().nullish(),
|
|
18
|
+
});
|
|
19
|
+
const utilizationWindowSchema = z.object({
|
|
20
|
+
utilization: z.number().nullish(),
|
|
21
|
+
resets_at: z.string().nullish(),
|
|
22
|
+
});
|
|
23
|
+
const modelScopedWindowSchema = z.object({
|
|
24
|
+
display_name: z.string().min(1),
|
|
25
|
+
utilization: z.number().nullish(),
|
|
26
|
+
resets_at: z.string().nullish(),
|
|
27
|
+
});
|
|
28
|
+
const spendMoneySchema = z.object({
|
|
29
|
+
amount_minor: z.number().int().nonnegative(),
|
|
30
|
+
currency: z.string().min(1),
|
|
31
|
+
exponent: z.number().int().nonnegative(),
|
|
32
|
+
});
|
|
33
|
+
const spendBudgetSchema = z.object({
|
|
34
|
+
enabled: z.boolean(),
|
|
35
|
+
used: spendMoneySchema,
|
|
36
|
+
limit: spendMoneySchema,
|
|
37
|
+
});
|
|
38
|
+
const extraUsageSchema = z.object({
|
|
39
|
+
is_enabled: z.boolean(),
|
|
40
|
+
monthly_limit: z.number().nullish(),
|
|
41
|
+
used_credits: z.number().nullish(),
|
|
42
|
+
utilization: z.number().nullish(),
|
|
43
|
+
});
|
|
44
|
+
const rateLimitsSchema = z.object({
|
|
45
|
+
five_hour: utilizationWindowSchema.nullish(),
|
|
46
|
+
seven_day: utilizationWindowSchema.nullish(),
|
|
47
|
+
seven_day_opus: utilizationWindowSchema.nullish(),
|
|
48
|
+
seven_day_sonnet: utilizationWindowSchema.nullish(),
|
|
49
|
+
seven_day_oauth_apps: utilizationWindowSchema.nullish(),
|
|
50
|
+
model_scoped: z.array(modelScopedWindowSchema).nullish(),
|
|
51
|
+
extra_usage: extraUsageSchema.nullish(),
|
|
52
|
+
spend: spendBudgetSchema.nullish(),
|
|
53
|
+
});
|
|
54
|
+
const getUsageResponseSchema = z.object({
|
|
55
|
+
subscription_type: z.string().nullish(),
|
|
56
|
+
rate_limits_available: z.boolean(),
|
|
57
|
+
rate_limits: rateLimitsSchema.nullish(),
|
|
58
|
+
});
|
|
59
|
+
function clampPercent(value) {
|
|
60
|
+
if (!Number.isFinite(value)) {
|
|
61
|
+
return 0;
|
|
62
|
+
}
|
|
63
|
+
const clamped = Math.max(0, Math.min(100, value));
|
|
64
|
+
return Math.round(clamped * 100) / 100;
|
|
65
|
+
}
|
|
66
|
+
function normalizeIsoTimestamp(value) {
|
|
67
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
const parsed = Date.parse(value);
|
|
71
|
+
if (!Number.isFinite(parsed)) {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
return new Date(parsed).toISOString();
|
|
75
|
+
}
|
|
76
|
+
function isoFromEpochSeconds(value) {
|
|
77
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
const date = new Date(value * 1_000);
|
|
81
|
+
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
82
|
+
}
|
|
83
|
+
function formatPlanLabel(planTier, subscriptionType) {
|
|
84
|
+
const tier = planTier?.trim().toLowerCase();
|
|
85
|
+
if (tier !== undefined && tier.length > 0) {
|
|
86
|
+
if (tier === "max_20x") {
|
|
87
|
+
return "Max 20x";
|
|
88
|
+
}
|
|
89
|
+
if (tier === "max_5x") {
|
|
90
|
+
return "Max 5x";
|
|
91
|
+
}
|
|
92
|
+
if (tier.startsWith("default_claude_")) {
|
|
93
|
+
const suffix = tier.slice("default_claude_".length).replace(/_/gu, " ");
|
|
94
|
+
return suffix.replace(/\b[a-z]/gu, (ch) => ch.toUpperCase()).slice(0, 64);
|
|
95
|
+
}
|
|
96
|
+
return tier
|
|
97
|
+
.replace(/_/gu, " ")
|
|
98
|
+
.replace(/\b[a-z]/gu, (ch) => ch.toUpperCase())
|
|
99
|
+
.slice(0, 64);
|
|
100
|
+
}
|
|
101
|
+
const sub = subscriptionType?.trim().toLowerCase();
|
|
102
|
+
if (sub === undefined || sub.length === 0) {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
switch (sub) {
|
|
106
|
+
case "pro":
|
|
107
|
+
return "Pro";
|
|
108
|
+
case "max":
|
|
109
|
+
return "Max";
|
|
110
|
+
case "team":
|
|
111
|
+
return "Team";
|
|
112
|
+
case "enterprise":
|
|
113
|
+
return "Enterprise";
|
|
114
|
+
default:
|
|
115
|
+
return sub.slice(0, 64);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function scopeToken(displayName) {
|
|
119
|
+
return displayName
|
|
120
|
+
.toLowerCase()
|
|
121
|
+
.replace(/[^a-z0-9]+/gu, "_")
|
|
122
|
+
.replace(/^_+|_+$/gu, "");
|
|
123
|
+
}
|
|
124
|
+
function formatMinorCurrency(amountMinor, currency, exponent) {
|
|
125
|
+
const divisor = 10 ** exponent;
|
|
126
|
+
const major = amountMinor / divisor;
|
|
127
|
+
const prefix = currency.toUpperCase() === "USD" ? "$" : `${currency.toUpperCase()} `;
|
|
128
|
+
return `${prefix}${major.toFixed(exponent)}`;
|
|
129
|
+
}
|
|
130
|
+
function buildWindow(params) {
|
|
131
|
+
const usedPercent = clampPercent(params.usedPercent);
|
|
132
|
+
const remainingPercent = clampPercent(100 - usedPercent);
|
|
133
|
+
return {
|
|
134
|
+
id: params.id,
|
|
135
|
+
kind: params.kind,
|
|
136
|
+
label: params.label,
|
|
137
|
+
...(params.group === undefined ? {} : { group: params.group }),
|
|
138
|
+
usedPercent,
|
|
139
|
+
remainingPercent,
|
|
140
|
+
...(params.resetsAt === undefined ? {} : { resetsAt: params.resetsAt }),
|
|
141
|
+
...(params.windowDurationMins === undefined ? {} : { windowDurationMins: params.windowDurationMins }),
|
|
142
|
+
...(params.isExtra === undefined ? {} : { isExtra: params.isExtra }),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function extractExtraUsage(rateLimits) {
|
|
146
|
+
const spend = rateLimits.spend;
|
|
147
|
+
if (spend?.enabled &&
|
|
148
|
+
spend.used.currency.trim() === spend.limit.currency.trim() &&
|
|
149
|
+
spend.used.exponent === spend.limit.exponent) {
|
|
150
|
+
if (spend.limit.amount_minor === 0) {
|
|
151
|
+
return {
|
|
152
|
+
credits: {
|
|
153
|
+
unlimited: false,
|
|
154
|
+
zeroSpendCap: true,
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
const percent = clampPercent((spend.used.amount_minor / spend.limit.amount_minor) * 100);
|
|
159
|
+
const usedText = formatMinorCurrency(spend.used.amount_minor, spend.used.currency, spend.used.exponent);
|
|
160
|
+
const limitText = formatMinorCurrency(spend.limit.amount_minor, spend.limit.currency, spend.limit.exponent);
|
|
161
|
+
return {
|
|
162
|
+
window: buildWindow({
|
|
163
|
+
id: "monthly_spend",
|
|
164
|
+
kind: "monthly",
|
|
165
|
+
label: "Extra usage",
|
|
166
|
+
usedPercent: percent,
|
|
167
|
+
isExtra: true,
|
|
168
|
+
}),
|
|
169
|
+
credits: {
|
|
170
|
+
unlimited: false,
|
|
171
|
+
balanceDisplay: `${usedText} / ${limitText}`,
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
const extra = rateLimits.extra_usage;
|
|
176
|
+
if (extra === null || extra === undefined || !extra.is_enabled) {
|
|
177
|
+
return {};
|
|
178
|
+
}
|
|
179
|
+
if (extra.monthly_limit === 0) {
|
|
180
|
+
return {
|
|
181
|
+
credits: {
|
|
182
|
+
unlimited: false,
|
|
183
|
+
zeroSpendCap: true,
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
const percent = typeof extra.used_credits === "number" &&
|
|
188
|
+
typeof extra.monthly_limit === "number" &&
|
|
189
|
+
Number.isFinite(extra.used_credits) &&
|
|
190
|
+
Number.isFinite(extra.monthly_limit) &&
|
|
191
|
+
extra.monthly_limit > 0
|
|
192
|
+
? clampPercent((extra.used_credits / extra.monthly_limit) * 100)
|
|
193
|
+
: typeof extra.utilization === "number" && Number.isFinite(extra.utilization)
|
|
194
|
+
? clampPercent(extra.utilization)
|
|
195
|
+
: undefined;
|
|
196
|
+
const balanceDisplay = typeof extra.used_credits === "number" &&
|
|
197
|
+
typeof extra.monthly_limit === "number" &&
|
|
198
|
+
Number.isFinite(extra.used_credits) &&
|
|
199
|
+
Number.isFinite(extra.monthly_limit) &&
|
|
200
|
+
extra.monthly_limit > 0
|
|
201
|
+
? `$${(extra.used_credits / 100).toFixed(2)} / $${(extra.monthly_limit / 100).toFixed(2)}`
|
|
202
|
+
: undefined;
|
|
203
|
+
return {
|
|
204
|
+
...(percent === undefined
|
|
205
|
+
? {}
|
|
206
|
+
: {
|
|
207
|
+
window: buildWindow({
|
|
208
|
+
id: "monthly_spend",
|
|
209
|
+
kind: "monthly",
|
|
210
|
+
label: "Extra usage",
|
|
211
|
+
usedPercent: percent,
|
|
212
|
+
isExtra: true,
|
|
213
|
+
}),
|
|
214
|
+
}),
|
|
215
|
+
...(balanceDisplay === undefined
|
|
216
|
+
? {}
|
|
217
|
+
: {
|
|
218
|
+
credits: {
|
|
219
|
+
unlimited: false,
|
|
220
|
+
balanceDisplay,
|
|
221
|
+
},
|
|
222
|
+
}),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/** Converts a live `rate_limit_event` from `@anthropic-ai/claude-agent-sdk` into a passive quota report. */
|
|
226
|
+
export function claudeRateLimitEventToReport(info, observedAt) {
|
|
227
|
+
const type = info.rateLimitType;
|
|
228
|
+
if (type === undefined || typeof info.utilization !== "number" || !Number.isFinite(info.utilization)) {
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
// SDK rate_limit_event emits utilization in the 0..1 range.
|
|
232
|
+
const usedPercent = clampPercent(info.utilization <= 1 ? info.utilization * 100 : info.utilization);
|
|
233
|
+
const resetsAt = isoFromEpochSeconds(info.resetsAt);
|
|
234
|
+
switch (type) {
|
|
235
|
+
case "five_hour":
|
|
236
|
+
return {
|
|
237
|
+
agentId: "claude",
|
|
238
|
+
observedAt,
|
|
239
|
+
windows: [
|
|
240
|
+
buildWindow({
|
|
241
|
+
id: "five_hour",
|
|
242
|
+
kind: "session",
|
|
243
|
+
label: "Session",
|
|
244
|
+
usedPercent,
|
|
245
|
+
windowDurationMins: SESSION_WINDOW_MINUTES,
|
|
246
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
247
|
+
}),
|
|
248
|
+
],
|
|
249
|
+
};
|
|
250
|
+
case "seven_day":
|
|
251
|
+
return {
|
|
252
|
+
agentId: "claude",
|
|
253
|
+
observedAt,
|
|
254
|
+
windows: [
|
|
255
|
+
buildWindow({
|
|
256
|
+
id: "seven_day",
|
|
257
|
+
kind: "weekly",
|
|
258
|
+
label: "Weekly",
|
|
259
|
+
usedPercent,
|
|
260
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
261
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
262
|
+
}),
|
|
263
|
+
],
|
|
264
|
+
};
|
|
265
|
+
case "seven_day_opus":
|
|
266
|
+
return {
|
|
267
|
+
agentId: "claude",
|
|
268
|
+
observedAt,
|
|
269
|
+
windows: [
|
|
270
|
+
buildWindow({
|
|
271
|
+
id: "seven_day_opus",
|
|
272
|
+
kind: "weekly",
|
|
273
|
+
label: "Weekly · Opus",
|
|
274
|
+
group: "Models",
|
|
275
|
+
usedPercent,
|
|
276
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
277
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
278
|
+
}),
|
|
279
|
+
],
|
|
280
|
+
};
|
|
281
|
+
case "seven_day_sonnet":
|
|
282
|
+
return {
|
|
283
|
+
agentId: "claude",
|
|
284
|
+
observedAt,
|
|
285
|
+
windows: [
|
|
286
|
+
buildWindow({
|
|
287
|
+
id: "seven_day_sonnet",
|
|
288
|
+
kind: "weekly",
|
|
289
|
+
label: "Weekly · Sonnet",
|
|
290
|
+
group: "Models",
|
|
291
|
+
usedPercent,
|
|
292
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
293
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
294
|
+
}),
|
|
295
|
+
],
|
|
296
|
+
};
|
|
297
|
+
case "seven_day_overage_included":
|
|
298
|
+
return {
|
|
299
|
+
agentId: "claude",
|
|
300
|
+
observedAt,
|
|
301
|
+
windows: [
|
|
302
|
+
buildWindow({
|
|
303
|
+
id: "seven_day_overage_included",
|
|
304
|
+
kind: "weekly",
|
|
305
|
+
label: "Weekly · Model",
|
|
306
|
+
group: "Models",
|
|
307
|
+
usedPercent,
|
|
308
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
309
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
310
|
+
}),
|
|
311
|
+
],
|
|
312
|
+
};
|
|
313
|
+
default:
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async function runCliCommand(params) {
|
|
318
|
+
params.signal.throwIfAborted();
|
|
319
|
+
const launch = executableLaunch(params.command, [...params.args]);
|
|
320
|
+
const child = spawn(launch.command, [...launch.arguments], {
|
|
321
|
+
cwd: params.cwd,
|
|
322
|
+
...platformSpawnOptions,
|
|
323
|
+
env: { ...process.env, ...params.environment },
|
|
324
|
+
shell: false,
|
|
325
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
326
|
+
});
|
|
327
|
+
const processTreePromise = captureProcessTree(child).catch(() => []);
|
|
328
|
+
const timeoutSignal = AbortSignal.any([params.signal, AbortSignal.timeout(params.timeoutMs)]);
|
|
329
|
+
let stdout = "";
|
|
330
|
+
let stderr = "";
|
|
331
|
+
let stdoutBytes = 0;
|
|
332
|
+
let stderrBytes = 0;
|
|
333
|
+
return await new Promise((resolve, reject) => {
|
|
334
|
+
let settled = false;
|
|
335
|
+
const finish = (outcome) => {
|
|
336
|
+
if (settled) {
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
settled = true;
|
|
340
|
+
timeoutSignal.removeEventListener("abort", onAbort);
|
|
341
|
+
outcome();
|
|
342
|
+
};
|
|
343
|
+
const onAbort = () => {
|
|
344
|
+
void processTreePromise
|
|
345
|
+
.then(async (processTree) => await stopProcessTree(child, processTree))
|
|
346
|
+
.catch(() => undefined)
|
|
347
|
+
.finally(() => {
|
|
348
|
+
finish(() => reject(timeoutSignal.reason ?? new Error("Claude command aborted")));
|
|
349
|
+
});
|
|
350
|
+
};
|
|
351
|
+
timeoutSignal.addEventListener("abort", onAbort, { once: true });
|
|
352
|
+
child.stdout?.setEncoding("utf8");
|
|
353
|
+
child.stdout?.on("data", (chunk) => {
|
|
354
|
+
if (stdoutBytes < MAX_CLI_OUTPUT_BYTES) {
|
|
355
|
+
stdout += chunk;
|
|
356
|
+
stdoutBytes += Buffer.byteLength(chunk);
|
|
357
|
+
}
|
|
358
|
+
});
|
|
359
|
+
child.stderr?.setEncoding("utf8");
|
|
360
|
+
child.stderr?.on("data", (chunk) => {
|
|
361
|
+
if (stderrBytes < MAX_CLI_OUTPUT_BYTES) {
|
|
362
|
+
stderr += chunk;
|
|
363
|
+
stderrBytes += Buffer.byteLength(chunk);
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
child.once("error", (error) => {
|
|
367
|
+
finish(() => reject(error));
|
|
368
|
+
});
|
|
369
|
+
child.once("close", (code) => {
|
|
370
|
+
finish(() => resolve({ stdout, stderr, exitCode: code }));
|
|
371
|
+
});
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
async function readClaudeAuthStatus(options) {
|
|
375
|
+
try {
|
|
376
|
+
const result = await runCliCommand({
|
|
377
|
+
command: options.command,
|
|
378
|
+
args: ["auth", "status"],
|
|
379
|
+
cwd: options.cwd,
|
|
380
|
+
environment: options.environment,
|
|
381
|
+
signal: options.signal,
|
|
382
|
+
timeoutMs: CLAUDE_AUTH_TIMEOUT_MILLISECONDS,
|
|
383
|
+
});
|
|
384
|
+
const trimmed = result.stdout.trim();
|
|
385
|
+
if (trimmed.length === 0) {
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
const parsed = authStatusSchema.safeParse(JSON.parse(trimmed));
|
|
389
|
+
return parsed.success ? parsed.data : null;
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
if (options.signal.aborted) {
|
|
393
|
+
throw options.signal.reason ?? error;
|
|
394
|
+
}
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
function createIdlePromptStream(signal) {
|
|
399
|
+
return {
|
|
400
|
+
[Symbol.asyncIterator]() {
|
|
401
|
+
return {
|
|
402
|
+
next: () => new Promise((resolve) => {
|
|
403
|
+
if (signal.aborted) {
|
|
404
|
+
resolve({ done: true, value: undefined });
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
signal.addEventListener("abort", () => resolve({ done: true, value: undefined }), {
|
|
408
|
+
once: true,
|
|
409
|
+
});
|
|
410
|
+
}),
|
|
411
|
+
};
|
|
412
|
+
},
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
function raceWithAbort(promise, signal) {
|
|
416
|
+
if (signal.aborted) {
|
|
417
|
+
return Promise.reject(signal.reason ?? new Error("Operation aborted"));
|
|
418
|
+
}
|
|
419
|
+
return new Promise((resolve, reject) => {
|
|
420
|
+
const onAbort = () => {
|
|
421
|
+
reject(signal.reason ?? new Error("Operation aborted"));
|
|
422
|
+
};
|
|
423
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
424
|
+
promise.then((value) => {
|
|
425
|
+
signal.removeEventListener("abort", onAbort);
|
|
426
|
+
resolve(value);
|
|
427
|
+
}, (error) => {
|
|
428
|
+
signal.removeEventListener("abort", onAbort);
|
|
429
|
+
reject(error);
|
|
430
|
+
});
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
function mapSdkUsageResponse(raw, auth, checkedAt) {
|
|
434
|
+
const parsed = getUsageResponseSchema.parse(raw);
|
|
435
|
+
if (!parsed.rate_limits_available) {
|
|
436
|
+
return {
|
|
437
|
+
agentId: "claude",
|
|
438
|
+
status: "unsupported",
|
|
439
|
+
checkedAt,
|
|
440
|
+
reason: "no_subscription_quota",
|
|
441
|
+
message: "Claude Code is not using a subscription plan with rolling usage windows.",
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
const rateLimits = parsed.rate_limits;
|
|
445
|
+
if (rateLimits === null || rateLimits === undefined) {
|
|
446
|
+
return {
|
|
447
|
+
agentId: "claude",
|
|
448
|
+
status: "unavailable",
|
|
449
|
+
checkedAt,
|
|
450
|
+
errorCode: "claude_usage_empty",
|
|
451
|
+
errorMessage: "Claude Code returned no usage quota windows.",
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
const windows = [];
|
|
455
|
+
if (typeof rateLimits.five_hour?.utilization === "number") {
|
|
456
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.five_hour.resets_at);
|
|
457
|
+
windows.push(buildWindow({
|
|
458
|
+
id: "five_hour",
|
|
459
|
+
kind: "session",
|
|
460
|
+
label: "Session",
|
|
461
|
+
usedPercent: rateLimits.five_hour.utilization,
|
|
462
|
+
windowDurationMins: SESSION_WINDOW_MINUTES,
|
|
463
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
464
|
+
}));
|
|
465
|
+
}
|
|
466
|
+
if (typeof rateLimits.seven_day?.utilization === "number") {
|
|
467
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.seven_day.resets_at);
|
|
468
|
+
windows.push(buildWindow({
|
|
469
|
+
id: "seven_day",
|
|
470
|
+
kind: "weekly",
|
|
471
|
+
label: "Weekly",
|
|
472
|
+
usedPercent: rateLimits.seven_day.utilization,
|
|
473
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
474
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
475
|
+
}));
|
|
476
|
+
}
|
|
477
|
+
if (typeof rateLimits.seven_day_sonnet?.utilization === "number") {
|
|
478
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.seven_day_sonnet.resets_at);
|
|
479
|
+
windows.push(buildWindow({
|
|
480
|
+
id: "seven_day_sonnet",
|
|
481
|
+
kind: "weekly",
|
|
482
|
+
label: "Weekly · Sonnet",
|
|
483
|
+
group: "Models",
|
|
484
|
+
usedPercent: rateLimits.seven_day_sonnet.utilization,
|
|
485
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
486
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
487
|
+
}));
|
|
488
|
+
}
|
|
489
|
+
if (typeof rateLimits.seven_day_opus?.utilization === "number") {
|
|
490
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.seven_day_opus.resets_at);
|
|
491
|
+
windows.push(buildWindow({
|
|
492
|
+
id: "seven_day_opus",
|
|
493
|
+
kind: "weekly",
|
|
494
|
+
label: "Weekly · Opus",
|
|
495
|
+
group: "Models",
|
|
496
|
+
usedPercent: rateLimits.seven_day_opus.utilization,
|
|
497
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
498
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
499
|
+
}));
|
|
500
|
+
}
|
|
501
|
+
if (typeof rateLimits.seven_day_oauth_apps?.utilization === "number") {
|
|
502
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.seven_day_oauth_apps.resets_at);
|
|
503
|
+
windows.push(buildWindow({
|
|
504
|
+
id: "seven_day_oauth_apps",
|
|
505
|
+
kind: "weekly",
|
|
506
|
+
label: "Weekly · OAuth apps",
|
|
507
|
+
group: "Models",
|
|
508
|
+
usedPercent: rateLimits.seven_day_oauth_apps.utilization,
|
|
509
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
510
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
511
|
+
}));
|
|
512
|
+
}
|
|
513
|
+
const existingIds = new Set(windows.map((window) => window.id));
|
|
514
|
+
for (const entry of rateLimits.model_scoped ?? []) {
|
|
515
|
+
if (typeof entry.utilization !== "number") {
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
const token = scopeToken(entry.display_name);
|
|
519
|
+
const id = token.length > 0 ? `seven_day_${token}` : "seven_day_model";
|
|
520
|
+
if (existingIds.has(id)) {
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
existingIds.add(id);
|
|
524
|
+
const resetsAt = normalizeIsoTimestamp(entry.resets_at);
|
|
525
|
+
windows.push(buildWindow({
|
|
526
|
+
id,
|
|
527
|
+
kind: "weekly",
|
|
528
|
+
label: `Weekly · ${entry.display_name.trim()}`,
|
|
529
|
+
group: "Models",
|
|
530
|
+
usedPercent: entry.utilization,
|
|
531
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
532
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
533
|
+
}));
|
|
534
|
+
}
|
|
535
|
+
const extra = extractExtraUsage(rateLimits);
|
|
536
|
+
if (extra.window !== undefined) {
|
|
537
|
+
windows.push(extra.window);
|
|
538
|
+
}
|
|
539
|
+
const plan = formatPlanLabel(auth?.planTier, parsed.subscription_type ?? auth?.subscriptionType);
|
|
540
|
+
const email = auth?.email?.trim();
|
|
541
|
+
return {
|
|
542
|
+
agentId: "claude",
|
|
543
|
+
status: "available",
|
|
544
|
+
checkedAt,
|
|
545
|
+
...(plan === undefined ? {} : { plan }),
|
|
546
|
+
...(email === undefined || email.length === 0 ? {} : { accountLabel: email.slice(0, 128) }),
|
|
547
|
+
windows,
|
|
548
|
+
...(extra.credits === undefined ? {} : { credits: extra.credits }),
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
const CLI_USAGE_LINE = /^Current (session|week(?: \(([^)]+)\))?):\s*([0-9.]+)% used(?:\s*·\s*resets (.+))?$/u;
|
|
552
|
+
const CLI_EXTRA_LINE = /^Extra usage:\s*([0-9.]+)% used(?:\s*·\s*([^·]+))?/u;
|
|
553
|
+
const CLI_MONTHS = [
|
|
554
|
+
"jan",
|
|
555
|
+
"feb",
|
|
556
|
+
"mar",
|
|
557
|
+
"apr",
|
|
558
|
+
"may",
|
|
559
|
+
"jun",
|
|
560
|
+
"jul",
|
|
561
|
+
"aug",
|
|
562
|
+
"sep",
|
|
563
|
+
"oct",
|
|
564
|
+
"nov",
|
|
565
|
+
"dec",
|
|
566
|
+
];
|
|
567
|
+
const CLI_DATE_RESET = /^([A-Za-z]{3})\s+(\d{1,2})(?:,\s*(\d{4}))?(?:\s+at|\s*,)\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/iu;
|
|
568
|
+
const CLI_TIME_RESET = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/iu;
|
|
569
|
+
const RESET_SLACK_MILLISECONDS = 2 * 60 * 60 * 1_000;
|
|
570
|
+
function zonedParts(epochMs, timeZone) {
|
|
571
|
+
try {
|
|
572
|
+
const formatter = new Intl.DateTimeFormat("en-US", {
|
|
573
|
+
timeZone,
|
|
574
|
+
year: "numeric",
|
|
575
|
+
month: "2-digit",
|
|
576
|
+
day: "2-digit",
|
|
577
|
+
hour: "2-digit",
|
|
578
|
+
minute: "2-digit",
|
|
579
|
+
hourCycle: "h23",
|
|
580
|
+
});
|
|
581
|
+
const parts = formatter.formatToParts(new Date(epochMs));
|
|
582
|
+
const read = (type) => Number(parts.find((part) => part.type === type)?.value ?? Number.NaN);
|
|
583
|
+
const year = read("year");
|
|
584
|
+
const month = read("month");
|
|
585
|
+
const day = read("day");
|
|
586
|
+
const hour = read("hour") % 24;
|
|
587
|
+
const minute = read("minute");
|
|
588
|
+
if (![year, month, day, hour, minute].every(Number.isFinite)) {
|
|
589
|
+
return null;
|
|
590
|
+
}
|
|
591
|
+
return { year, month, day, hour, minute };
|
|
592
|
+
}
|
|
593
|
+
catch {
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function zonedDateTimeToUtcMs(target, timeZone) {
|
|
598
|
+
const desiredWallMs = Date.UTC(target.year, target.month - 1, target.day, target.hour, target.minute, 0, 0);
|
|
599
|
+
let candidate = desiredWallMs;
|
|
600
|
+
for (let step = 0; step < 3; step += 1) {
|
|
601
|
+
const actual = zonedParts(candidate, timeZone);
|
|
602
|
+
if (actual === null) {
|
|
603
|
+
return null;
|
|
604
|
+
}
|
|
605
|
+
const actualWallMs = Date.UTC(actual.year, actual.month - 1, actual.day, actual.hour, actual.minute, 0, 0);
|
|
606
|
+
const diff = desiredWallMs - actualWallMs;
|
|
607
|
+
if (diff === 0) {
|
|
608
|
+
return candidate;
|
|
609
|
+
}
|
|
610
|
+
candidate += diff;
|
|
611
|
+
}
|
|
612
|
+
const verified = zonedParts(candidate, timeZone);
|
|
613
|
+
if (verified === null ||
|
|
614
|
+
verified.year !== target.year ||
|
|
615
|
+
verified.month !== target.month ||
|
|
616
|
+
verified.day !== target.day ||
|
|
617
|
+
verified.hour !== target.hour ||
|
|
618
|
+
verified.minute !== target.minute) {
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
return candidate;
|
|
622
|
+
}
|
|
623
|
+
function parseClaudeCliResetText(raw, nowMs, spanMinutes) {
|
|
624
|
+
if (raw === undefined) {
|
|
625
|
+
return undefined;
|
|
626
|
+
}
|
|
627
|
+
let text = raw.trim();
|
|
628
|
+
if (text.length === 0) {
|
|
629
|
+
return undefined;
|
|
630
|
+
}
|
|
631
|
+
let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
632
|
+
const zoneStart = text.lastIndexOf("(");
|
|
633
|
+
if (zoneStart >= 0 && text.endsWith(")")) {
|
|
634
|
+
const candidateZone = text.slice(zoneStart + 1, -1).trim();
|
|
635
|
+
if (candidateZone.length > 0 && zonedParts(nowMs, candidateZone) !== null) {
|
|
636
|
+
timeZone = candidateZone;
|
|
637
|
+
}
|
|
638
|
+
text = text.slice(0, zoneStart).trim();
|
|
639
|
+
}
|
|
640
|
+
const ref = zonedParts(nowMs, timeZone);
|
|
641
|
+
if (ref === null) {
|
|
642
|
+
return undefined;
|
|
643
|
+
}
|
|
644
|
+
const latestMs = nowMs + spanMinutes * 60_000 + RESET_SLACK_MILLISECONDS;
|
|
645
|
+
const dateMatch = CLI_DATE_RESET.exec(text);
|
|
646
|
+
if (dateMatch !== null) {
|
|
647
|
+
const monthToken = (dateMatch[1] ?? "").toLowerCase();
|
|
648
|
+
const monthIndex = CLI_MONTHS.indexOf(monthToken);
|
|
649
|
+
const day = Number(dateMatch[2]);
|
|
650
|
+
const explicitYear = dateMatch[3] === undefined ? undefined : Number(dateMatch[3]);
|
|
651
|
+
const rawHour = Number(dateMatch[4]);
|
|
652
|
+
const minute = dateMatch[5] === undefined ? 0 : Number(dateMatch[5]);
|
|
653
|
+
const meridiem = (dateMatch[6] ?? "").toLowerCase();
|
|
654
|
+
if (monthIndex < 0 || !Number.isFinite(day) || !Number.isFinite(rawHour) || !Number.isFinite(minute)) {
|
|
655
|
+
return undefined;
|
|
656
|
+
}
|
|
657
|
+
const hour = (rawHour % 12) + (meridiem === "pm" ? 12 : 0);
|
|
658
|
+
if (explicitYear !== undefined) {
|
|
659
|
+
const utcMs = zonedDateTimeToUtcMs({ year: explicitYear, month: monthIndex + 1, day, hour, minute }, timeZone);
|
|
660
|
+
return utcMs === null ? undefined : new Date(utcMs).toISOString();
|
|
661
|
+
}
|
|
662
|
+
let fallbackPast = null;
|
|
663
|
+
for (const year of [ref.year - 1, ref.year, ref.year + 1]) {
|
|
664
|
+
const utcMs = zonedDateTimeToUtcMs({ year, month: monthIndex + 1, day, hour, minute }, timeZone);
|
|
665
|
+
if (utcMs === null) {
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
if (utcMs >= nowMs - 24 * 60 * 60 * 1_000 && utcMs <= latestMs) {
|
|
669
|
+
return new Date(utcMs).toISOString();
|
|
670
|
+
}
|
|
671
|
+
if (utcMs < nowMs) {
|
|
672
|
+
fallbackPast = utcMs;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
return fallbackPast === null ? undefined : new Date(fallbackPast).toISOString();
|
|
676
|
+
}
|
|
677
|
+
const timeMatch = CLI_TIME_RESET.exec(text);
|
|
678
|
+
if (timeMatch !== null) {
|
|
679
|
+
const rawHour = Number(timeMatch[1]);
|
|
680
|
+
const minute = timeMatch[2] === undefined ? 0 : Number(timeMatch[2]);
|
|
681
|
+
const meridiem = (timeMatch[3] ?? "").toLowerCase();
|
|
682
|
+
if (!Number.isFinite(rawHour) || !Number.isFinite(minute)) {
|
|
683
|
+
return undefined;
|
|
684
|
+
}
|
|
685
|
+
const hour = (rawHour % 12) + (meridiem === "pm" ? 12 : 0);
|
|
686
|
+
for (const dayOffset of [0, 1, 2]) {
|
|
687
|
+
const base = new Date(Date.UTC(ref.year, ref.month - 1, ref.day + dayOffset));
|
|
688
|
+
const utcMs = zonedDateTimeToUtcMs({ year: base.getUTCFullYear(), month: base.getUTCMonth() + 1, day: base.getUTCDate(), hour, minute }, timeZone);
|
|
689
|
+
if (utcMs !== null && utcMs >= nowMs && utcMs <= latestMs) {
|
|
690
|
+
return new Date(utcMs).toISOString();
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
return undefined;
|
|
695
|
+
}
|
|
696
|
+
/** Parses plain text printed by `claude -p /usage` when SDK structured `get_usage` is unavailable. */
|
|
697
|
+
export function parseClaudeCliUsageOutput(output, auth, checkedAt) {
|
|
698
|
+
const nowMs = Date.parse(checkedAt);
|
|
699
|
+
const windows = [];
|
|
700
|
+
let credits;
|
|
701
|
+
for (const rawLine of output.split(/\r?\n/u)) {
|
|
702
|
+
const line = rawLine.trim();
|
|
703
|
+
const match = CLI_USAGE_LINE.exec(line);
|
|
704
|
+
if (match !== null) {
|
|
705
|
+
const period = match[1];
|
|
706
|
+
const scope = match[2];
|
|
707
|
+
const percent = Number(match[3]);
|
|
708
|
+
const resetRaw = match[4];
|
|
709
|
+
if (!Number.isFinite(percent)) {
|
|
710
|
+
continue;
|
|
711
|
+
}
|
|
712
|
+
if (period === "session") {
|
|
713
|
+
const resetsAt = parseClaudeCliResetText(resetRaw, nowMs, SESSION_WINDOW_MINUTES);
|
|
714
|
+
windows.push(buildWindow({
|
|
715
|
+
id: "five_hour",
|
|
716
|
+
kind: "session",
|
|
717
|
+
label: "Session",
|
|
718
|
+
usedPercent: percent,
|
|
719
|
+
windowDurationMins: SESSION_WINDOW_MINUTES,
|
|
720
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
721
|
+
}));
|
|
722
|
+
}
|
|
723
|
+
else if (scope === undefined || scope.toLowerCase() === "all models") {
|
|
724
|
+
const resetsAt = parseClaudeCliResetText(resetRaw, nowMs, WEEKLY_WINDOW_MINUTES);
|
|
725
|
+
windows.push(buildWindow({
|
|
726
|
+
id: "seven_day",
|
|
727
|
+
kind: "weekly",
|
|
728
|
+
label: "Weekly",
|
|
729
|
+
usedPercent: percent,
|
|
730
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
731
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
732
|
+
}));
|
|
733
|
+
}
|
|
734
|
+
else {
|
|
735
|
+
const token = scopeToken(scope);
|
|
736
|
+
const resetsAt = parseClaudeCliResetText(resetRaw, nowMs, WEEKLY_WINDOW_MINUTES);
|
|
737
|
+
windows.push(buildWindow({
|
|
738
|
+
id: token.length > 0 ? `seven_day_${token}` : "seven_day_model",
|
|
739
|
+
kind: "weekly",
|
|
740
|
+
label: `Weekly · ${scope.trim()}`,
|
|
741
|
+
group: "Models",
|
|
742
|
+
usedPercent: percent,
|
|
743
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
744
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
745
|
+
}));
|
|
746
|
+
}
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
const extraMatch = CLI_EXTRA_LINE.exec(line);
|
|
750
|
+
if (extraMatch !== null) {
|
|
751
|
+
const percent = Number(extraMatch[1]);
|
|
752
|
+
const detail = extraMatch[2]?.trim();
|
|
753
|
+
if (Number.isFinite(percent)) {
|
|
754
|
+
windows.push(buildWindow({
|
|
755
|
+
id: "monthly_spend",
|
|
756
|
+
kind: "monthly",
|
|
757
|
+
label: "Extra usage",
|
|
758
|
+
usedPercent: percent,
|
|
759
|
+
isExtra: true,
|
|
760
|
+
}));
|
|
761
|
+
}
|
|
762
|
+
if (detail !== undefined && detail.length > 0) {
|
|
763
|
+
credits = { unlimited: false, balanceDisplay: detail.slice(0, 64) };
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (windows.length === 0) {
|
|
768
|
+
return {
|
|
769
|
+
agentId: "claude",
|
|
770
|
+
status: "unavailable",
|
|
771
|
+
checkedAt,
|
|
772
|
+
errorCode: "claude_usage_unavailable",
|
|
773
|
+
errorMessage: "Claude Code did not report subscription usage figures.",
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
const plan = formatPlanLabel(auth?.planTier, auth?.subscriptionType);
|
|
777
|
+
const email = auth?.email?.trim();
|
|
778
|
+
return {
|
|
779
|
+
agentId: "claude",
|
|
780
|
+
status: "available",
|
|
781
|
+
checkedAt,
|
|
782
|
+
...(plan === undefined ? {} : { plan }),
|
|
783
|
+
...(email === undefined || email.length === 0 ? {} : { accountLabel: email.slice(0, 128) }),
|
|
784
|
+
windows,
|
|
785
|
+
...(credits === undefined ? {} : { credits }),
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
async function readClaudeUsageViaSdk(options, auth, checkedAt) {
|
|
789
|
+
const probeController = new AbortController();
|
|
790
|
+
const timeoutSignal = AbortSignal.any([
|
|
791
|
+
options.signal,
|
|
792
|
+
probeController.signal,
|
|
793
|
+
AbortSignal.timeout(CLAUDE_USAGE_TIMEOUT_MILLISECONDS),
|
|
794
|
+
]);
|
|
795
|
+
const forwardAbort = () => {
|
|
796
|
+
probeController.abort(timeoutSignal.reason);
|
|
797
|
+
};
|
|
798
|
+
timeoutSignal.addEventListener("abort", forwardAbort, { once: true });
|
|
799
|
+
const q = query({
|
|
800
|
+
prompt: createIdlePromptStream(probeController.signal),
|
|
801
|
+
options: {
|
|
802
|
+
abortController: probeController,
|
|
803
|
+
cwd: options.cwd,
|
|
804
|
+
env: {
|
|
805
|
+
...process.env,
|
|
806
|
+
...options.environment,
|
|
807
|
+
CLAUDE_CODE_EXECUTABLE: options.command,
|
|
808
|
+
},
|
|
809
|
+
pathToClaudeCodeExecutable: options.command,
|
|
810
|
+
persistSession: false,
|
|
811
|
+
settingSources: [],
|
|
812
|
+
spawnClaudeCodeProcess: spawnClaudeWithParentLifeline,
|
|
813
|
+
},
|
|
814
|
+
});
|
|
815
|
+
try {
|
|
816
|
+
const init = await raceWithAbort(q.initializationResult(), timeoutSignal);
|
|
817
|
+
const response = await raceWithAbort(q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(), timeoutSignal);
|
|
818
|
+
const mergedAuth = auth ??
|
|
819
|
+
(init.account === undefined
|
|
820
|
+
? null
|
|
821
|
+
: {
|
|
822
|
+
loggedIn: true,
|
|
823
|
+
email: init.account.email,
|
|
824
|
+
subscriptionType: init.account.subscriptionType,
|
|
825
|
+
apiProvider: init.account.apiProvider,
|
|
826
|
+
});
|
|
827
|
+
return mapSdkUsageResponse(response, mergedAuth, checkedAt);
|
|
828
|
+
}
|
|
829
|
+
finally {
|
|
830
|
+
timeoutSignal.removeEventListener("abort", forwardAbort);
|
|
831
|
+
probeController.abort();
|
|
832
|
+
q.close();
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Probes Claude Code subscription quotas using the Agent SDK's structured `get_usage` control request,
|
|
837
|
+
* falling back to `claude -p /usage` if the experimental control request is unavailable.
|
|
838
|
+
*/
|
|
839
|
+
export async function readClaudeUsageQuota(options) {
|
|
840
|
+
options.signal.throwIfAborted();
|
|
841
|
+
const checkedAt = new Date().toISOString();
|
|
842
|
+
const auth = await readClaudeAuthStatus(options);
|
|
843
|
+
if (auth !== null) {
|
|
844
|
+
if (!auth.loggedIn) {
|
|
845
|
+
return {
|
|
846
|
+
agentId: "claude",
|
|
847
|
+
status: "unauthenticated",
|
|
848
|
+
checkedAt,
|
|
849
|
+
message: "Sign in to Claude Code on this computer to view subscription quotas.",
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
const provider = auth.apiProvider?.trim();
|
|
853
|
+
const method = auth.authMethod?.trim();
|
|
854
|
+
if ((provider !== undefined && provider.length > 0 && provider !== "firstParty") ||
|
|
855
|
+
(method !== undefined && method.length > 0 && method !== "claude.ai" && method !== "oauth")) {
|
|
856
|
+
return {
|
|
857
|
+
agentId: "claude",
|
|
858
|
+
status: "unsupported",
|
|
859
|
+
checkedAt,
|
|
860
|
+
reason: "api_key",
|
|
861
|
+
message: "Claude Code is not using a Claude.ai subscription.",
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
try {
|
|
866
|
+
return await readClaudeUsageViaSdk(options, auth, checkedAt);
|
|
867
|
+
}
|
|
868
|
+
catch (sdkError) {
|
|
869
|
+
if (options.signal.aborted) {
|
|
870
|
+
throw options.signal.reason ?? sdkError;
|
|
871
|
+
}
|
|
872
|
+
try {
|
|
873
|
+
const cliResult = await runCliCommand({
|
|
874
|
+
command: options.command,
|
|
875
|
+
args: ["-p", "/usage"],
|
|
876
|
+
cwd: options.cwd,
|
|
877
|
+
environment: options.environment,
|
|
878
|
+
signal: options.signal,
|
|
879
|
+
timeoutMs: CLAUDE_USAGE_TIMEOUT_MILLISECONDS,
|
|
880
|
+
});
|
|
881
|
+
return parseClaudeCliUsageOutput(cliResult.stdout, auth, checkedAt);
|
|
882
|
+
}
|
|
883
|
+
catch (cliError) {
|
|
884
|
+
if (options.signal.aborted) {
|
|
885
|
+
throw options.signal.reason ?? cliError;
|
|
886
|
+
}
|
|
887
|
+
const message = sdkError instanceof Error && sdkError.message.trim().length > 0
|
|
888
|
+
? sdkError.message.trim().slice(0, 256)
|
|
889
|
+
: "Claude Code could not report subscription usage quotas.";
|
|
890
|
+
return {
|
|
891
|
+
agentId: "claude",
|
|
892
|
+
status: "unavailable",
|
|
893
|
+
checkedAt,
|
|
894
|
+
errorCode: "claude_usage_probe_failed",
|
|
895
|
+
errorMessage: message,
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
//# sourceMappingURL=usage-quota.js.map
|