modelpace 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,337 @@
1
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
2
+
3
+ function toIsoTimestamp(value) {
4
+ if (value == null) return null;
5
+ if (typeof value === 'number' && Number.isFinite(value)) {
6
+ const millis = value < 1e12 ? value * 1000 : value;
7
+ const d = new Date(millis);
8
+ return Number.isFinite(d.getTime()) ? d.toISOString() : null;
9
+ }
10
+ if (typeof value === 'string' && value.trim()) {
11
+ const ms = Date.parse(value);
12
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
13
+ }
14
+ return null;
15
+ }
16
+
17
+ function clampPercent(value) {
18
+ if (!Number.isFinite(value)) return null;
19
+ return Math.max(0, Math.min(100, value));
20
+ }
21
+
22
+ export function inferWindowPool(driver, window) {
23
+ if (typeof window?.pool === 'string' && window.pool.trim()) {
24
+ return window.pool.trim().toLowerCase();
25
+ }
26
+ if (driver !== 'antigravity' && driver !== 'gemini') return null;
27
+ const id = String(window?.id ?? '').toLowerCase();
28
+ const label = String(window?.label ?? '').toLowerCase();
29
+ if (id.startsWith('3p-') || label.includes('3p') || id.startsWith('claude-') || id.startsWith('gpt-')) {
30
+ return id.startsWith('claude-') ? 'claude' : id.startsWith('gpt-') ? 'gpt' : '3p';
31
+ }
32
+ if (id.includes('argon') || label.includes('argon')) return 'argon';
33
+ if (id.includes('carbon') || label.includes('carbon')) return 'carbon';
34
+ if (id.startsWith('gemini') || label.includes('gemini')) return 'gemini';
35
+ return null;
36
+ }
37
+
38
+ function inferWindowDuration(driver, win) {
39
+ if (Number.isFinite(win?.windowDurationMins) && win.windowDurationMins > 0) {
40
+ return win.windowDurationMins;
41
+ }
42
+ const id = String(win?.id ?? '');
43
+ if (driver === 'claudeAgent' || driver === 'claude') {
44
+ if (id === 'five_hour') return 300;
45
+ if (id === 'seven_day' || id.startsWith('seven_day_')) return 10080;
46
+ }
47
+ if (win?.kind === 'session') return 300;
48
+ if (win?.kind === 'weekly') return 10080;
49
+ return null;
50
+ }
51
+
52
+ function inferWindowKind(win) {
53
+ if (['session', 'weekly', 'monthly', 'other'].includes(win?.kind)) return win.kind;
54
+ const id = String(win?.id ?? '');
55
+ if (id === 'five_hour' || id === 'primary' || id.endsWith('-5h')) return 'session';
56
+ if (id === 'seven_day' || id.startsWith('seven_day_') || id === 'secondary' || id.endsWith('-weekly')) {
57
+ return 'weekly';
58
+ }
59
+ if (id === 'individual' || id === 'monthly_spend') return 'monthly';
60
+ if (Number.isFinite(win?.windowDurationMins)) {
61
+ if (win.windowDurationMins < 1440) return 'session';
62
+ if (win.windowDurationMins === 10080) return 'weekly';
63
+ if (win.windowDurationMins >= 40000) return 'monthly';
64
+ }
65
+ return 'other';
66
+ }
67
+
68
+ function inferClaudeResetType(option) {
69
+ const id = String(option?.creditId ?? '').toLowerCase();
70
+ const label = String(option?.label ?? '').toLowerCase();
71
+ const desc = String(option?.description ?? '').toLowerCase();
72
+ const combined = `${id} ${label} ${desc}`;
73
+ if (combined.includes('full') || combined.includes('all limits')) {
74
+ return { resetType: 'claudeFull', coversWindowIds: null, coversWindowPrefixes: null };
75
+ }
76
+ if (combined.includes('fable')) {
77
+ return { resetType: 'claudeFable', coversWindowIds: ['seven_day_fable'], coversWindowPrefixes: null };
78
+ }
79
+ if (combined.includes('session') || combined.includes('5-hour') || combined.includes('five_hour')) {
80
+ return { resetType: 'claudeSession', coversWindowIds: ['five_hour'], coversWindowPrefixes: null };
81
+ }
82
+ if (combined.includes('weekly') || combined.includes('7-day') || combined.includes('seven_day')) {
83
+ const modelMatch = id.match(/seven_day_([a-z0-9_]+)/) || label.match(/weekly\s*·\s*([a-z0-9_-]+)/);
84
+ if (modelMatch && !['all', 'all_models'].includes(modelMatch[1])) {
85
+ return {
86
+ resetType: 'custom',
87
+ coversWindowIds: [`seven_day_${modelMatch[1].replace(/-/g, '_')}`],
88
+ coversWindowPrefixes: null,
89
+ };
90
+ }
91
+ return { resetType: 'claudeWeekly', coversWindowIds: null, coversWindowPrefixes: ['seven_day'] };
92
+ }
93
+ return { resetType: 'custom', coversWindowIds: null, coversWindowPrefixes: null };
94
+ }
95
+
96
+ function normalizeResetCredits(driver, rawCredits) {
97
+ if (!rawCredits || !isObject(rawCredits)) return null;
98
+
99
+ // Already normalized v2 shape
100
+ if (Array.isArray(rawCredits.cards)) {
101
+ const cards = rawCredits.cards
102
+ .filter((c) => isObject(c) && typeof c.resetType === 'string')
103
+ .map((c, idx) => ({
104
+ creditId: c.creditId ?? `card-${idx + 1}`,
105
+ resetType: c.resetType,
106
+ status: c.status ?? 'available',
107
+ resetsLeft: Number.isSafeInteger(c.resetsLeft) ? c.resetsLeft : 1,
108
+ coversWindowIds: Array.isArray(c.coversWindowIds) ? [...c.coversWindowIds] : null,
109
+ coversWindowPrefixes: Array.isArray(c.coversWindowPrefixes) ? [...c.coversWindowPrefixes] : null,
110
+ expiresAt: toIsoTimestamp(c.expiresAt),
111
+ }));
112
+ const availableCount = Number.isSafeInteger(rawCredits.availableCount)
113
+ ? rawCredits.availableCount
114
+ : cards.filter((c) => c.status === 'available').reduce((sum, c) => sum + c.resetsLeft, 0);
115
+ return {
116
+ known: rawCredits.known !== false,
117
+ availableCount,
118
+ nextExpiresAt: toIsoTimestamp(rawCredits.nextExpiresAt) ?? cards.find((c) => c.expiresAt)?.expiresAt ?? null,
119
+ cards,
120
+ };
121
+ }
122
+
123
+ // T3 ServerProviderResetCredits shape: { availableCount, nextExpiresAt, nextCreditId, options }
124
+ const availableCount = Number.isSafeInteger(rawCredits.availableCount) ? rawCredits.availableCount : null;
125
+ if (availableCount === null) return null;
126
+ const nextExpiresAt = toIsoTimestamp(rawCredits.nextExpiresAt);
127
+ const options = Array.isArray(rawCredits.options) ? rawCredits.options : [];
128
+ const cards = [];
129
+
130
+ if (options.length > 0) {
131
+ for (const opt of options) {
132
+ if (!isObject(opt) || !Number.isSafeInteger(opt.availableCount)) continue;
133
+ const meta = (driver === 'claudeAgent' || driver === 'claude')
134
+ ? inferClaudeResetType(opt)
135
+ : driver === 'codex'
136
+ ? { resetType: 'codexRateLimits', coversWindowIds: null, coversWindowPrefixes: null }
137
+ : { resetType: 'custom', coversWindowIds: null, coversWindowPrefixes: null };
138
+ cards.push({
139
+ creditId: String(opt.creditId ?? 'credit'),
140
+ resetType: meta.resetType,
141
+ status: opt.availableCount > 0 ? 'available' : 'unusable',
142
+ resetsLeft: opt.availableCount,
143
+ coversWindowIds: meta.coversWindowIds,
144
+ coversWindowPrefixes: meta.coversWindowPrefixes,
145
+ expiresAt: toIsoTimestamp(opt.expiresAt) ?? nextExpiresAt,
146
+ });
147
+ }
148
+ } else if (driver === 'codex') {
149
+ cards.push({
150
+ creditId: rawCredits.nextCreditId ?? 'codex-reset',
151
+ resetType: 'codexRateLimits',
152
+ status: availableCount > 0 ? 'available' : 'unusable',
153
+ resetsLeft: availableCount,
154
+ coversWindowIds: null,
155
+ coversWindowPrefixes: null,
156
+ expiresAt: nextExpiresAt,
157
+ });
158
+ } else if (driver === 'claudeAgent' || driver === 'claude') {
159
+ // Unknown coverage if Claude has options omitted while count > 0
160
+ return {
161
+ known: availableCount === 0,
162
+ availableCount,
163
+ nextExpiresAt,
164
+ cards: [],
165
+ };
166
+ }
167
+
168
+ return {
169
+ known: true,
170
+ availableCount,
171
+ nextExpiresAt,
172
+ cards,
173
+ };
174
+ }
175
+
176
+ function normalizeWindows(driver, rawWindows) {
177
+ if (!Array.isArray(rawWindows)) return [];
178
+ const hasCodexPlanWindows = driver === 'codex'
179
+ && rawWindows.some((w) => w?.id === 'primary' || w?.id === 'secondary');
180
+
181
+ return rawWindows
182
+ .filter((win) => isObject(win))
183
+ .map((win) => {
184
+ const usedRaw = clampPercent(win.usedPercent);
185
+ const remRaw = clampPercent(win.remainingPercent);
186
+ const usedPercent = usedRaw ?? (remRaw !== null ? clampPercent(100 - remRaw) : null);
187
+ const remainingPercent = remRaw ?? (usedRaw !== null ? clampPercent(100 - usedRaw) : null);
188
+ const kind = inferWindowKind(win);
189
+ const windowDurationMins = inferWindowDuration(driver, { ...win, kind });
190
+ const id = typeof win.id === 'string' && win.id ? win.id : null;
191
+ const pool = inferWindowPool(driver, win);
192
+ const applicableByDefault = driver === 'codex' && id === 'individual' && hasCodexPlanWindows
193
+ ? false
194
+ : win.applicableByDefault !== false;
195
+
196
+ return {
197
+ id,
198
+ kind,
199
+ label: typeof win.label === 'string' && win.label ? win.label : (id ?? kind),
200
+ pool,
201
+ modelIds: Array.isArray(win.modelIds) ? [...win.modelIds] : null,
202
+ providerIds: Array.isArray(win.providerIds) ? [...win.providerIds] : null,
203
+ usedPercent,
204
+ remainingPercent,
205
+ resetsAt: toIsoTimestamp(win.resetsAt),
206
+ windowDurationMins,
207
+ ...(applicableByDefault ? {} : { applicableByDefault: false }),
208
+ };
209
+ });
210
+ }
211
+
212
+ function normalizeProviderEntry(provider, observedIso) {
213
+ const instanceId = String(provider.instanceId ?? provider.id ?? '').trim();
214
+ const driver = String(provider.driver ?? instanceId).trim();
215
+ const enabled = provider.enabled !== false;
216
+ const installed = provider.installed !== false;
217
+ const limits = isObject(provider.usageLimits) ? provider.usageLimits : null;
218
+ const authStatus = provider.auth?.status;
219
+
220
+ let status = 'ready';
221
+ let detail = null;
222
+
223
+ if (!enabled) {
224
+ status = 'disabled';
225
+ detail = provider.message ?? 'Provider instance disabled';
226
+ } else if (!installed) {
227
+ status = 'unavailable';
228
+ detail = provider.message ?? 'Provider CLI not installed';
229
+ } else if (limits?.unavailable) {
230
+ status = limits.unavailable.reason === 'unsupported' ? 'not_applicable' : 'unavailable';
231
+ detail = limits.unavailable.message ?? limits.unavailable.reason;
232
+ } else if (authStatus === 'unauthenticated') {
233
+ status = 'unavailable';
234
+ detail = provider.message ?? 'Provider unauthenticated';
235
+ } else if (provider.status && provider.status !== 'ready') {
236
+ status = 'unavailable';
237
+ detail = provider.message ?? provider.unavailableReason ?? `Provider status: ${provider.status}`;
238
+ }
239
+
240
+ const windows = normalizeWindows(driver, limits?.windows ?? []);
241
+ const checkedAt = toIsoTimestamp(limits?.checkedAt ?? provider.checkedAt) ?? observedIso;
242
+ const resetCredits = normalizeResetCredits(driver, limits?.resetCredits);
243
+ const models = Array.isArray(provider.models)
244
+ ? provider.models
245
+ .map((m) => (typeof m === 'string' ? m : (m?.slug ?? m?.id ?? null)))
246
+ .filter((m) => typeof m === 'string' && m)
247
+ : null;
248
+
249
+ return {
250
+ instanceId,
251
+ driver,
252
+ displayName: typeof provider.displayName === 'string' && provider.displayName.trim()
253
+ ? provider.displayName.trim()
254
+ : instanceId,
255
+ enabled,
256
+ status,
257
+ plan: typeof provider.auth?.label === 'string' && provider.auth.label.trim()
258
+ ? provider.auth.label.trim()
259
+ : (typeof provider.plan === 'string' ? provider.plan : null),
260
+ checkedAt,
261
+ detail,
262
+ ...(models ? { models } : {}),
263
+ windows,
264
+ resetCredits,
265
+ budget: null,
266
+ };
267
+ }
268
+
269
+ export function normalizeT3ConfigToSnapshot(serverConfig, now = Date.now()) {
270
+ const raw = isObject(serverConfig?.value)
271
+ ? serverConfig.value
272
+ : isObject(serverConfig?.result)
273
+ ? serverConfig.result
274
+ : serverConfig;
275
+ if (!isObject(raw) || !Array.isArray(raw.providers)) {
276
+ throw new Error('Invalid T3 serverConfig: expected providers array');
277
+ }
278
+ const nowMs = now instanceof Date ? now.getTime() : now;
279
+ const observedAt = new Date(nowMs).toISOString();
280
+ const instances = {};
281
+
282
+ for (const provider of raw.providers) {
283
+ if (!isObject(provider) || typeof provider.instanceId !== 'string' || !provider.instanceId.trim()) {
284
+ continue;
285
+ }
286
+ const normalized = normalizeProviderEntry(provider, observedAt);
287
+ instances[normalized.instanceId] = normalized;
288
+ }
289
+
290
+ const sources = [];
291
+ if (Array.isArray(raw.usageLimitSources)) {
292
+ for (const source of raw.usageLimitSources) {
293
+ if (!isObject(source) || typeof source.id !== 'string') continue;
294
+ const sourceEntry = {
295
+ id: source.id,
296
+ kind: source.kind ?? 'cliproxy',
297
+ label: source.label ?? source.id,
298
+ origin: source.origin ?? null,
299
+ endpoint: source.endpoint ?? null,
300
+ checkedAt: toIsoTimestamp(source.checkedAt) ?? observedAt,
301
+ error: source.error ?? null,
302
+ accounts: [],
303
+ };
304
+ for (const account of Array.isArray(source.accounts) ? source.accounts : []) {
305
+ if (!isObject(account) || typeof account.id !== 'string') continue;
306
+ const accountKey = `${source.id}:${account.id}`;
307
+ const accNorm = normalizeProviderEntry(
308
+ {
309
+ instanceId: accountKey,
310
+ driver: account.driver,
311
+ displayName: account.email ? `${source.label ?? source.id} · ${account.email}` : `${source.label ?? source.id} · ${account.id}`,
312
+ enabled: true,
313
+ installed: true,
314
+ status: 'ready',
315
+ plan: account.plan ?? null,
316
+ models: account.models ?? null,
317
+ usageLimits: account.usageLimits,
318
+ },
319
+ observedAt,
320
+ );
321
+ sourceEntry.accounts.push(accNorm);
322
+ if (!instances[accountKey]) {
323
+ instances[accountKey] = accNorm;
324
+ }
325
+ }
326
+ sources.push(sourceEntry);
327
+ }
328
+ }
329
+
330
+ return {
331
+ schemaVersion: 2,
332
+ observedAt,
333
+ source: 't3-rpc',
334
+ instances,
335
+ ...(sources.length ? { usageLimitSources: sources } : {}),
336
+ };
337
+ }
@@ -0,0 +1,275 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ const execFileAsync = promisify(execFile);
5
+
6
+ export class T3RpcError extends Error {
7
+ constructor(message, { status = null, code = null } = {}) {
8
+ super(message);
9
+ this.name = 'T3RpcError';
10
+ if (status != null) this.status = status;
11
+ if (code != null) this.code = code;
12
+ }
13
+ }
14
+
15
+ export function splitCommandArgs(command) {
16
+ if (Array.isArray(command)) {
17
+ const argv = command.map((item) => String(item).trim()).filter(Boolean);
18
+ if (!argv.length) throw new T3RpcError('Invalid empty tokenCommand');
19
+ return argv;
20
+ }
21
+ if (typeof command !== 'string' || !command.trim()) {
22
+ throw new T3RpcError('Invalid tokenCommand');
23
+ }
24
+ const argv = [];
25
+ let current = '';
26
+ let quote = null;
27
+ let escape = false;
28
+ for (const ch of command.trim()) {
29
+ if (escape) {
30
+ current += ch;
31
+ escape = false;
32
+ continue;
33
+ }
34
+ if (ch === '\\' && quote !== "'") {
35
+ escape = true;
36
+ continue;
37
+ }
38
+ if (quote) {
39
+ if (ch === quote) quote = null;
40
+ else current += ch;
41
+ continue;
42
+ }
43
+ if (ch === '"' || ch === "'") {
44
+ quote = ch;
45
+ continue;
46
+ }
47
+ if (/\s/.test(ch)) {
48
+ if (current) {
49
+ argv.push(current);
50
+ current = '';
51
+ }
52
+ continue;
53
+ }
54
+ current += ch;
55
+ }
56
+ if (escape || quote) throw new T3RpcError('Unterminated quote in tokenCommand');
57
+ if (current) argv.push(current);
58
+ if (!argv.length) throw new T3RpcError('Invalid empty tokenCommand');
59
+ return argv;
60
+ }
61
+
62
+ export async function resolveBearer({ bearer, tokenCommand, timeoutMs = 10_000, signal } = {}) {
63
+ if (typeof bearer === 'string' && bearer.trim()) {
64
+ return bearer.trim();
65
+ }
66
+ if (!tokenCommand) return null;
67
+ const [file, ...args] = splitCommandArgs(tokenCommand);
68
+ try {
69
+ const { stdout } = await execFileAsync(file, args, {
70
+ timeout: timeoutMs,
71
+ signal,
72
+ maxBuffer: 1024 * 64,
73
+ windowsHide: true,
74
+ });
75
+ const token = String(stdout ?? '').trim();
76
+ if (!token) throw new T3RpcError('tokenCommand returned empty output');
77
+ return token;
78
+ } catch (error) {
79
+ if (error instanceof T3RpcError) throw error;
80
+ throw new T3RpcError('Failed to execute tokenCommand', {
81
+ code: error?.code ?? 'TOKEN_COMMAND_FAILED',
82
+ });
83
+ }
84
+ }
85
+
86
+ async function fetchWebsocketTicket(origin, bearer, signal) {
87
+ let response;
88
+ let ticket = null;
89
+ const headers = bearer ? { Authorization: `Bearer ${bearer}` } : {};
90
+ try {
91
+ response = await fetch(`${origin}/api/auth/websocket-ticket`, {
92
+ method: 'POST',
93
+ headers,
94
+ signal,
95
+ });
96
+ if (response.ok) {
97
+ const body = await response.json();
98
+ if (typeof body?.ticket === 'string' && body.ticket) {
99
+ ticket = body.ticket;
100
+ }
101
+ }
102
+ } catch {
103
+ ticket = null;
104
+ }
105
+ if (ticket) return ticket;
106
+ throw new T3RpcError('Failed to obtain WebSocket ticket', {
107
+ status: response?.status ?? null,
108
+ code: 'WS_TICKET_FAILED',
109
+ });
110
+ }
111
+
112
+ function normalizeOrigin(origin) {
113
+ if (typeof origin !== 'string' || !origin.trim()) {
114
+ throw new T3RpcError('Invalid T3 server origin');
115
+ }
116
+ let parsed;
117
+ try {
118
+ parsed = new URL(origin.trim());
119
+ } catch {
120
+ throw new T3RpcError('Invalid T3 server origin URL');
121
+ }
122
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
123
+ throw new T3RpcError('T3 server origin must use http or https');
124
+ }
125
+ return parsed.origin;
126
+ }
127
+
128
+ /**
129
+ * Connect to a T3 Code server via WebSocket RPC.
130
+ * Supports either `connectT3(origin, bearer, { signal, timeoutMs })`
131
+ * or `connectT3({ origin, bearer, tokenCommand, timeoutMs, signal })`.
132
+ */
133
+ export async function connectT3(originOrOptions, bearerArg, extraOptions = {}) {
134
+ const options = typeof originOrOptions === 'object' && originOrOptions !== null
135
+ ? originOrOptions
136
+ : { origin: originOrOptions, bearer: bearerArg, ...extraOptions };
137
+
138
+ const origin = normalizeOrigin(options.origin);
139
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
140
+ ? options.timeoutMs
141
+ : 15_000;
142
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
143
+ const combinedSignal = options.signal
144
+ ? AbortSignal.any([options.signal, timeoutSignal])
145
+ : timeoutSignal;
146
+
147
+ const bearer = await resolveBearer({
148
+ bearer: options.bearer,
149
+ tokenCommand: options.tokenCommand,
150
+ timeoutMs,
151
+ signal: combinedSignal,
152
+ });
153
+
154
+ const ticket = await fetchWebsocketTicket(origin, bearer, combinedSignal);
155
+ const wsOrigin = origin.replace(/^http/, 'ws');
156
+ const wsUrl = `${wsOrigin}/ws?orchestrationProtocol=2&clientSurface=web&wsTicket=${encodeURIComponent(ticket)}`;
157
+ const ws = new WebSocket(wsUrl);
158
+
159
+ const pending = new Map();
160
+ let nextId = 1;
161
+ let broken = null;
162
+
163
+ const breakAll = (message, code = 'WS_BROKEN') => {
164
+ broken ??= new T3RpcError(message, { code });
165
+ for (const entry of pending.values()) {
166
+ entry.reject(broken);
167
+ }
168
+ pending.clear();
169
+ try {
170
+ ws.close();
171
+ } catch {
172
+ // ignore close errors
173
+ }
174
+ };
175
+
176
+ const onAbort = () => breakAll('T3 RPC aborted or timed out', 'ABORTED');
177
+ if (combinedSignal.aborted) {
178
+ onAbort();
179
+ } else {
180
+ combinedSignal.addEventListener('abort', onAbort, { once: true });
181
+ }
182
+
183
+ await new Promise((resolve, reject) => {
184
+ if (broken) return reject(broken);
185
+ ws.addEventListener('open', resolve, { once: true });
186
+ ws.addEventListener(
187
+ 'error',
188
+ () => reject(broken ?? new T3RpcError('WebSocket connection failed', { code: 'WS_ERROR' })),
189
+ { once: true },
190
+ );
191
+ combinedSignal.addEventListener('abort', () => reject(broken), { once: true });
192
+ });
193
+
194
+ ws.addEventListener('error', () => breakAll('WebSocket connection failed', 'WS_ERROR'));
195
+ ws.addEventListener('close', () => breakAll('WebSocket closed unexpectedly', 'WS_CLOSED'));
196
+ ws.addEventListener('message', (event) => {
197
+ let messages;
198
+ try {
199
+ const rawText = typeof event.data === 'string'
200
+ ? event.data
201
+ : Buffer.from(event.data).toString('utf8');
202
+ messages = [JSON.parse(rawText)].flat();
203
+ } catch {
204
+ return breakAll('T3 returned invalid JSON frame', 'WS_INVALID_FRAME');
205
+ }
206
+ for (const frame of messages) {
207
+ if (frame?._tag === 'Ping') {
208
+ ws.send(JSON.stringify({ _tag: 'Pong' }));
209
+ continue;
210
+ }
211
+ const entry = pending.get(frame?.requestId);
212
+ if (!entry) continue;
213
+ if (frame._tag === 'Chunk') {
214
+ ws.send(JSON.stringify({ _tag: 'Ack', requestId: frame.requestId }));
215
+ const values = frame.values ?? [];
216
+ if (entry.stream === true || (typeof entry.stream === 'function' && entry.stream(values))) {
217
+ pending.delete(frame.requestId);
218
+ entry.resolve({ _tag: 'Chunk', values });
219
+ }
220
+ } else if (frame._tag === 'Exit') {
221
+ pending.delete(frame.requestId);
222
+ entry.resolve(frame.exit);
223
+ }
224
+ }
225
+ });
226
+
227
+ return {
228
+ call: (tag, payload = {}, { stream = false } = {}) =>
229
+ new Promise((resolve, reject) => {
230
+ if (broken) return reject(broken);
231
+ const id = String(nextId++);
232
+ pending.set(id, { resolve, reject, stream });
233
+ ws.send(JSON.stringify({ _tag: 'Request', id, tag, payload, headers: [] }));
234
+ }),
235
+ close: () => {
236
+ combinedSignal.removeEventListener('abort', onAbort);
237
+ broken ??= new T3RpcError('T3 RPC closed', { code: 'WS_CLOSED' });
238
+ try {
239
+ ws.close();
240
+ } catch {
241
+ // ignore
242
+ }
243
+ },
244
+ };
245
+ }
246
+
247
+ export function unwrapRpcExit(exit) {
248
+ if (!exit || typeof exit !== 'object') {
249
+ throw new T3RpcError('Empty RPC exit response', { code: 'RPC_EMPTY' });
250
+ }
251
+ if (exit._tag === 'Failure') {
252
+ const message = exit.cause?.message || exit.cause?.defect || 'T3 RPC call failed';
253
+ throw new T3RpcError(String(message), { code: 'RPC_FAILURE' });
254
+ }
255
+ if (exit._tag === 'Success') {
256
+ return exit.value;
257
+ }
258
+ return exit;
259
+ }
260
+
261
+ export async function fetchT3ServerConfig(options = {}) {
262
+ const rpc = await connectT3(options);
263
+ try {
264
+ const exit = await rpc.call('server.getConfig', {});
265
+ const config = unwrapRpcExit(exit);
266
+ if (!config || typeof config !== 'object' || !Array.isArray(config.providers)) {
267
+ throw new T3RpcError('server.getConfig did not return providers list', {
268
+ code: 'INVALID_SERVER_CONFIG',
269
+ });
270
+ }
271
+ return config;
272
+ } finally {
273
+ rpc.close();
274
+ }
275
+ }
@@ -0,0 +1,73 @@
1
+ import { fetchT3AutoConfig } from './adapters/t3-auto.mjs';
2
+ import { normalizeSnapshot, overlayBudgetEntries } from './adapters/json-snapshot.mjs';
3
+ import { normalizeT3ConfigToSnapshot } from './adapters/t3-config.mjs';
4
+ import { fetchT3ServerConfig } from './adapters/t3-rpc.mjs';
5
+ import { decideDispatch } from './core/decide.mjs';
6
+ import { collectDispatchScores } from './core/scores.mjs';
7
+ import { collectSpeed } from './speed/collect.mjs';
8
+
9
+ /**
10
+ * plan / dashboard / MCP 共用的输入汇集:快照(原始 JSON、本机自动发现或远端 origin)、验收评分与本地速度。
11
+ * 没有任何快照来源时 snapshot 为 null,由调用方决定是否报错。
12
+ */
13
+ export async function gatherDispatchInputs({
14
+ policy,
15
+ rawSnapshot = null,
16
+ origin,
17
+ bearer,
18
+ tokenCommand,
19
+ auto = false,
20
+ budget = null,
21
+ scoresPath,
22
+ speedMetrics = null,
23
+ speedScan = false,
24
+ days = 30,
25
+ scan = {},
26
+ env = process.env,
27
+ now = Date.now(),
28
+ } = {}) {
29
+ let snapshot = null;
30
+ if (rawSnapshot) {
31
+ snapshot = normalizeSnapshot(rawSnapshot, { now });
32
+ } else if (auto) {
33
+ snapshot = normalizeT3ConfigToSnapshot(await fetchT3AutoConfig({ env, origin }), now);
34
+ } else if (origin) {
35
+ snapshot = normalizeT3ConfigToSnapshot(await fetchT3ServerConfig({ origin, bearer, tokenCommand }), now);
36
+ }
37
+ if (snapshot && budget) snapshot = overlayBudgetEntries(snapshot, budget);
38
+
39
+ const scoresSummary = collectDispatchScores({ scoresFile: scoresPath, env }, policy.scoring);
40
+
41
+ let speed = null;
42
+ if (speedScan) {
43
+ speed = await collectSpeed({ days, now, scan, scoresFile: scoresPath, scoring: policy.scoring, env });
44
+ }
45
+ return { snapshot, scoresSummary, speed, speedMetrics: speedMetrics ?? speed?.metrics ?? null };
46
+ }
47
+
48
+ /** 汇集输入后做一次派发决策;没有快照来源时 decision 为 null,由调用方决定是否报错。 */
49
+ export async function planDispatch({ policy, request = {}, now = Date.now(), ...inputArgs } = {}) {
50
+ const inputs = await gatherDispatchInputs({ policy, now, ...inputArgs });
51
+ const decision = inputs.snapshot
52
+ ? decideDispatch({
53
+ snapshot: inputs.snapshot,
54
+ policy,
55
+ scoresSummary: inputs.scoresSummary,
56
+ speedMetrics: inputs.speedMetrics,
57
+ request,
58
+ now,
59
+ })
60
+ : null;
61
+ return { ...inputs, decision, now };
62
+ }
63
+
64
+ /** 速度窗口天数:1..365 的整数,缺省 30。 */
65
+ export function resolveDays(value, label = 'days') {
66
+ if (value === undefined || value === null) return 30;
67
+ if (!Number.isInteger(value) && !(typeof value === 'string' && /^\d+$/.test(value))) {
68
+ throw new Error(`${label} must be an integer in 1..365`);
69
+ }
70
+ const days = Number(value);
71
+ if (days < 1 || days > 365) throw new Error(`${label} must be an integer in 1..365`);
72
+ return days;
73
+ }