sidekick-shared 0.21.0 → 0.21.2
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/README.md +2 -2
- package/dist/index.d.ts +9 -2
- package/dist/index.js +28 -6
- package/dist/multiProviderQuotaService.d.ts +10 -0
- package/dist/multiProviderQuotaService.js +34 -0
- package/dist/providerQuota.d.ts +2 -1
- package/dist/providers/detect.js +3 -13
- package/dist/providers/openCode.d.ts +31 -0
- package/dist/providers/openCode.js +108 -2
- package/dist/providers/openCodeDatabase.d.ts +19 -0
- package/dist/providers/openCodeDatabase.js +28 -0
- package/dist/quota.d.ts +1 -1
- package/dist/quotaHistory.d.ts +1 -1
- package/dist/quotaHistory.js +14 -2
- package/dist/quotaSnapshots.d.ts +8 -2
- package/dist/schemas/index.d.ts +1 -1
- package/dist/schemas/index.js +2 -1
- package/dist/schemas/quota.d.ts +165 -0
- package/dist/schemas/quota.js +8 -1
- package/dist/schemas/quotaHistory.d.ts +2 -0
- package/dist/schemas/quotaHistory.js +1 -0
- package/dist/zaiQuota.d.ts +209 -0
- package/dist/zaiQuota.js +290 -0
- package/dist/zaiQuotaApi.d.ts +33 -0
- package/dist/zaiQuotaApi.js +271 -0
- package/dist/zaiQuotaWatcher.d.ts +97 -0
- package/dist/zaiQuotaWatcher.js +260 -0
- package/package.json +1 -1
package/dist/zaiQuota.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ZAI_PROVIDER_IDS = exports.ZAI_PROMPT_INVOCATIONS = exports.ZAI_TIER_BUDGETS = void 0;
|
|
4
|
+
exports.isZaiProviderId = isZaiProviderId;
|
|
5
|
+
exports.turnTokenWeight = turnTokenWeight;
|
|
6
|
+
exports.accumulateZaiUsage = accumulateZaiUsage;
|
|
7
|
+
exports.resolveZaiTier = resolveZaiTier;
|
|
8
|
+
exports.inferZaiQuotaState = inferZaiQuotaState;
|
|
9
|
+
exports.parseZaiQuotaError = parseZaiQuotaError;
|
|
10
|
+
exports.extractNextFlushTime = extractNextFlushTime;
|
|
11
|
+
exports.makeUnavailableZaiQuotaState = makeUnavailableZaiQuotaState;
|
|
12
|
+
exports.rowsToZaiTurnsAndErrors = rowsToZaiTurnsAndErrors;
|
|
13
|
+
// ── Tier budgets ──
|
|
14
|
+
/**
|
|
15
|
+
* Published z.ai coding-plan prompt budgets.
|
|
16
|
+
*
|
|
17
|
+
* Source: https://docs.z.ai/devpack/overview & /devpack/faq.
|
|
18
|
+
* "One prompt ≈ one query; each prompt is estimated to invoke the model
|
|
19
|
+
* 15–20 times." We use the midpoint (17.5) when converting observed
|
|
20
|
+
* assistant turns into prompt equivalents.
|
|
21
|
+
*/
|
|
22
|
+
exports.ZAI_TIER_BUDGETS = {
|
|
23
|
+
lite: { fiveHour: 80, weekly: 400 },
|
|
24
|
+
pro: { fiveHour: 400, weekly: 2000 },
|
|
25
|
+
max: { fiveHour: 1600, weekly: 8000 },
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Midpoint of z.ai's documented "15–20 model invocations per prompt" range.
|
|
29
|
+
* Used to convert accumulated assistant turns into prompt equivalents.
|
|
30
|
+
* Calibration note: this constant may need per-tier adjustment after
|
|
31
|
+
* real-world validation against the z.ai web UI.
|
|
32
|
+
*/
|
|
33
|
+
exports.ZAI_PROMPT_INVOCATIONS = 17.5;
|
|
34
|
+
const FIVE_HOUR_MS = 5 * 3_600_000;
|
|
35
|
+
const SEVEN_DAY_MS = 7 * 86_400_000;
|
|
36
|
+
/**
|
|
37
|
+
* Provider IDs that OpenCode tags on z.ai-routed messages.
|
|
38
|
+
* `zai-coding-plan` is the Coding Plan key; `zai` is the bare API key.
|
|
39
|
+
*/
|
|
40
|
+
exports.ZAI_PROVIDER_IDS = ['zai', 'zai-coding-plan'];
|
|
41
|
+
function isZaiProviderId(value) {
|
|
42
|
+
return value === 'zai' || value === 'zai-coding-plan';
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Sums the token fields of a single turn into a scalar.
|
|
46
|
+
* Cache reads are weighted at 0.1× (Anthropic convention) to avoid
|
|
47
|
+
* over-counting repeated context. Output and reasoning tokens are weighted 1×.
|
|
48
|
+
*/
|
|
49
|
+
function turnTokenWeight(turn) {
|
|
50
|
+
return (turn.inputTokens +
|
|
51
|
+
turn.outputTokens +
|
|
52
|
+
Math.round(turn.cacheReadTokens * 0.1) +
|
|
53
|
+
turn.cacheWriteTokens +
|
|
54
|
+
(turn.reasoningTokens || 0));
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Reduces a stream of z.ai-routed assistant turns into rolling-window usage.
|
|
58
|
+
*
|
|
59
|
+
* Pure & stateless: the caller is responsible for passing the relevant turns.
|
|
60
|
+
* Turns outside the 7-day window are ignored; turns inside the 7-day window
|
|
61
|
+
* but outside the 5-hour window still count toward weekly usage.
|
|
62
|
+
*/
|
|
63
|
+
function accumulateZaiUsage(turns, nowMs = Date.now()) {
|
|
64
|
+
const fiveHourCutoff = nowMs - FIVE_HOUR_MS;
|
|
65
|
+
const weeklyCutoff = nowMs - SEVEN_DAY_MS;
|
|
66
|
+
let fiveHourTurns = 0;
|
|
67
|
+
let weeklyTurns = 0;
|
|
68
|
+
let fiveHourTokens = 0;
|
|
69
|
+
let weeklyTokens = 0;
|
|
70
|
+
let fiveHourStartedAtMs = null;
|
|
71
|
+
let weeklyStartedAtMs = null;
|
|
72
|
+
for (const turn of turns) {
|
|
73
|
+
if (turn.timestampMs < weeklyCutoff)
|
|
74
|
+
continue;
|
|
75
|
+
weeklyTurns += 1;
|
|
76
|
+
weeklyTokens += turnTokenWeight(turn);
|
|
77
|
+
if (weeklyStartedAtMs === null || turn.timestampMs < weeklyStartedAtMs) {
|
|
78
|
+
weeklyStartedAtMs = turn.timestampMs;
|
|
79
|
+
}
|
|
80
|
+
if (turn.timestampMs >= fiveHourCutoff) {
|
|
81
|
+
fiveHourTurns += 1;
|
|
82
|
+
fiveHourTokens += turnTokenWeight(turn);
|
|
83
|
+
if (fiveHourStartedAtMs === null || turn.timestampMs < fiveHourStartedAtMs) {
|
|
84
|
+
fiveHourStartedAtMs = turn.timestampMs;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
fiveHourTurns,
|
|
90
|
+
weeklyTurns,
|
|
91
|
+
fiveHourTokens,
|
|
92
|
+
weeklyTokens,
|
|
93
|
+
fiveHourPrompts: fiveHourTurns / exports.ZAI_PROMPT_INVOCATIONS,
|
|
94
|
+
weeklyPrompts: weeklyTurns / exports.ZAI_PROMPT_INVOCATIONS,
|
|
95
|
+
fiveHourStartedAtMs,
|
|
96
|
+
weeklyStartedAtMs,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
// ── Tier resolution ──
|
|
100
|
+
/**
|
|
101
|
+
* Resolves the effective z.ai tier when the user has selected `'auto'`.
|
|
102
|
+
*
|
|
103
|
+
* Heuristic: if accumulated weekly prompts already exceed a tier's budget,
|
|
104
|
+
* the user must be on a higher tier. This under-detects at the start of a
|
|
105
|
+
* weekly cycle (a Max user looks identical to a Lite user until they cross
|
|
106
|
+
* 400 prompts/week), so callers should still expose an explicit override.
|
|
107
|
+
*/
|
|
108
|
+
function resolveZaiTier(configured, accumulated) {
|
|
109
|
+
if (configured !== 'auto')
|
|
110
|
+
return configured;
|
|
111
|
+
if (accumulated.weeklyPrompts > exports.ZAI_TIER_BUDGETS.pro.weekly)
|
|
112
|
+
return 'max';
|
|
113
|
+
if (accumulated.weeklyPrompts > exports.ZAI_TIER_BUDGETS.lite.weekly)
|
|
114
|
+
return 'pro';
|
|
115
|
+
return 'lite';
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Converts accumulated usage into a shared `QuotaState`.
|
|
119
|
+
*
|
|
120
|
+
* The two windows reuse the `fiveHour` / `sevenDay` field names for cross-
|
|
121
|
+
* provider compatibility, but are labeled "5-Hour" and "Weekly" via
|
|
122
|
+
* `fiveHourLabel` / `sevenDayLabel` — mirroring how Codex relabels its
|
|
123
|
+
* generic primary/secondary windows.
|
|
124
|
+
*
|
|
125
|
+
* Reset timestamps are best-effort because z.ai does not expose them:
|
|
126
|
+
* - `fiveHour.resetsAt` ← first turn in window + 5h, unless an error
|
|
127
|
+
* event supplied an authoritative reset.
|
|
128
|
+
* - `sevenDay.resetsAt` ← first turn in window + 7d (documented as
|
|
129
|
+
* "7 days from order time" — order time is unknown, so this is a
|
|
130
|
+
* lower bound at best).
|
|
131
|
+
*/
|
|
132
|
+
function inferZaiQuotaState(accumulated, tier, options = {}) {
|
|
133
|
+
const budget = exports.ZAI_TIER_BUDGETS[tier];
|
|
134
|
+
const capturedAt = options.capturedAt ?? new Date().toISOString();
|
|
135
|
+
const fiveHourUtil = budget.fiveHour > 0
|
|
136
|
+
? Math.min((accumulated.fiveHourPrompts / budget.fiveHour) * 100, 200)
|
|
137
|
+
: 0;
|
|
138
|
+
const weeklyUtil = budget.weekly > 0
|
|
139
|
+
? Math.min((accumulated.weeklyPrompts / budget.weekly) * 100, 200)
|
|
140
|
+
: 0;
|
|
141
|
+
const fiveHourResetsAt = options.authoritativeFiveHourResetAt
|
|
142
|
+
?? (accumulated.fiveHourStartedAtMs !== null
|
|
143
|
+
? new Date(accumulated.fiveHourStartedAtMs + FIVE_HOUR_MS).toISOString()
|
|
144
|
+
: '');
|
|
145
|
+
const sevenDayResetsAt = options.authoritativeWeeklyResetAt
|
|
146
|
+
?? (accumulated.weeklyStartedAtMs !== null
|
|
147
|
+
? new Date(accumulated.weeklyStartedAtMs + SEVEN_DAY_MS).toISOString()
|
|
148
|
+
: '');
|
|
149
|
+
const fiveHour = {
|
|
150
|
+
utilization: Math.round(fiveHourUtil * 10) / 10,
|
|
151
|
+
resetsAt: fiveHourResetsAt,
|
|
152
|
+
};
|
|
153
|
+
const sevenDay = {
|
|
154
|
+
utilization: Math.round(weeklyUtil * 10) / 10,
|
|
155
|
+
resetsAt: sevenDayResetsAt,
|
|
156
|
+
};
|
|
157
|
+
const hasAnyData = accumulated.fiveHourTurns > 0 || accumulated.weeklyTurns > 0;
|
|
158
|
+
return {
|
|
159
|
+
fiveHour,
|
|
160
|
+
sevenDay,
|
|
161
|
+
available: hasAnyData,
|
|
162
|
+
providerId: 'zai',
|
|
163
|
+
source: 'session',
|
|
164
|
+
capturedAt,
|
|
165
|
+
stale: options.stale ?? !hasAnyData,
|
|
166
|
+
fiveHourLabel: '5-Hour',
|
|
167
|
+
sevenDayLabel: 'Weekly',
|
|
168
|
+
planType: tier,
|
|
169
|
+
limitId: `zai-${tier}`,
|
|
170
|
+
limitName: `z.ai ${tier.charAt(0).toUpperCase() + tier.slice(1)}`,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* z.ai business error codes that signal quota/plan state.
|
|
175
|
+
* Source: https://docs.z.ai/api-reference/api-code
|
|
176
|
+
*/
|
|
177
|
+
const ZAI_ERROR_CODES = {
|
|
178
|
+
'1308': 'exhausted', // Usage limit reached for `{number} {unit}` (includes next_flush_time)
|
|
179
|
+
'1310': 'exhausted', // Weekly/Monthly limit exhausted (resets at next_flush_time)
|
|
180
|
+
'1313': 'fup', // Fair-Use-Policy violation — request rate restricted
|
|
181
|
+
'1309': 'expired', // GLM Coding Plan package has expired
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* Extracts a z.ai quota error from a message-error payload, if present.
|
|
185
|
+
*
|
|
186
|
+
* The reset timestamp is embedded inside the human-readable `message` text
|
|
187
|
+
* as `${next_flush_time}`. z.ai's docs interpolate the value into the
|
|
188
|
+
* message string; we parse ISO datetimes, epoch seconds, and the literal
|
|
189
|
+
* `YYYY-MM-DD HH:mm:ss` form defensively.
|
|
190
|
+
*
|
|
191
|
+
* Returns `null` when the code is not a quota-related business error.
|
|
192
|
+
*/
|
|
193
|
+
function parseZaiQuotaError(error) {
|
|
194
|
+
if (!error)
|
|
195
|
+
return null;
|
|
196
|
+
const code = String(error.code ?? '');
|
|
197
|
+
const kind = ZAI_ERROR_CODES[code];
|
|
198
|
+
if (!kind)
|
|
199
|
+
return null;
|
|
200
|
+
const message = error.message ?? '';
|
|
201
|
+
const resetsAt = extractNextFlushTime(message);
|
|
202
|
+
return { kind, resetsAt, code, message };
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Parses `${next_flush_time}` out of a z.ai error message.
|
|
206
|
+
*
|
|
207
|
+
* Handles ISO 8601 (`2025-01-31T14:00:00Z`), space-separated
|
|
208
|
+
* (`2025-01-31 14:00:00`), and epoch-seconds (1234567890) forms.
|
|
209
|
+
* Returns undefined when no parseable timestamp is found.
|
|
210
|
+
*/
|
|
211
|
+
function extractNextFlushTime(message) {
|
|
212
|
+
if (!message)
|
|
213
|
+
return undefined;
|
|
214
|
+
// ISO 8601 with optional timezone.
|
|
215
|
+
const isoMatch = message.match(/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)/);
|
|
216
|
+
if (isoMatch) {
|
|
217
|
+
const ms = Date.parse(isoMatch[1]);
|
|
218
|
+
if (Number.isFinite(ms))
|
|
219
|
+
return new Date(ms).toISOString();
|
|
220
|
+
}
|
|
221
|
+
// `YYYY-MM-DD HH:mm:ss` (no T separator) — z.ai's likely interpolated form.
|
|
222
|
+
const spaceMatch = message.match(/(\d{4}-\d{2}-\d{2}[ ]\d{2}:\d{2}:\d{2})/);
|
|
223
|
+
if (spaceMatch) {
|
|
224
|
+
const normalised = spaceMatch[1].replace(' ', 'T');
|
|
225
|
+
const ms = Date.parse(`${normalised}Z`);
|
|
226
|
+
if (Number.isFinite(ms))
|
|
227
|
+
return new Date(ms).toISOString();
|
|
228
|
+
}
|
|
229
|
+
// Epoch seconds — 10-digit integer in a plausible range.
|
|
230
|
+
const epochMatch = message.match(/(?<!\d)(\d{10})(?!\d)/);
|
|
231
|
+
if (epochMatch) {
|
|
232
|
+
const seconds = Number(epochMatch[1]);
|
|
233
|
+
if (seconds > 1_700_000_000 && seconds < 2_000_000_000) {
|
|
234
|
+
return new Date(seconds * 1000).toISOString();
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
// ── Unavailable state helper ──
|
|
240
|
+
/**
|
|
241
|
+
* Builds an unavailable z.ai `QuotaState` for the cold-start case where
|
|
242
|
+
* no z.ai traffic has been observed yet.
|
|
243
|
+
*/
|
|
244
|
+
function makeUnavailableZaiQuotaState(error = 'No z.ai usage observed yet', tier = 'lite', capturedAt = new Date().toISOString()) {
|
|
245
|
+
return {
|
|
246
|
+
fiveHour: { utilization: 0, resetsAt: '' },
|
|
247
|
+
sevenDay: { utilization: 0, resetsAt: '' },
|
|
248
|
+
available: false,
|
|
249
|
+
error,
|
|
250
|
+
providerId: 'zai',
|
|
251
|
+
source: 'session',
|
|
252
|
+
capturedAt,
|
|
253
|
+
stale: true,
|
|
254
|
+
fiveHourLabel: '5-Hour',
|
|
255
|
+
sevenDayLabel: 'Weekly',
|
|
256
|
+
planType: tier,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Converts raw OpenCode DB rows (filtered to z.ai providerIDs by the caller)
|
|
261
|
+
* into the watcher's `ZaiAssistantTurn` shape, and surfaces any trapped
|
|
262
|
+
* business errors.
|
|
263
|
+
*
|
|
264
|
+
* Returns `{ turns, errors }` so callers can replay them through
|
|
265
|
+
* `ZaiQuotaWatcher.ingestAssistantTurns` and `ingestError`.
|
|
266
|
+
*/
|
|
267
|
+
function rowsToZaiTurnsAndErrors(rows) {
|
|
268
|
+
const turns = [];
|
|
269
|
+
const errors = [];
|
|
270
|
+
for (const row of rows) {
|
|
271
|
+
turns.push({
|
|
272
|
+
timestampMs: row.timeCreated,
|
|
273
|
+
model: row.modelId,
|
|
274
|
+
inputTokens: row.inputTokens || 0,
|
|
275
|
+
outputTokens: row.outputTokens || 0,
|
|
276
|
+
cacheReadTokens: row.cacheReadTokens || 0,
|
|
277
|
+
cacheWriteTokens: row.cacheWriteTokens || 0,
|
|
278
|
+
reasoningTokens: row.reasoningTokens || 0,
|
|
279
|
+
});
|
|
280
|
+
if (row.errorCode != null || row.errorMessage) {
|
|
281
|
+
const parsed = parseZaiQuotaError({
|
|
282
|
+
code: row.errorCode ?? undefined,
|
|
283
|
+
message: row.errorMessage ?? undefined,
|
|
284
|
+
});
|
|
285
|
+
if (parsed)
|
|
286
|
+
errors.push(parsed);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return { turns, errors };
|
|
290
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { QuotaState } from './quota';
|
|
2
|
+
import type { ProviderQuotaState } from './providerQuota';
|
|
3
|
+
type ZaiSnapshotProvider = 'zai';
|
|
4
|
+
type SnapshotReader = (providerId: ZaiSnapshotProvider, accountId: string) => QuotaState | null;
|
|
5
|
+
type SnapshotWriter = (providerId: ZaiSnapshotProvider, accountId: string, quota: QuotaState) => void;
|
|
6
|
+
export type ZaiPlatform = 'ZAI' | 'ZHIPU';
|
|
7
|
+
export type ZaiCredentialSource = 'opencode' | 'env';
|
|
8
|
+
export interface ZaiCredentials {
|
|
9
|
+
authToken: string;
|
|
10
|
+
baseUrl: string;
|
|
11
|
+
platform: ZaiPlatform;
|
|
12
|
+
source: ZaiCredentialSource;
|
|
13
|
+
}
|
|
14
|
+
export interface ReadZaiCredentialsOptions {
|
|
15
|
+
openCodeDataDir?: string;
|
|
16
|
+
env?: Record<string, string | undefined>;
|
|
17
|
+
}
|
|
18
|
+
export interface ZaiQuotaApiOptions extends ReadZaiCredentialsOptions {
|
|
19
|
+
credentials?: ZaiCredentials | null;
|
|
20
|
+
fetchImpl?: typeof fetch;
|
|
21
|
+
capturedAt?: string;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
export interface ZaiQuotaResolveOptions extends ZaiQuotaApiOptions {
|
|
25
|
+
accountId?: string;
|
|
26
|
+
readSnapshot?: SnapshotReader;
|
|
27
|
+
writeSnapshot?: SnapshotWriter;
|
|
28
|
+
}
|
|
29
|
+
export declare function readZaiCredentials(options?: ReadZaiCredentialsOptions): ZaiCredentials | null;
|
|
30
|
+
export declare function quotaStateFromZaiQuotaLimitPayload(payload: unknown, capturedAt?: string): QuotaState;
|
|
31
|
+
export declare function fetchZaiQuotaFromApi(options?: ZaiQuotaApiOptions): Promise<QuotaState>;
|
|
32
|
+
export declare function resolveZaiQuota(options?: ZaiQuotaResolveOptions): Promise<ProviderQuotaState<'zai'>>;
|
|
33
|
+
export {};
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.readZaiCredentials = readZaiCredentials;
|
|
7
|
+
exports.quotaStateFromZaiQuotaLimitPayload = quotaStateFromZaiQuotaLimitPayload;
|
|
8
|
+
exports.fetchZaiQuotaFromApi = fetchZaiQuotaFromApi;
|
|
9
|
+
exports.resolveZaiQuota = resolveZaiQuota;
|
|
10
|
+
const fs_1 = __importDefault(require("fs"));
|
|
11
|
+
const os_1 = __importDefault(require("os"));
|
|
12
|
+
const path_1 = __importDefault(require("path"));
|
|
13
|
+
const quotaSnapshots_1 = require("./quotaSnapshots");
|
|
14
|
+
const DEFAULT_ZAI_BASE_URL = 'https://api.z.ai/api/anthropic';
|
|
15
|
+
const QUOTA_PATH = '/api/monitor/usage/quota/limit';
|
|
16
|
+
const DEFAULT_ACCOUNT_ID = 'default';
|
|
17
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
18
|
+
function unavailableZaiQuotaState(error, meta = {}, capturedAt = new Date().toISOString()) {
|
|
19
|
+
return {
|
|
20
|
+
fiveHour: { utilization: 0, resetsAt: '' },
|
|
21
|
+
sevenDay: { utilization: 0, resetsAt: '' },
|
|
22
|
+
available: false,
|
|
23
|
+
error,
|
|
24
|
+
providerId: 'zai',
|
|
25
|
+
source: 'api',
|
|
26
|
+
capturedAt,
|
|
27
|
+
fiveHourLabel: '5-Hour',
|
|
28
|
+
sevenDayLabel: 'Weekly',
|
|
29
|
+
...meta,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function openCodeDataDirCandidates() {
|
|
33
|
+
const candidates = [];
|
|
34
|
+
const xdg = process.env.XDG_DATA_HOME;
|
|
35
|
+
if (xdg)
|
|
36
|
+
candidates.push(path_1.default.join(xdg, 'opencode'));
|
|
37
|
+
candidates.push(path_1.default.join(os_1.default.homedir(), '.local', 'share', 'opencode'));
|
|
38
|
+
if (process.platform === 'darwin') {
|
|
39
|
+
candidates.push(path_1.default.join(os_1.default.homedir(), 'Library', 'Application Support', 'opencode'));
|
|
40
|
+
}
|
|
41
|
+
else if (process.platform === 'win32') {
|
|
42
|
+
candidates.push(path_1.default.join(process.env.LOCALAPPDATA || process.env.APPDATA || path_1.default.join(os_1.default.homedir(), 'AppData', 'Local'), 'opencode'));
|
|
43
|
+
}
|
|
44
|
+
return Array.from(new Set(candidates));
|
|
45
|
+
}
|
|
46
|
+
function readOpenCodeAuthToken(openCodeDataDir) {
|
|
47
|
+
const candidates = openCodeDataDir ? [openCodeDataDir] : openCodeDataDirCandidates();
|
|
48
|
+
for (const dataDir of candidates) {
|
|
49
|
+
try {
|
|
50
|
+
const parsed = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dataDir, 'auth.json'), 'utf8'));
|
|
51
|
+
const codingPlan = parsed['zai-coding-plan'];
|
|
52
|
+
const zai = parsed.zai;
|
|
53
|
+
if (typeof codingPlan?.key === 'string' && codingPlan.key.trim())
|
|
54
|
+
return codingPlan.key.trim();
|
|
55
|
+
if (typeof zai?.key === 'string' && zai.key.trim())
|
|
56
|
+
return zai.key.trim();
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// Try the next candidate.
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
function platformFromBaseUrl(baseUrl) {
|
|
65
|
+
if (baseUrl.includes('api.z.ai'))
|
|
66
|
+
return 'ZAI';
|
|
67
|
+
if (baseUrl.includes('open.bigmodel.cn') || baseUrl.includes('dev.bigmodel.cn'))
|
|
68
|
+
return 'ZHIPU';
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
function readZaiCredentials(options = {}) {
|
|
72
|
+
const openCodeToken = readOpenCodeAuthToken(options.openCodeDataDir);
|
|
73
|
+
if (openCodeToken) {
|
|
74
|
+
return {
|
|
75
|
+
authToken: openCodeToken,
|
|
76
|
+
baseUrl: DEFAULT_ZAI_BASE_URL,
|
|
77
|
+
platform: 'ZAI',
|
|
78
|
+
source: 'opencode',
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const env = options.env ?? process.env;
|
|
82
|
+
const authToken = env.ANTHROPIC_AUTH_TOKEN?.trim();
|
|
83
|
+
const baseUrl = env.ANTHROPIC_BASE_URL?.trim();
|
|
84
|
+
if (!authToken || !baseUrl)
|
|
85
|
+
return null;
|
|
86
|
+
const platform = platformFromBaseUrl(baseUrl);
|
|
87
|
+
if (!platform)
|
|
88
|
+
return null;
|
|
89
|
+
return {
|
|
90
|
+
authToken,
|
|
91
|
+
baseUrl,
|
|
92
|
+
platform,
|
|
93
|
+
source: 'env',
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function quotaLimitUrl(baseUrl) {
|
|
97
|
+
try {
|
|
98
|
+
const parsed = new URL(baseUrl);
|
|
99
|
+
return `${parsed.protocol}//${parsed.host}${QUOTA_PATH}`;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function tokenLimitEntries(payload) {
|
|
106
|
+
const limits = payload.data?.limits ?? payload.limits ?? [];
|
|
107
|
+
return limits.filter((item) => item?.type === 'TOKENS_LIMIT' && typeof item.percentage === 'number');
|
|
108
|
+
}
|
|
109
|
+
function isFiveHourLimit(item) {
|
|
110
|
+
return item.type === 'TOKENS_LIMIT' && item.unit === 3 && item.number === 5;
|
|
111
|
+
}
|
|
112
|
+
function isWeeklyLimit(item) {
|
|
113
|
+
return item.type === 'TOKENS_LIMIT' && item.unit === 6 && item.number === 1;
|
|
114
|
+
}
|
|
115
|
+
function isoFromEpochMs(value) {
|
|
116
|
+
if (value == null)
|
|
117
|
+
return '';
|
|
118
|
+
const ms = typeof value === 'number' ? value : Number(value);
|
|
119
|
+
if (!Number.isFinite(ms) || ms <= 0)
|
|
120
|
+
return '';
|
|
121
|
+
return new Date(ms).toISOString();
|
|
122
|
+
}
|
|
123
|
+
function displayPlanName(level) {
|
|
124
|
+
if (!level)
|
|
125
|
+
return 'z.ai Coding Plan';
|
|
126
|
+
return `z.ai ${level.charAt(0).toUpperCase()}${level.slice(1)}`;
|
|
127
|
+
}
|
|
128
|
+
function quotaStateFromZaiQuotaLimitPayload(payload, capturedAt = new Date().toISOString()) {
|
|
129
|
+
const data = payload;
|
|
130
|
+
const tokenLimits = tokenLimitEntries(data);
|
|
131
|
+
const fiveHourLimit = tokenLimits.find(isFiveHourLimit) ?? tokenLimits[0];
|
|
132
|
+
const weeklyLimit = tokenLimits.find(isWeeklyLimit) ?? tokenLimits.find(item => item !== fiveHourLimit);
|
|
133
|
+
const level = data.data?.level;
|
|
134
|
+
if (!fiveHourLimit || !weeklyLimit) {
|
|
135
|
+
return unavailableZaiQuotaState('z.ai quota API returned no token quota windows.', {
|
|
136
|
+
failureKind: 'unknown',
|
|
137
|
+
}, capturedAt);
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
fiveHour: {
|
|
141
|
+
utilization: fiveHourLimit.percentage ?? 0,
|
|
142
|
+
resetsAt: isoFromEpochMs(fiveHourLimit.nextResetTime),
|
|
143
|
+
},
|
|
144
|
+
sevenDay: {
|
|
145
|
+
utilization: weeklyLimit.percentage ?? 0,
|
|
146
|
+
resetsAt: isoFromEpochMs(weeklyLimit.nextResetTime),
|
|
147
|
+
},
|
|
148
|
+
available: true,
|
|
149
|
+
providerId: 'zai',
|
|
150
|
+
source: 'api',
|
|
151
|
+
capturedAt,
|
|
152
|
+
fiveHourLabel: '5-Hour',
|
|
153
|
+
sevenDayLabel: 'Weekly',
|
|
154
|
+
planType: level,
|
|
155
|
+
limitId: level ? `zai-${level}` : 'zai-coding-plan',
|
|
156
|
+
limitName: displayPlanName(level),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function parseRetryAfterMs(retryAfter) {
|
|
160
|
+
if (!retryAfter)
|
|
161
|
+
return undefined;
|
|
162
|
+
const seconds = Number(retryAfter);
|
|
163
|
+
if (Number.isFinite(seconds) && seconds >= 0)
|
|
164
|
+
return seconds * 1000;
|
|
165
|
+
const dateMs = Date.parse(retryAfter);
|
|
166
|
+
if (Number.isFinite(dateMs))
|
|
167
|
+
return Math.max(0, dateMs - Date.now());
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
function failureKindForStatus(status) {
|
|
171
|
+
if (status === 401 || status === 403)
|
|
172
|
+
return 'auth';
|
|
173
|
+
if (status === 429)
|
|
174
|
+
return 'rate_limit';
|
|
175
|
+
if (status >= 500)
|
|
176
|
+
return 'server';
|
|
177
|
+
return 'unknown';
|
|
178
|
+
}
|
|
179
|
+
function sanitizeErrorMessage(message, authToken) {
|
|
180
|
+
let result = message;
|
|
181
|
+
if (authToken) {
|
|
182
|
+
result = result.split(authToken).join('<redacted>');
|
|
183
|
+
}
|
|
184
|
+
return result.replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/g, 'Bearer <redacted>');
|
|
185
|
+
}
|
|
186
|
+
async function fetchZaiQuotaFromApi(options = {}) {
|
|
187
|
+
const capturedAt = options.capturedAt ?? new Date().toISOString();
|
|
188
|
+
const credentials = options.credentials ?? readZaiCredentials(options);
|
|
189
|
+
if (!credentials) {
|
|
190
|
+
return unavailableZaiQuotaState('No z.ai credentials found. Sign in to OpenCode with z.ai or set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN.', { failureKind: 'auth' }, capturedAt);
|
|
191
|
+
}
|
|
192
|
+
const url = quotaLimitUrl(credentials.baseUrl);
|
|
193
|
+
if (!url) {
|
|
194
|
+
return unavailableZaiQuotaState('Invalid z.ai base URL.', { failureKind: 'unknown' }, capturedAt);
|
|
195
|
+
}
|
|
196
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
197
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
198
|
+
const controller = new AbortController();
|
|
199
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
200
|
+
timeout.unref?.();
|
|
201
|
+
try {
|
|
202
|
+
const response = await fetchImpl(url, {
|
|
203
|
+
method: 'GET',
|
|
204
|
+
headers: {
|
|
205
|
+
Authorization: credentials.authToken,
|
|
206
|
+
'Accept-Language': 'en-US,en',
|
|
207
|
+
Accept: 'application/json',
|
|
208
|
+
'Content-Type': 'application/json',
|
|
209
|
+
},
|
|
210
|
+
signal: controller.signal,
|
|
211
|
+
});
|
|
212
|
+
const body = await response.text();
|
|
213
|
+
let parsed;
|
|
214
|
+
try {
|
|
215
|
+
parsed = JSON.parse(body);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
parsed = null;
|
|
219
|
+
}
|
|
220
|
+
if (!response.ok) {
|
|
221
|
+
const failureKind = failureKindForStatus(response.status);
|
|
222
|
+
const retryAfterMs = parseRetryAfterMs(response.headers.get('retry-after'));
|
|
223
|
+
const detail = parsed && typeof parsed === 'object' && 'msg' in parsed
|
|
224
|
+
? String(parsed.msg ?? '')
|
|
225
|
+
: '';
|
|
226
|
+
const baseMessage = failureKind === 'auth'
|
|
227
|
+
? `z.ai quota API rejected credentials (HTTP ${response.status}).`
|
|
228
|
+
: `z.ai quota API error (HTTP ${response.status}).`;
|
|
229
|
+
return unavailableZaiQuotaState(sanitizeErrorMessage([baseMessage, detail].filter(Boolean).join(' '), credentials.authToken), { failureKind, httpStatus: response.status, retryAfterMs }, capturedAt);
|
|
230
|
+
}
|
|
231
|
+
return quotaStateFromZaiQuotaLimitPayload(parsed, capturedAt);
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
const isAbort = error instanceof Error && error.name === 'AbortError';
|
|
235
|
+
return unavailableZaiQuotaState(isAbort ? 'z.ai quota API timed out.' : 'z.ai quota API network error.', { failureKind: 'network' }, capturedAt);
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
clearTimeout(timeout);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function enrichZaiQuota(state) {
|
|
242
|
+
return {
|
|
243
|
+
...state,
|
|
244
|
+
runtimeProvider: 'zai',
|
|
245
|
+
providerId: 'zai',
|
|
246
|
+
fiveHourLabel: state.fiveHourLabel ?? '5-Hour',
|
|
247
|
+
sevenDayLabel: state.sevenDayLabel ?? 'Weekly',
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
async function resolveZaiQuota(options = {}) {
|
|
251
|
+
const accountId = options.accountId ?? DEFAULT_ACCOUNT_ID;
|
|
252
|
+
const readSnapshot = options.readSnapshot ?? quotaSnapshots_1.readQuotaSnapshot;
|
|
253
|
+
const writeSnapshot = options.writeSnapshot ?? quotaSnapshots_1.writeQuotaSnapshot;
|
|
254
|
+
const apiQuota = await fetchZaiQuotaFromApi(options);
|
|
255
|
+
if (apiQuota.available) {
|
|
256
|
+
writeSnapshot('zai', accountId, apiQuota);
|
|
257
|
+
return enrichZaiQuota(apiQuota);
|
|
258
|
+
}
|
|
259
|
+
const cached = readSnapshot('zai', accountId);
|
|
260
|
+
if (cached) {
|
|
261
|
+
return enrichZaiQuota({
|
|
262
|
+
...cached,
|
|
263
|
+
providerId: 'zai',
|
|
264
|
+
source: 'cache',
|
|
265
|
+
stale: true,
|
|
266
|
+
fiveHourLabel: cached.fiveHourLabel ?? '5-Hour',
|
|
267
|
+
sevenDayLabel: cached.sevenDayLabel ?? 'Weekly',
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
return enrichZaiQuota(apiQuota);
|
|
271
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { QuotaHistorySample } from './quotaHistory';
|
|
2
|
+
import { type ZaiAccumulatedUsage, type ZaiAssistantTurn, type ZaiTier } from './zaiQuota';
|
|
3
|
+
import type { QuotaState } from './quota';
|
|
4
|
+
import type { ProviderQuotaState } from './providerQuota';
|
|
5
|
+
import type { Disposable } from './quotaPoller';
|
|
6
|
+
/** Storage key wider than `AccountProviderId` — z.ai has no full account
|
|
7
|
+
* management in v1, but we still need a stable key for snapshot/history. */
|
|
8
|
+
type ZaiSnapshotProvider = 'zai';
|
|
9
|
+
type TierResolver = (configured: ZaiTier | 'auto', accumulated: ZaiAccumulatedUsage) => ZaiTier;
|
|
10
|
+
type SnapshotReader = (providerId: ZaiSnapshotProvider, accountId: string) => QuotaState | null;
|
|
11
|
+
type SnapshotWriter = (providerId: ZaiSnapshotProvider, accountId: string, quota: QuotaState) => void;
|
|
12
|
+
type HistoryAppender = (sample: QuotaHistorySample) => void | Promise<void>;
|
|
13
|
+
export interface ZaiQuotaWatcherOptions {
|
|
14
|
+
/** Configured tier. Default: `'auto'` (heuristic from observed usage). */
|
|
15
|
+
tier?: ZaiTier | 'auto';
|
|
16
|
+
/** Override tier resolution (used by tests). Default: `resolveZaiTier`. */
|
|
17
|
+
resolveTier?: TierResolver;
|
|
18
|
+
/** Override snapshot read (used by tests). */
|
|
19
|
+
readSnapshot?: SnapshotReader;
|
|
20
|
+
/** Override snapshot write (used by tests). */
|
|
21
|
+
writeSnapshot?: SnapshotWriter;
|
|
22
|
+
/** Override history append (used by tests). */
|
|
23
|
+
appendHistorySample?: HistoryAppender;
|
|
24
|
+
/** Stable workspace identifier — when provided, samples are appended to per-workspace history. */
|
|
25
|
+
workspaceId?: string;
|
|
26
|
+
/** Account identifier for snapshot persistence. Default: `'default'`. */
|
|
27
|
+
accountId?: string;
|
|
28
|
+
/** Minimum time between recomputes (ms). Default: 1000. */
|
|
29
|
+
recomputeDebounceMs?: number;
|
|
30
|
+
/** Time between prunes of in-memory turn buffer (ms). Default: 60000. */
|
|
31
|
+
pruneIntervalMs?: number;
|
|
32
|
+
/** Internal clock for tests. */
|
|
33
|
+
now?: () => number;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Watches z.ai-routed OpenCode activity and emits derived `QuotaState`.
|
|
37
|
+
*
|
|
38
|
+
* The watcher is event-driven (not a poller): call `ingestAssistantTurn`
|
|
39
|
+
* for every observed z.ai assistant turn, and `ingestError` whenever a
|
|
40
|
+
* z.ai business error is observed. The watcher debounces recompute and
|
|
41
|
+
* emits via `onUpdate` / `onQuotaUpdate`.
|
|
42
|
+
*/
|
|
43
|
+
export declare class ZaiQuotaWatcher implements Disposable {
|
|
44
|
+
private readonly tier;
|
|
45
|
+
private readonly resolveTier;
|
|
46
|
+
private readonly readSnapshot;
|
|
47
|
+
private readonly writeSnapshot;
|
|
48
|
+
private readonly appendHistorySample;
|
|
49
|
+
private readonly workspaceId;
|
|
50
|
+
private readonly accountId;
|
|
51
|
+
private readonly recomputeDebounceMs;
|
|
52
|
+
private readonly pruneIntervalMs;
|
|
53
|
+
private readonly now;
|
|
54
|
+
private readonly listeners;
|
|
55
|
+
/** In-memory rolling 7-day buffer of observed turns. */
|
|
56
|
+
private turns;
|
|
57
|
+
/** Most recent authoritative 5h reset (parsed from a z.ai error event). */
|
|
58
|
+
private authoritativeFiveHourResetAt;
|
|
59
|
+
/** Most recent authoritative weekly reset (parsed from a z.ai error event). */
|
|
60
|
+
private authoritativeWeeklyResetAt;
|
|
61
|
+
/** Most recent trapped error (so consumers can show "rate-limited until X"). */
|
|
62
|
+
private lastError;
|
|
63
|
+
private lastEmissionKey;
|
|
64
|
+
private pendingRecomputeTimer;
|
|
65
|
+
private pruneTimer;
|
|
66
|
+
private running;
|
|
67
|
+
constructor(options?: ZaiQuotaWatcherOptions);
|
|
68
|
+
start(): void;
|
|
69
|
+
stop(): void;
|
|
70
|
+
dispose(): void;
|
|
71
|
+
onUpdate(cb: (state: ProviderQuotaState<'zai'>) => void): Disposable;
|
|
72
|
+
onQuotaUpdate(cb: (state: ProviderQuotaState<'zai'>) => void): Disposable;
|
|
73
|
+
/** Feed an observed z.ai assistant turn. Schedules a debounced recompute. */
|
|
74
|
+
ingestAssistantTurn(turn: ZaiAssistantTurn): void;
|
|
75
|
+
/**
|
|
76
|
+
* Feed multiple turns at once (used for cold-start seeding from the DB).
|
|
77
|
+
* Schedules a single debounced recompute.
|
|
78
|
+
*/
|
|
79
|
+
ingestAssistantTurns(turns: readonly ZaiAssistantTurn[]): void;
|
|
80
|
+
/** Feed a z.ai error event. Triggers an immediate recompute + emit. */
|
|
81
|
+
ingestError(error: {
|
|
82
|
+
code?: string | number;
|
|
83
|
+
message?: string;
|
|
84
|
+
type?: string;
|
|
85
|
+
}): boolean;
|
|
86
|
+
/** Force a recompute+emit now (skipping the debounce). Used by tests. */
|
|
87
|
+
refresh(): void;
|
|
88
|
+
/** Current in-memory turn count (testing/diagnostics). */
|
|
89
|
+
get bufferedTurnCount(): number;
|
|
90
|
+
private scheduleRecompute;
|
|
91
|
+
private recomputeAndEmit;
|
|
92
|
+
private maybeAppendHistory;
|
|
93
|
+
private emitCachedOrUnavailable;
|
|
94
|
+
private emitState;
|
|
95
|
+
private pruneOldTurns;
|
|
96
|
+
}
|
|
97
|
+
export {};
|