sidekick-shared 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +14 -2
  2. package/dist/accountManager.d.ts +52 -0
  3. package/dist/accountManager.js +344 -0
  4. package/dist/accounts.d.ts +3 -0
  5. package/dist/accounts.js +180 -40
  6. package/dist/autoSwitch.d.ts +70 -0
  7. package/dist/autoSwitch.js +160 -0
  8. package/dist/claudeProfiles.d.ts +12 -0
  9. package/dist/claudeProfiles.js +96 -0
  10. package/dist/codexProfiles.d.ts +6 -2
  11. package/dist/codexProfiles.js +6 -1
  12. package/dist/credentialIO.d.ts +3 -2
  13. package/dist/credentialIO.js +11 -9
  14. package/dist/ensureDefaultAccounts.js +6 -0
  15. package/dist/index.d.ts +16 -3
  16. package/dist/index.js +60 -5
  17. package/dist/multiProviderQuotaService.d.ts +10 -0
  18. package/dist/multiProviderQuotaService.js +34 -0
  19. package/dist/providerQuota.d.ts +2 -1
  20. package/dist/providers/detect.js +3 -13
  21. package/dist/providers/openCode.d.ts +31 -0
  22. package/dist/providers/openCode.js +108 -2
  23. package/dist/providers/openCodeDatabase.d.ts +19 -0
  24. package/dist/providers/openCodeDatabase.js +28 -0
  25. package/dist/quota.d.ts +1 -1
  26. package/dist/quotaHistory.d.ts +1 -1
  27. package/dist/quotaHistory.js +14 -2
  28. package/dist/quotaSnapshots.d.ts +8 -2
  29. package/dist/schemas/accountManager.d.ts +104 -0
  30. package/dist/schemas/accountManager.js +84 -0
  31. package/dist/schemas/assistantTurn.d.ts +5 -5
  32. package/dist/schemas/index.d.ts +5 -1
  33. package/dist/schemas/index.js +10 -1
  34. package/dist/schemas/quota.d.ts +185 -20
  35. package/dist/schemas/quota.js +8 -1
  36. package/dist/schemas/quotaHistory.d.ts +3 -1
  37. package/dist/schemas/quotaHistory.js +1 -0
  38. package/dist/terminalSync.d.ts +7 -0
  39. package/dist/terminalSync.js +202 -0
  40. package/dist/zaiQuota.d.ts +209 -0
  41. package/dist/zaiQuota.js +290 -0
  42. package/dist/zaiQuotaWatcher.d.ts +97 -0
  43. package/dist/zaiQuotaWatcher.js +259 -0
  44. package/package.json +1 -1
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Stateless quota accumulator for z.ai coding plans.
3
+ *
4
+ * z.ai (GLM Coding Plan) does not expose an HTTP quota/usage API (verified
5
+ * against the canonical OpenAPI spec at https://docs.z.ai/openapi.json).
6
+ * The only programmatic signals are:
7
+ *
8
+ * 1. Per-call token `usage` returned inline on each chat completion —
9
+ * which OpenCode persists into `opencode.db` message rows tagged with
10
+ * `providerID ∈ {"zai", "zai-coding-plan"}`.
11
+ * 2. Business error codes (`1308` / `1310` / `1313` / `1309`) returned
12
+ * when a limit is actually hit, with `${next_flush_time}` embedded
13
+ * in the human-readable message text.
14
+ *
15
+ * This module is therefore a **derivation** rather than a fetcher: callers
16
+ * feed it observed assistant turns (and any error events), and it computes
17
+ * an estimated `QuotaState` keyed against the published per-tier budgets.
18
+ *
19
+ * Polling / eventing / persistence are the caller's responsibility —
20
+ * see `ZaiQuotaWatcher` for the bundled watcher.
21
+ */
22
+ import type { QuotaState } from './quota';
23
+ /**
24
+ * Published z.ai coding-plan prompt budgets.
25
+ *
26
+ * Source: https://docs.z.ai/devpack/overview & /devpack/faq.
27
+ * "One prompt ≈ one query; each prompt is estimated to invoke the model
28
+ * 15–20 times." We use the midpoint (17.5) when converting observed
29
+ * assistant turns into prompt equivalents.
30
+ */
31
+ export declare const ZAI_TIER_BUDGETS: {
32
+ readonly lite: {
33
+ readonly fiveHour: 80;
34
+ readonly weekly: 400;
35
+ };
36
+ readonly pro: {
37
+ readonly fiveHour: 400;
38
+ readonly weekly: 2000;
39
+ };
40
+ readonly max: {
41
+ readonly fiveHour: 1600;
42
+ readonly weekly: 8000;
43
+ };
44
+ };
45
+ export type ZaiTier = 'lite' | 'pro' | 'max';
46
+ /**
47
+ * Midpoint of z.ai's documented "15–20 model invocations per prompt" range.
48
+ * Used to convert accumulated assistant turns into prompt equivalents.
49
+ * Calibration note: this constant may need per-tier adjustment after
50
+ * real-world validation against the z.ai web UI.
51
+ */
52
+ export declare const ZAI_PROMPT_INVOCATIONS = 17.5;
53
+ /**
54
+ * Provider IDs that OpenCode tags on z.ai-routed messages.
55
+ * `zai-coding-plan` is the Coding Plan key; `zai` is the bare API key.
56
+ */
57
+ export declare const ZAI_PROVIDER_IDS: readonly ["zai", "zai-coding-plan"];
58
+ export type ZaiProviderId = (typeof ZAI_PROVIDER_IDS)[number];
59
+ export declare function isZaiProviderId(value: unknown): value is ZaiProviderId;
60
+ /**
61
+ * Minimal description of a z.ai-routed assistant turn needed to accumulate
62
+ * usage. Mirrors the fields OpenCode already extracts via its parser
63
+ * (`openCodeParser.ts:346-357`). Tokens are Anthropic-style for cross-
64
+ * provider comparability; cost is omitted (always 0 for z.ai).
65
+ *
66
+ * `timestampMs` is when the assistant turn completed (epoch milliseconds).
67
+ */
68
+ export interface ZaiAssistantTurn {
69
+ timestampMs: number;
70
+ model?: string;
71
+ inputTokens: number;
72
+ outputTokens: number;
73
+ cacheReadTokens: number;
74
+ cacheWriteTokens: number;
75
+ reasoningTokens: number;
76
+ }
77
+ export interface ZaiAccumulatedUsage {
78
+ /** Number of z.ai assistant turns inside the 5-hour window. */
79
+ fiveHourTurns: number;
80
+ /** Number of z.ai assistant turns inside the 7-day window. */
81
+ weeklyTurns: number;
82
+ /** Sum of token fields across the 5-hour window. */
83
+ fiveHourTokens: number;
84
+ /** Sum of token fields across the 7-day window. */
85
+ weeklyTokens: number;
86
+ /** Estimated prompts consumed in the 5-hour window (turns / 17.5). */
87
+ fiveHourPrompts: number;
88
+ /** Estimated prompts consumed in the 7-day window (turns / 17.5). */
89
+ weeklyPrompts: number;
90
+ /** Earliest turn timestamp inside the 5-hour window (epoch ms), or null. */
91
+ fiveHourStartedAtMs: number | null;
92
+ /** Earliest turn timestamp inside the 7-day window (epoch ms), or null. */
93
+ weeklyStartedAtMs: number | null;
94
+ }
95
+ /**
96
+ * Sums the token fields of a single turn into a scalar.
97
+ * Cache reads are weighted at 0.1× (Anthropic convention) to avoid
98
+ * over-counting repeated context. Output and reasoning tokens are weighted 1×.
99
+ */
100
+ export declare function turnTokenWeight(turn: Pick<ZaiAssistantTurn, 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens' | 'reasoningTokens'>): number;
101
+ /**
102
+ * Reduces a stream of z.ai-routed assistant turns into rolling-window usage.
103
+ *
104
+ * Pure & stateless: the caller is responsible for passing the relevant turns.
105
+ * Turns outside the 7-day window are ignored; turns inside the 7-day window
106
+ * but outside the 5-hour window still count toward weekly usage.
107
+ */
108
+ export declare function accumulateZaiUsage(turns: readonly ZaiAssistantTurn[], nowMs?: number): ZaiAccumulatedUsage;
109
+ /**
110
+ * Resolves the effective z.ai tier when the user has selected `'auto'`.
111
+ *
112
+ * Heuristic: if accumulated weekly prompts already exceed a tier's budget,
113
+ * the user must be on a higher tier. This under-detects at the start of a
114
+ * weekly cycle (a Max user looks identical to a Lite user until they cross
115
+ * 400 prompts/week), so callers should still expose an explicit override.
116
+ */
117
+ export declare function resolveZaiTier(configured: ZaiTier | 'auto', accumulated: ZaiAccumulatedUsage): ZaiTier;
118
+ export interface InferZaiQuotaStateOptions {
119
+ /** ISO timestamp to stamp on the sample. Default: now. */
120
+ capturedAt?: string;
121
+ /** Mark the sample stale when the windows aren't fully observed yet. */
122
+ stale?: boolean;
123
+ /** Authoritative reset timestamp from a trapped 1308/1310 error. */
124
+ authoritativeFiveHourResetAt?: string;
125
+ authoritativeWeeklyResetAt?: string;
126
+ }
127
+ /**
128
+ * Converts accumulated usage into a shared `QuotaState`.
129
+ *
130
+ * The two windows reuse the `fiveHour` / `sevenDay` field names for cross-
131
+ * provider compatibility, but are labeled "5-Hour" and "Weekly" via
132
+ * `fiveHourLabel` / `sevenDayLabel` — mirroring how Codex relabels its
133
+ * generic primary/secondary windows.
134
+ *
135
+ * Reset timestamps are best-effort because z.ai does not expose them:
136
+ * - `fiveHour.resetsAt` ← first turn in window + 5h, unless an error
137
+ * event supplied an authoritative reset.
138
+ * - `sevenDay.resetsAt` ← first turn in window + 7d (documented as
139
+ * "7 days from order time" — order time is unknown, so this is a
140
+ * lower bound at best).
141
+ */
142
+ export declare function inferZaiQuotaState(accumulated: ZaiAccumulatedUsage, tier: ZaiTier, options?: InferZaiQuotaStateOptions): QuotaState;
143
+ export type ZaiQuotaErrorKind = 'exhausted' | 'fup' | 'expired' | 'invalid';
144
+ export interface ZaiQuotaError {
145
+ kind: ZaiQuotaErrorKind;
146
+ /** ISO timestamp parsed from `${next_flush_time}` in the error message, if present. */
147
+ resetsAt?: string;
148
+ /** The raw business error code from z.ai. */
149
+ code: string;
150
+ /** Human-readable message. */
151
+ message: string;
152
+ }
153
+ /**
154
+ * Extracts a z.ai quota error from a message-error payload, if present.
155
+ *
156
+ * The reset timestamp is embedded inside the human-readable `message` text
157
+ * as `${next_flush_time}`. z.ai's docs interpolate the value into the
158
+ * message string; we parse ISO datetimes, epoch seconds, and the literal
159
+ * `YYYY-MM-DD HH:mm:ss` form defensively.
160
+ *
161
+ * Returns `null` when the code is not a quota-related business error.
162
+ */
163
+ export declare function parseZaiQuotaError(error: {
164
+ code?: string | number;
165
+ message?: string;
166
+ type?: string;
167
+ }): ZaiQuotaError | null;
168
+ /**
169
+ * Parses `${next_flush_time}` out of a z.ai error message.
170
+ *
171
+ * Handles ISO 8601 (`2025-01-31T14:00:00Z`), space-separated
172
+ * (`2025-01-31 14:00:00`), and epoch-seconds (1234567890) forms.
173
+ * Returns undefined when no parseable timestamp is found.
174
+ */
175
+ export declare function extractNextFlushTime(message: string): string | undefined;
176
+ /**
177
+ * Builds an unavailable z.ai `QuotaState` for the cold-start case where
178
+ * no z.ai traffic has been observed yet.
179
+ */
180
+ export declare function makeUnavailableZaiQuotaState(error?: string, tier?: ZaiTier, capturedAt?: string): QuotaState;
181
+ /**
182
+ * Shape of a row returned by `OpenCodeDatabase.getAssistantMessagesByProviderId`.
183
+ * Defined here to keep the sidekick-shared helper self-contained without
184
+ * leaking the OpenCode db module into the public quota surface.
185
+ */
186
+ export interface ZaiOpenCodeRow {
187
+ timeCreated: number;
188
+ modelId: string;
189
+ providerId: string;
190
+ inputTokens: number;
191
+ outputTokens: number;
192
+ cacheReadTokens: number;
193
+ cacheWriteTokens: number;
194
+ reasoningTokens: number;
195
+ errorMessage: string | null;
196
+ errorCode: string | null;
197
+ }
198
+ /**
199
+ * Converts raw OpenCode DB rows (filtered to z.ai providerIDs by the caller)
200
+ * into the watcher's `ZaiAssistantTurn` shape, and surfaces any trapped
201
+ * business errors.
202
+ *
203
+ * Returns `{ turns, errors }` so callers can replay them through
204
+ * `ZaiQuotaWatcher.ingestAssistantTurns` and `ingestError`.
205
+ */
206
+ export declare function rowsToZaiTurnsAndErrors(rows: readonly ZaiOpenCodeRow[]): {
207
+ turns: ZaiAssistantTurn[];
208
+ errors: ZaiQuotaError[];
209
+ };
@@ -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,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 {};