@shuind/dsh-codex-connect 0.0.0-stage → 0.2.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.
Files changed (42) hide show
  1. package/INSTALL.md +349 -0
  2. package/LICENSE +202 -0
  3. package/MIGRATION.md +101 -0
  4. package/NOTICE +26 -0
  5. package/README.md +71 -2
  6. package/VERSIONING.md +69 -0
  7. package/cordis.patch.yml +9 -0
  8. package/docs/README.zh.md +3 -0
  9. package/docs/assets/composer-capabilities.jpg +0 -0
  10. package/docs/assets/en/hero.jpg +0 -0
  11. package/docs/assets/en/image-generation.png +0 -0
  12. package/docs/assets/en/model-selector.jpg +0 -0
  13. package/docs/assets/en/oauth-status.jpg +0 -0
  14. package/docs/assets/en/plugin-configuration.jpg +0 -0
  15. package/docs/assets/en/plugin-entry.jpg +0 -0
  16. package/docs/assets/hero.jpg +0 -0
  17. package/docs/assets/model-selector.jpg +0 -0
  18. package/docs/assets/oauth-status.jpg +0 -0
  19. package/docs/assets/plugin-configuration.jpg +0 -0
  20. package/docs/assets/zh/hero.jpg +0 -0
  21. package/docs/assets/zh/image-generation.png +0 -0
  22. package/docs/assets/zh/model-selector.jpg +0 -0
  23. package/docs/assets/zh/oauth-status.jpg +0 -0
  24. package/docs/assets/zh/plugin-configuration.jpg +0 -0
  25. package/docs/assets/zh/plugin-entry.jpg +0 -0
  26. package/docs/design.md +61 -0
  27. package/docs/design.zh.md +39 -0
  28. package/docs/licenses/pi-ai-oauth.txt +21 -0
  29. package/docs/licenses/standalone-cli.txt +115 -0
  30. package/docs/preflight-activity.md +42 -0
  31. package/docs/preflight-activity.zh.md +42 -0
  32. package/docs/quota-tool.md +46 -0
  33. package/docs/reference.md +240 -0
  34. package/docs/reference.zh.md +240 -0
  35. package/docs/skills/codex-quota-awareness/SKILL.md +12 -0
  36. package/lib/bin.js +2442 -0
  37. package/lib/client.js +6804 -0
  38. package/lib/index.d.ts +631 -0
  39. package/lib/index.js +7091 -0
  40. package/lib/models-Brnw-PH4.js +1763 -0
  41. package/lib/openai-codex-responses-DfZMR6a9.js +3452 -0
  42. package/package.json +234 -4
@@ -0,0 +1,1763 @@
1
+ import { createRequire } from "node:module";
2
+ // \0rolldown/runtime.js
3
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
4
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
5
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js
6
+ var FifoQueue = class {
7
+ incoming = [];
8
+ outgoing = [];
9
+ get length() {
10
+ return this.incoming.length + this.outgoing.length;
11
+ }
12
+ enqueue(value) {
13
+ this.incoming.push(value);
14
+ }
15
+ dequeue() {
16
+ if (this.outgoing.length === 0) while (this.incoming.length > 0) this.outgoing.push(this.incoming.pop());
17
+ return this.outgoing.pop();
18
+ }
19
+ };
20
+ var EventStream = class {
21
+ queue = new FifoQueue();
22
+ waiting = new FifoQueue();
23
+ done = false;
24
+ finalResultPromise;
25
+ resolveFinalResult;
26
+ isComplete;
27
+ extractResult;
28
+ constructor(isComplete, extractResult) {
29
+ this.isComplete = isComplete;
30
+ this.extractResult = extractResult;
31
+ this.finalResultPromise = new Promise((resolve) => {
32
+ this.resolveFinalResult = resolve;
33
+ });
34
+ }
35
+ push(event) {
36
+ if (this.done) return;
37
+ if (this.isComplete(event)) {
38
+ this.done = true;
39
+ this.resolveFinalResult(this.extractResult(event));
40
+ }
41
+ const waiter = this.waiting.dequeue();
42
+ if (waiter) waiter({
43
+ value: event,
44
+ done: false
45
+ });
46
+ else this.queue.enqueue(event);
47
+ }
48
+ end(result) {
49
+ this.done = true;
50
+ if (result !== void 0) this.resolveFinalResult(result);
51
+ while (this.waiting.length > 0) this.waiting.dequeue()({
52
+ value: void 0,
53
+ done: true
54
+ });
55
+ }
56
+ async *[Symbol.asyncIterator]() {
57
+ while (true) if (this.queue.length > 0) yield this.queue.dequeue();
58
+ else if (this.done) return;
59
+ else {
60
+ const result = await new Promise((resolve) => this.waiting.enqueue(resolve));
61
+ if (result.done) return;
62
+ yield result.value;
63
+ }
64
+ }
65
+ result() {
66
+ return this.finalResultPromise;
67
+ }
68
+ };
69
+ /**
70
+ * Event stream of one assistant response. It also times the response: the final message (`done` or `error` event, or
71
+ * the result passed to `end()`) gets `durationMs`, measured with a monotonic clock from the stream's creation, unless
72
+ * the message already has one or its `timestamp` predates the stream. A stream that forwards a response which started
73
+ * elsewhere, such as a deferred result fetched later, therefore leaves it untimed.
74
+ */
75
+ var AssistantMessageEventStream = class extends EventStream {
76
+ #startedAt = Date.now();
77
+ #startedAtMonotonic = performance.now();
78
+ constructor() {
79
+ super((event) => event.type === "done" || event.type === "error", (event) => {
80
+ if (event.type === "done") return event.message;
81
+ else if (event.type === "error") return event.error;
82
+ throw new Error("Unexpected event type for final result");
83
+ });
84
+ }
85
+ push(event) {
86
+ if (event.type === "done") this.#time(event.message);
87
+ else if (event.type === "error") this.#time(event.error);
88
+ super.push(event);
89
+ }
90
+ end(result) {
91
+ if (result !== void 0) this.#time(result);
92
+ super.end(result);
93
+ }
94
+ #time(message) {
95
+ if (this.done || message.durationMs !== void 0 || message.timestamp < this.#startedAt) return;
96
+ message.durationMs = Math.max(0, Math.round(performance.now() - this.#startedAtMonotonic));
97
+ }
98
+ };
99
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/api/lazy.js
100
+ function createSetupErrorMessage(model, error, timestamp, stopReason) {
101
+ return {
102
+ role: "assistant",
103
+ content: [],
104
+ api: model.api,
105
+ provider: model.provider,
106
+ model: model.id,
107
+ usage: {
108
+ input: 0,
109
+ output: 0,
110
+ cacheRead: 0,
111
+ cacheWrite: 0,
112
+ totalTokens: 0,
113
+ cost: {
114
+ input: 0,
115
+ output: 0,
116
+ cacheRead: 0,
117
+ cacheWrite: 0,
118
+ total: 0
119
+ }
120
+ },
121
+ stopReason,
122
+ errorMessage: error instanceof Error ? error.message : String(error),
123
+ timestamp
124
+ };
125
+ }
126
+ function hasResult(source) {
127
+ return typeof source.result === "function";
128
+ }
129
+ async function forwardStream(target, source, observer, observeResult) {
130
+ let result;
131
+ for await (const event of source) {
132
+ target.push(event);
133
+ observer?.onEvent?.(event);
134
+ if (event.type === "done") result = event.message;
135
+ else if (event.type === "error") result = event.error;
136
+ }
137
+ if (hasResult(source)) result = await source.result();
138
+ target.end(result);
139
+ observeResult(result);
140
+ }
141
+ /**
142
+ * Returns a stream synchronously while running async setup (auth resolution,
143
+ * lazy module loading) behind it. Setup failures terminate the stream with an
144
+ * error event.
145
+ */
146
+ function lazyStream(model, setup, observer, signal) {
147
+ const startedAt = Date.now();
148
+ const outer = new AssistantMessageEventStream();
149
+ let observedResult = false;
150
+ const observeResult = (result) => {
151
+ if (observedResult) return;
152
+ observedResult = true;
153
+ observer?.onResult?.(result);
154
+ };
155
+ setup().then((inner) => forwardStream(outer, inner, observer, observeResult)).catch((error) => {
156
+ const reason = signal?.aborted ? "aborted" : "error";
157
+ const message = createSetupErrorMessage(model, error, startedAt, reason);
158
+ const event = {
159
+ type: "error",
160
+ reason,
161
+ error: message
162
+ };
163
+ outer.push(event);
164
+ observer?.onEvent?.(event);
165
+ outer.end(message);
166
+ observeResult(message);
167
+ });
168
+ return outer;
169
+ }
170
+ function lazyApi(load, capabilities) {
171
+ const api = {
172
+ stream: (model, context, options) => lazyStream(model, async () => (await load()).stream(model, context, options), void 0, options?.signal),
173
+ streamSimple: (model, context, options) => lazyStream(model, async () => (await load()).streamSimple(model, context, options), void 0, options?.signal)
174
+ };
175
+ if (capabilities?.fetchDeferred) api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
176
+ const implementation = await load();
177
+ if (!implementation.fetchDeferred) throw new Error("API does not support deferred responses");
178
+ return implementation.fetchDeferred(model, handle, options);
179
+ }, void 0, options?.signal);
180
+ if (capabilities?.cancelDeferred) api.cancelDeferred = async (model, handle, options) => {
181
+ const implementation = await load();
182
+ if (!implementation.cancelDeferred) throw new Error("API cannot cancel deferred responses");
183
+ await implementation.cancelDeferred(model, handle, options);
184
+ };
185
+ return api;
186
+ }
187
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/auth/context.js
188
+ var __rewriteRelativeImportExtension = function(path, preserveJsx) {
189
+ if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
190
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
191
+ });
192
+ return path;
193
+ };
194
+ const importNodeModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));
195
+ function getProcessEnv() {
196
+ return globalThis.process?.env;
197
+ }
198
+ /**
199
+ * Default auth context: env vars from `process.env` (undefined in browsers),
200
+ * file existence via node:fs (always false in browsers).
201
+ */
202
+ function defaultProviderAuthContext() {
203
+ return {
204
+ async env(name) {
205
+ const value = getProcessEnv()?.[name];
206
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
207
+ },
208
+ async fileExists(path) {
209
+ try {
210
+ const fs = await importNodeModule("node:fs/promises");
211
+ let resolved = path;
212
+ if (resolved.startsWith("~")) resolved = (await importNodeModule("node:os")).homedir() + resolved.slice(1);
213
+ await fs.access(resolved);
214
+ return true;
215
+ } catch {
216
+ return false;
217
+ }
218
+ }
219
+ };
220
+ }
221
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/abort.js
222
+ function abortReason(signal) {
223
+ if (signal.reason !== void 0) return signal.reason;
224
+ const error = /* @__PURE__ */ new Error("The operation was aborted");
225
+ error.name = "AbortError";
226
+ return error;
227
+ }
228
+ /** Create an operation-local signal for public APIs whose signal is optional. */
229
+ function operationSignal(signal) {
230
+ return signal ?? new AbortController().signal;
231
+ }
232
+ /**
233
+ * Stop waiting for an operation when its signal aborts while continuing to
234
+ * observe the abandoned promise so a later rejection is always handled.
235
+ */
236
+ function raceWithAbortSignal(operation, signal) {
237
+ if (signal.aborted) {
238
+ operation.catch(() => {});
239
+ return Promise.reject(abortReason(signal));
240
+ }
241
+ return new Promise((resolve, reject) => {
242
+ let settled = false;
243
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
244
+ const onAbort = () => {
245
+ if (settled) return;
246
+ settled = true;
247
+ cleanup();
248
+ reject(abortReason(signal));
249
+ };
250
+ signal.addEventListener("abort", onAbort, { once: true });
251
+ operation.then((value) => {
252
+ if (settled) return;
253
+ settled = true;
254
+ cleanup();
255
+ resolve(value);
256
+ }, (error) => {
257
+ if (settled) return;
258
+ settled = true;
259
+ cleanup();
260
+ reject(error);
261
+ });
262
+ if (signal.aborted) onAbort();
263
+ });
264
+ }
265
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js
266
+ /**
267
+ * Default in-memory credential store. Apps inject persistent stores.
268
+ * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.
269
+ * Writes are serialized per provider through a promise chain.
270
+ */
271
+ var InMemoryCredentialStore = class {
272
+ credentials = /* @__PURE__ */ new Map();
273
+ chains = /* @__PURE__ */ new Map();
274
+ /** Serialize tasks per provider id without releasing the chain before active work settles. */
275
+ enqueue(providerId, task, options) {
276
+ const signal = operationSignal(options?.signal);
277
+ const previous = this.chains.get(providerId) ?? Promise.resolve();
278
+ const queued = (async () => {
279
+ await previous.catch(() => {});
280
+ signal.throwIfAborted();
281
+ return task();
282
+ })();
283
+ const tail = queued.catch(() => {});
284
+ this.chains.set(providerId, tail);
285
+ tail.then(() => {
286
+ if (this.chains.get(providerId) === tail) this.chains.delete(providerId);
287
+ });
288
+ return raceWithAbortSignal(queued, signal);
289
+ }
290
+ async read(providerId, options) {
291
+ options?.signal?.throwIfAborted();
292
+ return this.credentials.get(providerId);
293
+ }
294
+ async list(options) {
295
+ options?.signal?.throwIfAborted();
296
+ return [...this.credentials].map(([providerId, credential]) => ({
297
+ providerId,
298
+ type: credential.type
299
+ }));
300
+ }
301
+ modify(providerId, fn, options) {
302
+ return this.enqueue(providerId, async () => {
303
+ const current = this.credentials.get(providerId);
304
+ const next = await fn(current);
305
+ options?.signal?.throwIfAborted();
306
+ if (next !== void 0) this.credentials.set(providerId, next);
307
+ return next ?? current;
308
+ }, options);
309
+ }
310
+ delete(providerId, options) {
311
+ return this.enqueue(providerId, async () => {
312
+ this.credentials.delete(providerId);
313
+ }, options);
314
+ }
315
+ };
316
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/diagnostics.js
317
+ function formatThrownValue(value) {
318
+ if (value instanceof Error) return value.message || value.name;
319
+ if (typeof value === "string") return value;
320
+ return String(value);
321
+ }
322
+ function extractDiagnosticError(error) {
323
+ if (!(error instanceof Error)) return {
324
+ name: "ThrownValue",
325
+ message: formatThrownValue(error)
326
+ };
327
+ const code = error.code;
328
+ return {
329
+ name: error.name || void 0,
330
+ message: error.message || error.name,
331
+ stack: error.stack,
332
+ code: typeof code === "string" || typeof code === "number" ? code : void 0
333
+ };
334
+ }
335
+ function createAssistantMessageDiagnostic(type, error, details) {
336
+ return {
337
+ type,
338
+ timestamp: Date.now(),
339
+ error: extractDiagnosticError(error),
340
+ details
341
+ };
342
+ }
343
+ function appendAssistantMessageDiagnostic(message, diagnostic) {
344
+ message.diagnostics = [...message.diagnostics ?? [], diagnostic];
345
+ }
346
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/models-error.js
347
+ var ModelsError = class extends Error {
348
+ code;
349
+ constructor(code, message, options) {
350
+ super(withCauseDetail(message, options?.cause), options);
351
+ this.name = "ModelsError";
352
+ this.code = code;
353
+ }
354
+ };
355
+ /** Callers surface `error.message` only, so keep the underlying reason in it. */
356
+ function withCauseDetail(message, cause) {
357
+ if (cause === void 0 || cause === null) return message;
358
+ const detail = formatThrownValue(cause).trim();
359
+ if (!detail || message.includes(detail)) return message;
360
+ return `${message}: ${detail}`;
361
+ }
362
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js
363
+ /**
364
+ * Auth resolution shared by all operations in a `Models` collection.
365
+ * A stored credential owns the provider: ambient/env is consulted only when
366
+ * nothing is stored. No silent env fallback after a failed refresh or for a
367
+ * credential type without a matching handler.
368
+ */
369
+ function resolveProviderAuth(provider, credentials, authContext, overrides) {
370
+ const signal = operationSignal(overrides?.signal);
371
+ return raceWithAbortSignal(resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal), signal);
372
+ }
373
+ async function resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal) {
374
+ signal.throwIfAborted();
375
+ const requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;
376
+ if (overrides?.apiKey !== void 0 && provider.auth.apiKey) return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, {
377
+ type: "api_key",
378
+ key: overrides.apiKey,
379
+ env: overrides.env
380
+ }, signal);
381
+ const stored = await readCredential(credentials, provider.id, signal);
382
+ if (stored) {
383
+ if (stored.type === "oauth" && provider.auth.oauth) return resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored, signal, overrides?.minOAuthValidityMs);
384
+ if (stored.type === "api_key" && provider.auth.apiKey) {
385
+ const credential = overrides?.env ? {
386
+ ...stored,
387
+ env: {
388
+ ...stored.env,
389
+ ...overrides.env
390
+ }
391
+ } : stored;
392
+ return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);
393
+ }
394
+ return;
395
+ }
396
+ return provider.auth.apiKey ? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, void 0, signal) : void 0;
397
+ }
398
+ function overlayEnvAuthContext(base, env) {
399
+ return {
400
+ env: async (name) => env[name] || await base.env(name),
401
+ fileExists: (path) => base.fileExists(path)
402
+ };
403
+ }
404
+ const DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 3e5;
405
+ const DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15e3;
406
+ /**
407
+ * Refresh a stored OAuth credential under the credential-store lock and persist
408
+ * the result before the lock is released. `needsRefresh` is re-checked under
409
+ * the lock, so concurrent callers and processes refresh only once.
410
+ *
411
+ * `signal` cancels only the wait for the lock. Once a refresh starts, the
412
+ * provider may already have rotated the refresh token, so the refresh and its
413
+ * persistence ignore `signal` and are bounded only by a timeout. Otherwise a
414
+ * cancelled caller could discard the only valid refresh token. Callers that
415
+ * must return promptly on cancellation race this promise with their signal.
416
+ *
417
+ * Resolves with the stored OAuth credential after the operation, or undefined
418
+ * when the provider no longer has an OAuth credential.
419
+ */
420
+ async function refreshStoredOAuthCredential(credentials, providerId, oauth, needsRefresh, signal) {
421
+ let post;
422
+ const lockWait = new AbortController();
423
+ const cancelLockWait = () => lockWait.abort(signal.reason);
424
+ signal.addEventListener("abort", cancelLockWait, { once: true });
425
+ if (signal.aborted) cancelLockWait();
426
+ try {
427
+ post = await credentials.modify(providerId, async (current) => {
428
+ signal.removeEventListener("abort", cancelLockWait);
429
+ signal.throwIfAborted();
430
+ if (current?.type !== "oauth") return void 0;
431
+ if (!needsRefresh(current)) return void 0;
432
+ try {
433
+ return await oauth.refresh(current, AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS));
434
+ } catch (error) {
435
+ throw new ModelsError("oauth", `OAuth refresh failed for ${providerId}`, { cause: error });
436
+ }
437
+ }, { signal: lockWait.signal });
438
+ } catch (error) {
439
+ if (error instanceof ModelsError) throw error;
440
+ signal.throwIfAborted();
441
+ throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
442
+ } finally {
443
+ signal.removeEventListener("abort", cancelLockWait);
444
+ }
445
+ return post?.type === "oauth" ? post : void 0;
446
+ }
447
+ /**
448
+ * OAuth resolution with double-checked locking: tokens with less than five
449
+ * minutes remaining are refreshed through `refreshStoredOAuthCredential`.
450
+ */
451
+ async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal, minOAuthValidityMs) {
452
+ const minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);
453
+ const expiresSoon = (credential) => Date.now() + minimumValidityMs >= credential.expires;
454
+ let credential = stored;
455
+ if (expiresSoon(credential)) {
456
+ const post = await refreshStoredOAuthCredential(credentials, providerId, oauth, expiresSoon, signal);
457
+ if (!post) return void 0;
458
+ credential = post;
459
+ if (minOAuthValidityMs !== void 0 && expiresSoon(credential)) throw new ModelsError("oauth", `OAuth refresh returned a token that expires too soon for ${providerId}`);
460
+ }
461
+ try {
462
+ return {
463
+ auth: await oauth.toAuth(credential),
464
+ source: "OAuth"
465
+ };
466
+ } catch (error) {
467
+ throw new ModelsError("oauth", `OAuth auth derivation failed for ${providerId}`, { cause: error });
468
+ }
469
+ }
470
+ async function resolveApiKey(authContext, apiKey, providerId, credential, signal) {
471
+ try {
472
+ return await apiKey.resolve({
473
+ ctx: authContext,
474
+ credential,
475
+ signal
476
+ });
477
+ } catch (error) {
478
+ throw new ModelsError("auth", `API key auth failed for provider ${providerId}`, { cause: error });
479
+ }
480
+ }
481
+ async function readCredential(credentials, providerId, signal) {
482
+ try {
483
+ return await credentials.read(providerId, { signal });
484
+ } catch (error) {
485
+ throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
486
+ }
487
+ }
488
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/models-store.js
489
+ var InMemoryModelsStore = class {
490
+ entries = /* @__PURE__ */ new Map();
491
+ async read(providerId, options) {
492
+ options?.signal?.throwIfAborted();
493
+ const entry = this.entries.get(providerId);
494
+ return entry ? structuredClone(entry) : void 0;
495
+ }
496
+ async write(providerId, entry, options) {
497
+ options?.signal?.throwIfAborted();
498
+ this.entries.set(providerId, structuredClone(entry));
499
+ }
500
+ async delete(providerId, options) {
501
+ options?.signal?.throwIfAborted();
502
+ this.entries.delete(providerId);
503
+ }
504
+ };
505
+ // node_modules/.pnpm/@earendil-works+pi-telemetry@1.6.0/node_modules/@earendil-works/pi-telemetry/dist/metrics.js
506
+ /** Bind instrument names, kinds, metadata, and exact measurement attributes to one or more schemas. */
507
+ function createTypedMetrics(metrics, schemas) {
508
+ const definitions = /* @__PURE__ */ new Map();
509
+ for (const schema of schemas) for (const [name, definition] of Object.entries(schema.metrics ?? {})) definitions.set(name, definition);
510
+ return {
511
+ counter: (name) => metrics.counter(name, definitions.get(name)),
512
+ upDownCounter: (name) => metrics.upDownCounter(name, definitions.get(name)),
513
+ histogram: (name) => metrics.histogram(name, definitions.get(name))
514
+ };
515
+ }
516
+ // node_modules/.pnpm/@earendil-works+pi-telemetry@1.6.0/node_modules/@earendil-works/pi-telemetry/dist/noop.js
517
+ async function startNoopSpan(_options, callback) {
518
+ return callback(noopTelemetrySpan);
519
+ }
520
+ const noopCounter = Object.freeze({ add: () => {} });
521
+ const noopUpDownCounter = Object.freeze({ add: () => {} });
522
+ const noopHistogram = Object.freeze({ record: () => {} });
523
+ /** Shared instruments that never inspect or retain metadata, measurements, or contexts. */
524
+ const NOOP_TELEMETRY_METRICS = Object.freeze({
525
+ counter: () => noopCounter,
526
+ upDownCounter: () => noopUpDownCounter,
527
+ histogram: () => noopHistogram
528
+ });
529
+ const noopTelemetrySpan = {
530
+ metrics: NOOP_TELEMETRY_METRICS,
531
+ propagation: Object.freeze({
532
+ inject: () => void 0,
533
+ extract: () => NOOP_TELEMETRY_CONTEXT
534
+ }),
535
+ startSpan: startNoopSpan,
536
+ addLink: () => {},
537
+ addEvent: () => {},
538
+ setAttributes: () => {},
539
+ setStatus: () => {}
540
+ };
541
+ Object.freeze(noopTelemetrySpan);
542
+ /** Shared telemetry context used when an application does not provide one. */
543
+ const NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan;
544
+ performance.timeOrigin;
545
+ // node_modules/.pnpm/@earendil-works+pi-telemetry@1.6.0/node_modules/@earendil-works/pi-telemetry/dist/index.js
546
+ /** Typed identity helper for serializable telemetry schema data. */
547
+ function defineTelemetrySchema(schema) {
548
+ return schema;
549
+ }
550
+ function bindTypedSpanStarter(telemetryContext) {
551
+ const startSpan = (name, attributes, callback) => telemetryContext.startSpan({
552
+ name,
553
+ attributes
554
+ }, (span) => callback(span, bindTypedSpanStarter(span)));
555
+ return startSpan;
556
+ }
557
+ /**
558
+ * Bind an explicit parent context to the combined span vocabulary of one or more schemas.
559
+ * Schema values are used only for type inference; no runtime schema validation is performed.
560
+ */
561
+ function createTypedSpanStarter(telemetryContext, _schemas) {
562
+ return bindTypedSpanStarter(telemetryContext);
563
+ }
564
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/text.js
565
+ /** Extract and join text from message content. */
566
+ function contentText(content, separator = "\n") {
567
+ if (typeof content === "string") return content;
568
+ return content.filter((block) => block.type === "text").map((block) => block.text).join(separator);
569
+ }
570
+ /** Render a system message as a complete prompt: its content followed by its sections. */
571
+ function getSystemMessageText(message) {
572
+ const parts = [contentText(message.content)];
573
+ for (const text of Object.values(message.sections ?? {})) if (text !== null) parts.push(text);
574
+ return parts.filter((part) => part.length > 0).join("\n\n");
575
+ }
576
+ /**
577
+ * Render a later system message for APIs that accept system messages mid-conversation.
578
+ * Section changes are framed by name so the model can relate them to the leading prompt.
579
+ * This framing is request-time only and may change between versions.
580
+ */
581
+ function renderSystemMessageUpdate(message) {
582
+ const parts = [];
583
+ const text = contentText(message.content);
584
+ if (text.length > 0) parts.push(text);
585
+ for (const [name, value] of Object.entries(message.sections ?? {})) parts.push(value === null ? `Removed system prompt section "${name}".` : `Updated system prompt section "${name}":\n\n${value}`);
586
+ return parts.join("\n\n");
587
+ }
588
+ /**
589
+ * `text.slice(start, end)` as a string of its own. V8 represents a slice of 13 or more characters as a view that keeps
590
+ * all of `text` alive, so a short excerpt kept from a large text (a 500-character error message cut from a megabyte
591
+ * response body) would keep the whole text alive as long as the excerpt lives. Appending a character and slicing it off
592
+ * again makes V8 copy just the slice.
593
+ */
594
+ function ownedSlice(text, start, end = text.length) {
595
+ return `${text.slice(start, end)} `.slice(0, -1);
596
+ }
597
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/telemetry.js
598
+ const provider = {
599
+ type: "string",
600
+ description: "Provider identifier.",
601
+ required: true
602
+ };
603
+ const model = {
604
+ type: "string",
605
+ description: "Requested model identifier.",
606
+ required: true
607
+ };
608
+ const stop = {
609
+ type: "string",
610
+ description: "Normalized stop reason.",
611
+ values: [
612
+ "pending",
613
+ "stop",
614
+ "length",
615
+ "toolUse",
616
+ "error",
617
+ "aborted",
618
+ "deferred"
619
+ ]
620
+ };
621
+ const request = {
622
+ description: "One logical model request, including authentication and provider setup.",
623
+ parents: { kind: "any" },
624
+ startAttributes: {
625
+ provider,
626
+ api: {
627
+ type: "string",
628
+ description: "API identifier.",
629
+ required: true
630
+ },
631
+ model,
632
+ reasoning: {
633
+ type: "string",
634
+ description: "Scalar requested reasoning level.",
635
+ required: false
636
+ }
637
+ },
638
+ endAttributes: {
639
+ stop,
640
+ "usage.input": {
641
+ type: "number",
642
+ description: "Uncached input tokens."
643
+ },
644
+ "usage.output": {
645
+ type: "number",
646
+ description: "Output tokens."
647
+ },
648
+ "usage.cache_read": {
649
+ type: "number",
650
+ description: "Cache-read tokens."
651
+ },
652
+ "usage.cache_write": {
653
+ type: "number",
654
+ description: "Cache-write tokens."
655
+ },
656
+ "cost.total": {
657
+ type: "number",
658
+ description: "Total request cost in USD."
659
+ },
660
+ "response.id": {
661
+ type: "string",
662
+ description: "Provider response identifier.",
663
+ cardinality: "high"
664
+ }
665
+ },
666
+ events: {
667
+ "pi.ai.first_chunk": {
668
+ description: "First normalized stream event delivered.",
669
+ attributes: {}
670
+ },
671
+ "pi.ai.block": {
672
+ description: "A completed content block; content is never recorded.",
673
+ attributes: {
674
+ type: {
675
+ type: "string",
676
+ description: "Block kind.",
677
+ values: [
678
+ "text",
679
+ "thinking",
680
+ "tool_call"
681
+ ],
682
+ required: true
683
+ },
684
+ index: {
685
+ type: "number",
686
+ description: "Content block index.",
687
+ required: true
688
+ },
689
+ chars: {
690
+ type: "number",
691
+ description: "UTF-16 character count.",
692
+ required: true
693
+ },
694
+ tool: {
695
+ type: "string",
696
+ description: "Tool name, for tool-call blocks only.",
697
+ required: false
698
+ }
699
+ }
700
+ }
701
+ },
702
+ status: {
703
+ default: "ok",
704
+ errorWhen: "Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok."
705
+ }
706
+ };
707
+ /** Pi-owned request metadata, bounded error status, events, and low-cardinality metrics. */
708
+ const AI_TELEMETRY_SCHEMA = defineTelemetrySchema({
709
+ version: 1,
710
+ spans: {
711
+ "pi.ai.request": request,
712
+ "pi.ai.poll": {
713
+ ...request,
714
+ description: "One deferred-response poll, not the deferred request's lifetime."
715
+ }
716
+ },
717
+ metrics: {
718
+ "pi.ai.request.duration": {
719
+ kind: "histogram",
720
+ description: "Logical request or poll duration.",
721
+ unit: "ms",
722
+ attributes: {
723
+ provider,
724
+ model,
725
+ stop: {
726
+ ...stop,
727
+ required: true
728
+ }
729
+ }
730
+ },
731
+ "pi.ai.first_chunk.duration": {
732
+ kind: "histogram",
733
+ description: "Time to the first normalized stream event.",
734
+ unit: "ms",
735
+ attributes: {
736
+ provider,
737
+ model
738
+ }
739
+ },
740
+ "pi.ai.tokens": {
741
+ kind: "counter",
742
+ description: "Reported model token usage; pending and deferred polls are excluded.",
743
+ unit: "token",
744
+ attributes: {
745
+ provider,
746
+ model,
747
+ kind: {
748
+ type: "string",
749
+ description: "Token usage category.",
750
+ values: [
751
+ "input",
752
+ "output",
753
+ "cache_read",
754
+ "cache_write"
755
+ ],
756
+ required: true
757
+ }
758
+ }
759
+ },
760
+ "pi.ai.cost": {
761
+ kind: "counter",
762
+ description: "Reported model cost; pending and deferred polls are excluded.",
763
+ unit: "USD",
764
+ attributes: {
765
+ provider,
766
+ model
767
+ }
768
+ }
769
+ }
770
+ });
771
+ function createInstruments(adapter) {
772
+ const metrics = createTypedMetrics(adapter, [AI_TELEMETRY_SCHEMA]);
773
+ return {
774
+ requestDuration: metrics.histogram("pi.ai.request.duration"),
775
+ firstChunkDuration: metrics.histogram("pi.ai.first_chunk.duration"),
776
+ tokens: metrics.counter("pi.ai.tokens"),
777
+ cost: metrics.counter("pi.ai.cost")
778
+ };
779
+ }
780
+ const instrumentCache = /* @__PURE__ */ new WeakMap();
781
+ function observeModelRequest(requestedModel, options, poll) {
782
+ const started = performance.now();
783
+ const attributes = {
784
+ provider: requestedModel.provider,
785
+ model: requestedModel.id
786
+ };
787
+ const adapter = options?.telemetry?.metrics ?? NOOP_TELEMETRY_METRICS;
788
+ let instruments = instrumentCache.get(adapter);
789
+ if (!instruments) {
790
+ instruments = createInstruments(adapter);
791
+ instrumentCache.set(adapter, instruments);
792
+ }
793
+ const { requestDuration, firstChunkDuration, tokens, cost } = instruments;
794
+ let span;
795
+ let finish;
796
+ let first = true;
797
+ const toolChars = /* @__PURE__ */ new Map();
798
+ const finished = new Promise((resolve) => {
799
+ finish = resolve;
800
+ });
801
+ const run = (activeSpan) => {
802
+ span = activeSpan;
803
+ return finished;
804
+ };
805
+ const startAttributes = {
806
+ ...attributes,
807
+ api: requestedModel.api,
808
+ ...typeof options?.reasoning === "string" ? { reasoning: options.reasoning } : {}
809
+ };
810
+ const start = createTypedSpanStarter(options?.telemetry ?? NOOP_TELEMETRY_CONTEXT, [AI_TELEMETRY_SCHEMA]);
811
+ if (poll) start("pi.ai.poll", startAttributes, run);
812
+ else start("pi.ai.request", startAttributes, run);
813
+ return {
814
+ onEvent(event) {
815
+ if (first) {
816
+ first = false;
817
+ span.addEvent("pi.ai.first_chunk");
818
+ firstChunkDuration.record(performance.now() - started, attributes, span);
819
+ }
820
+ if (event.type === "toolcall_delta") toolChars.set(event.contentIndex, (toolChars.get(event.contentIndex) ?? 0) + event.delta.length);
821
+ else if (event.type === "text_end" || event.type === "thinking_end") span.addEvent("pi.ai.block", {
822
+ type: event.type === "text_end" ? "text" : "thinking",
823
+ index: event.contentIndex,
824
+ chars: event.content.length
825
+ });
826
+ else if (event.type === "toolcall_end") {
827
+ const chars = toolChars.get(event.contentIndex) ?? 0;
828
+ toolChars.delete(event.contentIndex);
829
+ span.addEvent("pi.ai.block", {
830
+ type: "tool_call",
831
+ index: event.contentIndex,
832
+ chars,
833
+ tool: event.toolCall.name
834
+ });
835
+ }
836
+ },
837
+ onResult(message) {
838
+ if (message) {
839
+ span.setAttributes({
840
+ stop: message.stopReason,
841
+ "usage.input": message.usage.input,
842
+ "usage.output": message.usage.output,
843
+ "usage.cache_read": message.usage.cacheRead,
844
+ "usage.cache_write": message.usage.cacheWrite,
845
+ "cost.total": message.usage.cost.total,
846
+ "response.id": message.responseId
847
+ });
848
+ if (message.stopReason === "error") span.setStatus({
849
+ status: "error",
850
+ error: {
851
+ name: "provider_error",
852
+ message: ownedSlice(message.errorMessage ?? "", 0, 500)
853
+ }
854
+ });
855
+ requestDuration.record(performance.now() - started, {
856
+ ...attributes,
857
+ stop: message.stopReason
858
+ }, span);
859
+ if (!poll || message.stopReason !== "pending" && message.stopReason !== "deferred") {
860
+ tokens.add(message.usage.input, {
861
+ ...attributes,
862
+ kind: "input"
863
+ });
864
+ tokens.add(message.usage.output, {
865
+ ...attributes,
866
+ kind: "output"
867
+ });
868
+ tokens.add(message.usage.cacheRead, {
869
+ ...attributes,
870
+ kind: "cache_read"
871
+ });
872
+ tokens.add(message.usage.cacheWrite, {
873
+ ...attributes,
874
+ kind: "cache_write"
875
+ });
876
+ cost.add(message.usage.cost.total, attributes);
877
+ }
878
+ }
879
+ finish();
880
+ }
881
+ };
882
+ }
883
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/identity.js
884
+ const NVIDIA_NIM_HOST = "integrate.api.nvidia.com";
885
+ const OPENCODE_HOST = "opencode.ai";
886
+ /** Merge identities field by field; later sources win and undefined fields are skipped. */
887
+ function mergeClientIdentity(...sources) {
888
+ let merged;
889
+ for (const source of sources) {
890
+ if (!source) continue;
891
+ merged = { ...merged };
892
+ if (source.userAgent !== void 0) merged.userAgent = source.userAgent;
893
+ if (source.attribution !== void 0) merged.attribution = source.attribution;
894
+ if (source.version !== void 0) merged.version = source.version;
895
+ }
896
+ return merged;
897
+ }
898
+ /** The version in the detailed `User-Agent`. */
899
+ function getClientVersion(identity) {
900
+ return identity?.version ?? "1.6.0";
901
+ }
902
+ function runtimeDescription() {
903
+ if (typeof process === "undefined") return void 0;
904
+ const versions = process.versions;
905
+ if (versions?.bun) return `bun/${versions.bun}`;
906
+ if (versions?.node) return `node/${process.version}`;
907
+ }
908
+ /** The `User-Agent` value of an identity. */
909
+ function formatUserAgent(identity) {
910
+ const mode = identity?.userAgent ?? "detailed";
911
+ if (typeof mode === "object") return mode.custom;
912
+ if (mode === "short") return "pi";
913
+ const product = `pi/${getClientVersion(identity)}`;
914
+ const runtime = runtimeDescription();
915
+ return runtime ? `${product} (${process.platform}; ${runtime}; ${process.arch})` : `${product} (browser)`;
916
+ }
917
+ function matchesHost(baseUrl, expectedHost) {
918
+ try {
919
+ return new URL(baseUrl).hostname === expectedHost;
920
+ } catch {
921
+ return false;
922
+ }
923
+ }
924
+ function isOpenRouter(target) {
925
+ return target.provider === "openrouter" || target.baseUrl.includes("openrouter.ai");
926
+ }
927
+ function isNvidiaNim(target) {
928
+ return target.provider === "nvidia" || matchesHost(target.baseUrl, NVIDIA_NIM_HOST);
929
+ }
930
+ function isOpenCode(target) {
931
+ return target.provider === "opencode" || target.provider === "opencode-go" || matchesHost(target.baseUrl, OPENCODE_HOST);
932
+ }
933
+ /** Provider attribution headers of an identity for a request target. Empty when attribution is off. */
934
+ function getAttributionHeaders(target, identity) {
935
+ const attribution = identity?.attribution;
936
+ if (!attribution) return {};
937
+ const { name, url, categories } = attribution;
938
+ if (isOpenRouter(target)) return {
939
+ "HTTP-Referer": url,
940
+ "X-OpenRouter-Title": name,
941
+ ...categories === void 0 || categories.length === 0 ? {} : { "X-OpenRouter-Categories": categories.join(",") }
942
+ };
943
+ if (isNvidiaNim(target)) return { "X-BILLING-INVOKE-ORIGIN": name.charAt(0).toUpperCase() + name.slice(1) };
944
+ if (isOpenCode(target)) return { "x-opencode-client": name };
945
+ return {};
946
+ }
947
+ /**
948
+ * OpenCode's per-conversation routing header for requests to OpenCode, including custom providers pointing at it.
949
+ * Undefined without a session or for other targets.
950
+ */
951
+ function getOpenCodeSessionHeaders(target, sessionId) {
952
+ return sessionId && isOpenCode(target) ? { "x-opencode-session": sessionId } : void 0;
953
+ }
954
+ /**
955
+ * Default headers an identity adds to a request: `User-Agent` and provider attribution. APIs apply them below model,
956
+ * provider, and request headers, so configured headers override them and `null` request headers remove them.
957
+ */
958
+ function getIdentityHeaders(target, identity) {
959
+ return {
960
+ "User-Agent": formatUserAgent(identity),
961
+ ...getAttributionHeaders(target, identity)
962
+ };
963
+ }
964
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/model-operations.js
965
+ /** The type of a model. Models without `type` are chat models. */
966
+ function getModelType(model) {
967
+ return model.type ?? "chat";
968
+ }
969
+ /** Runtime-checked model type narrowing, including legacy chat models without `type`. */
970
+ function isModelType(model, type) {
971
+ return getModelType(model) === type;
972
+ }
973
+ function assertChatModel(model) {
974
+ if (!isModelType(model, "chat")) throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not a chat model`);
975
+ }
976
+ function assertImageModel(model) {
977
+ if (!isModelType(model, "image")) throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not an image model`);
978
+ }
979
+ function assertClassifierModel(model) {
980
+ if (!isModelType(model, "classifier")) throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not a classifier model`);
981
+ }
982
+ /** Rejects classifier images for models whose catalog entry does not accept image input. */
983
+ function assertClassifierInputSupported(model, context) {
984
+ if (context.images?.length && !model.input.includes("image")) throw new ModelsError("provider", `Model ${model.provider}/${model.id} does not accept image input`);
985
+ }
986
+ function imageErrorResult(model, error, aborted = false) {
987
+ return {
988
+ api: model.api,
989
+ provider: model.provider,
990
+ model: model.id,
991
+ output: [],
992
+ stopReason: aborted ? "aborted" : "error",
993
+ errorMessage: error instanceof Error ? error.message : String(error),
994
+ timestamp: Date.now()
995
+ };
996
+ }
997
+ function classifierErrorResult(model, error, aborted = false) {
998
+ return {
999
+ api: model.api,
1000
+ provider: model.provider,
1001
+ model: model.id,
1002
+ answers: {},
1003
+ stopReason: aborted ? "aborted" : "error",
1004
+ errorMessage: error instanceof Error ? error.message : String(error),
1005
+ timestamp: Date.now()
1006
+ };
1007
+ }
1008
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/transcript.js
1009
+ /**
1010
+ * Build the leading system message for a prompt and tool set. Returns undefined when
1011
+ * both are empty, so an empty transcript stays empty.
1012
+ */
1013
+ function createInitialSystemMessage(systemPrompt, tools) {
1014
+ const hasSystemPrompt = systemPrompt !== void 0 && systemPrompt.length > 0;
1015
+ const hasTools = tools !== void 0 && tools.length > 0;
1016
+ if (!hasSystemPrompt && !hasTools) return void 0;
1017
+ return {
1018
+ role: "system",
1019
+ content: systemPrompt ?? "",
1020
+ ...hasTools ? { toolsAdded: tools } : {},
1021
+ timestamp: 0
1022
+ };
1023
+ }
1024
+ /**
1025
+ * Fold `Context.systemPrompt` and `Context.tools` into a leading system message.
1026
+ * This is the only entry point that produces a {@link TranscriptContext}; every
1027
+ * provider-facing function expects the result.
1028
+ */
1029
+ function normalizeContext(context) {
1030
+ const initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);
1031
+ return { messages: initialMessage ? [initialMessage, ...context.messages] : context.messages };
1032
+ }
1033
+ function isSystemMessage(message) {
1034
+ return message.role === "system";
1035
+ }
1036
+ /** Return the leading system message, if the transcript starts with one. */
1037
+ function getInitialSystemMessage(messages) {
1038
+ const first = messages[0];
1039
+ return first && isSystemMessage(first) ? first : void 0;
1040
+ }
1041
+ /** Resolve the tools available after applying every transcript delta in order. */
1042
+ function getCurrentTools(messages) {
1043
+ const tools = /* @__PURE__ */ new Map();
1044
+ for (const message of messages) {
1045
+ if (!isSystemMessage(message)) continue;
1046
+ for (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);
1047
+ for (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);
1048
+ }
1049
+ return [...tools.values()];
1050
+ }
1051
+ /**
1052
+ * Replay every system message into one leading system message holding the current
1053
+ * prompt and tools. Later `content` is appended to the base prompt, `sections` are
1054
+ * patched by name, and tools are resolved with {@link getCurrentTools}.
1055
+ */
1056
+ function getCurrentSystemMessage(messages) {
1057
+ const content = [];
1058
+ const sections = /* @__PURE__ */ new Map();
1059
+ let timestamp;
1060
+ for (const message of messages) {
1061
+ if (!isSystemMessage(message)) continue;
1062
+ timestamp ??= message.timestamp;
1063
+ const text = contentText(message.content);
1064
+ if (text.length > 0) content.push(text);
1065
+ for (const [name, value] of Object.entries(message.sections ?? {})) if (value === null) sections.delete(name);
1066
+ else sections.set(name, value);
1067
+ }
1068
+ const tools = getCurrentTools(messages);
1069
+ if (timestamp === void 0 && tools.length === 0) return void 0;
1070
+ return {
1071
+ role: "system",
1072
+ content: content.join("\n\n"),
1073
+ ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {},
1074
+ ...tools.length > 0 ? { toolsAdded: tools } : {},
1075
+ timestamp: timestamp ?? 0
1076
+ };
1077
+ }
1078
+ /**
1079
+ * Rebuild the transcript for APIs without mid-conversation system messages: the replayed
1080
+ * system message leads, and every later system message is dropped.
1081
+ */
1082
+ function collapseSystemMessages(context) {
1083
+ const head = getCurrentSystemMessage(context.messages);
1084
+ const messages = context.messages.filter((message) => message.role !== "system");
1085
+ return { messages: head ? [head, ...messages] : messages };
1086
+ }
1087
+ /** Keep later system messages in place when the model accepts them; otherwise collapse them. */
1088
+ function resolveTranscript(context, supportsMidConvoSystemMessages) {
1089
+ return supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);
1090
+ }
1091
+ /** Every definition referenced by transcript tool state, in first-declaration order. */
1092
+ function getDeclaredTools(messages) {
1093
+ const definitions = /* @__PURE__ */ new Map();
1094
+ for (const message of messages) {
1095
+ if (!isSystemMessage(message)) continue;
1096
+ for (const tool of message.toolsAdded ?? []) definitions.set(tool.name, tool);
1097
+ }
1098
+ return [...definitions.values()];
1099
+ }
1100
+ /** Index of the last system message with a removal or same-name redeclaration, or -1. */
1101
+ function findLastNonAdditiveToolChange(systemMessages) {
1102
+ const declared = /* @__PURE__ */ new Set();
1103
+ let last = -1;
1104
+ for (let index = 0; index < systemMessages.length; index++) {
1105
+ const message = systemMessages[index];
1106
+ if ((message.toolsRemoved?.length ?? 0) > 0) last = index;
1107
+ for (const tool of message.toolsAdded ?? []) {
1108
+ if (declared.has(tool.name)) last = index;
1109
+ declared.add(tool.name);
1110
+ }
1111
+ }
1112
+ return last;
1113
+ }
1114
+ /**
1115
+ * Split tool declarations between the top-level request field and in-place changes.
1116
+ *
1117
+ * With `"changes"`, the top-level list stays empty and every system message, including the
1118
+ * leading one, declares its tools in place: an in-place declaration can replace an earlier
1119
+ * in-place one, but not a top-level one. With `"additions"`, a removal or redefinition cannot be
1120
+ * expressed in place, so the top-level list becomes the tool state after the last such change;
1121
+ * later additions stay anchored, and the cached prefix is invalidated once per removal instead
1122
+ * of on every later addition. With `"none"`, the top-level list is the current tool set.
1123
+ */
1124
+ function resolveTranscriptTools(messages, support) {
1125
+ const systemMessages = messages.filter(isSystemMessage);
1126
+ if (support === "none") return {
1127
+ requestTools: getCurrentTools(systemMessages),
1128
+ foldedSystemMessages: systemMessages.length
1129
+ };
1130
+ if (support === "changes") return {
1131
+ requestTools: [],
1132
+ foldedSystemMessages: 0
1133
+ };
1134
+ const folded = Math.max(getInitialSystemMessage(messages) ? 1 : 0, findLastNonAdditiveToolChange(systemMessages) + 1);
1135
+ return {
1136
+ requestTools: getCurrentTools(systemMessages.slice(0, folded)),
1137
+ foldedSystemMessages: folded
1138
+ };
1139
+ }
1140
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/models.js
1141
+ const KNOWN_MODEL_TYPES = {
1142
+ chat: true,
1143
+ image: true,
1144
+ classifier: true
1145
+ };
1146
+ /** Models from stores and remote sources may have types that only newer versions know. */
1147
+ function hasKnownModelType(model) {
1148
+ return Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model));
1149
+ }
1150
+ /** Drops stored models whose type this version does not know. */
1151
+ function withKnownModelTypes(entry) {
1152
+ return {
1153
+ ...entry,
1154
+ models: entry.models.filter(hasKnownModelType)
1155
+ };
1156
+ }
1157
+ function mergeHeaders(base, override) {
1158
+ if (!base && !override) return void 0;
1159
+ const merged = { ...base };
1160
+ for (const [name, value] of Object.entries(override ?? {})) {
1161
+ const lowerName = name.toLowerCase();
1162
+ for (const existingName of Object.keys(merged)) if (existingName.toLowerCase() === lowerName) delete merged[existingName];
1163
+ merged[name] = value;
1164
+ }
1165
+ return merged;
1166
+ }
1167
+ var ModelsImpl = class {
1168
+ providers = /* @__PURE__ */ new Map();
1169
+ credentials;
1170
+ modelsStore;
1171
+ authContext;
1172
+ identity;
1173
+ refreshGenerations = /* @__PURE__ */ new Map();
1174
+ refreshControllers = /* @__PURE__ */ new Map();
1175
+ publicationChains = /* @__PURE__ */ new Map();
1176
+ constructor(options) {
1177
+ this.credentials = options?.credentials ?? new InMemoryCredentialStore();
1178
+ this.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();
1179
+ this.authContext = options?.authContext ?? defaultProviderAuthContext();
1180
+ this.identity = options?.identity;
1181
+ }
1182
+ setProvider(provider) {
1183
+ this.supersedeProviderRefresh(provider.id);
1184
+ this.providers.set(provider.id, provider);
1185
+ }
1186
+ deleteProvider(id) {
1187
+ this.supersedeProviderRefresh(id);
1188
+ this.providers.delete(id);
1189
+ }
1190
+ clearProviders() {
1191
+ for (const id of /* @__PURE__ */ new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) this.supersedeProviderRefresh(id);
1192
+ this.providers.clear();
1193
+ }
1194
+ getProviders() {
1195
+ return Array.from(this.providers.values());
1196
+ }
1197
+ getProvider(id) {
1198
+ return this.providers.get(id);
1199
+ }
1200
+ getModels(provider) {
1201
+ if (provider !== void 0) {
1202
+ const entry = this.providers.get(provider);
1203
+ if (!entry) return [];
1204
+ try {
1205
+ return entry.getModels();
1206
+ } catch {
1207
+ return [];
1208
+ }
1209
+ }
1210
+ const models = [];
1211
+ for (const entry of this.providers.values()) try {
1212
+ models.push(...entry.getModels());
1213
+ } catch {}
1214
+ return models;
1215
+ }
1216
+ getAllModels(provider) {
1217
+ if (provider !== void 0) {
1218
+ const entry = this.providers.get(provider);
1219
+ if (!entry) return [];
1220
+ try {
1221
+ return entry.getAllModels?.() ?? entry.getModels();
1222
+ } catch {
1223
+ return [];
1224
+ }
1225
+ }
1226
+ const models = [];
1227
+ for (const entry of this.providers.values()) try {
1228
+ models.push(...entry.getAllModels?.() ?? entry.getModels());
1229
+ } catch {}
1230
+ return models;
1231
+ }
1232
+ getModelsOfType(type, provider) {
1233
+ return this.getAllModels(provider).filter((model) => isModelType(model, type));
1234
+ }
1235
+ getModel(provider, id) {
1236
+ return this.getModels(provider).find((model) => model.id === id);
1237
+ }
1238
+ getModelOfType(type, provider, id) {
1239
+ return this.getModelsOfType(type, provider).find((model) => model.id === id);
1240
+ }
1241
+ supersedeProviderRefresh(providerId) {
1242
+ const generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;
1243
+ this.refreshGenerations.set(providerId, generation);
1244
+ const previous = this.refreshControllers.get(providerId);
1245
+ if (previous) {
1246
+ this.refreshControllers.delete(providerId);
1247
+ previous.abort();
1248
+ }
1249
+ return generation;
1250
+ }
1251
+ beginProviderRefresh(providerId) {
1252
+ const generation = this.supersedeProviderRefresh(providerId);
1253
+ const controller = new AbortController();
1254
+ this.refreshControllers.set(providerId, controller);
1255
+ return {
1256
+ generation,
1257
+ controller
1258
+ };
1259
+ }
1260
+ publishProviderModels(providerId, generation, signal, publication) {
1261
+ const previous = this.publicationChains.get(providerId) ?? Promise.resolve();
1262
+ const queued = (async () => {
1263
+ await previous.catch(() => {});
1264
+ if (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;
1265
+ if (publication.persist === null) await this.modelsStore.delete(providerId, { signal });
1266
+ else if (publication.persist !== void 0) await this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });
1267
+ if (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;
1268
+ publication.update?.();
1269
+ return true;
1270
+ })();
1271
+ const tail = queued.catch(() => {});
1272
+ this.publicationChains.set(providerId, tail);
1273
+ tail.then(() => {
1274
+ if (this.publicationChains.get(providerId) === tail) this.publicationChains.delete(providerId);
1275
+ });
1276
+ return raceWithAbortSignal(queued, signal);
1277
+ }
1278
+ async runProviderRefreshPhase(provider, credential, allowNetwork, force, generation, signal) {
1279
+ const stored = await this.modelsStore.read(provider.id, { signal });
1280
+ await provider.refreshModels({
1281
+ credential,
1282
+ stored: stored ? withKnownModelTypes(structuredClone(stored)) : void 0,
1283
+ publish: (publication) => this.publishProviderModels(provider.id, generation, signal, publication),
1284
+ allowNetwork,
1285
+ force: allowNetwork ? force : void 0,
1286
+ signal,
1287
+ baseUrl: provider.baseUrl
1288
+ });
1289
+ }
1290
+ async refresh(options = {}) {
1291
+ const allowNetwork = options.allowNetwork ?? true;
1292
+ const callerSignal = operationSignal(options.signal);
1293
+ const errors = /* @__PURE__ */ new Map();
1294
+ if (callerSignal.aborted) return {
1295
+ aborted: true,
1296
+ errors
1297
+ };
1298
+ const selected = options.providers ? new Set(options.providers) : void 0;
1299
+ const refreshable = Array.from(this.providers.values()).filter((provider) => provider.refreshModels !== void 0 && (!selected || selected.has(provider.id)));
1300
+ const refresh = Promise.all(refreshable.map(async (provider) => {
1301
+ const { generation, controller } = this.beginProviderRefresh(provider.id);
1302
+ const signal = AbortSignal.any([callerSignal, controller.signal]);
1303
+ const operation = (async () => {
1304
+ let storedCredential;
1305
+ let credentialError;
1306
+ try {
1307
+ storedCredential = await this.readCredential(provider.id, signal);
1308
+ } catch (error) {
1309
+ credentialError = error;
1310
+ }
1311
+ await this.runProviderRefreshPhase(provider, storedCredential, false, void 0, generation, signal);
1312
+ if (credentialError !== void 0) throw credentialError;
1313
+ if (!allowNetwork || signal.aborted) return;
1314
+ const network = await this.resolveNetworkRefresh(provider, storedCredential, signal);
1315
+ if (!network) return;
1316
+ await this.runProviderRefreshPhase(provider, network.credential, true, options.force, generation, signal);
1317
+ })();
1318
+ try {
1319
+ await raceWithAbortSignal(operation, signal);
1320
+ } catch (error) {
1321
+ if (!signal.aborted) errors.set(provider.id, error instanceof Error ? error : new ModelsError("model_source", `Model refresh failed for ${provider.id}`, { cause: error }));
1322
+ } finally {
1323
+ if (this.refreshControllers.get(provider.id) === controller) this.refreshControllers.delete(provider.id);
1324
+ }
1325
+ }));
1326
+ try {
1327
+ await raceWithAbortSignal(refresh, callerSignal);
1328
+ } catch (error) {
1329
+ if (!callerSignal.aborted) throw error;
1330
+ }
1331
+ return {
1332
+ aborted: callerSignal.aborted,
1333
+ errors: new Map(errors)
1334
+ };
1335
+ }
1336
+ /** The credential for the network refresh phase, or undefined when the provider is not configured. */
1337
+ async resolveNetworkRefresh(provider, stored, signal) {
1338
+ if (provider.refreshModelsAuth === "configured") return await this.checkProviderAuth(provider, stored, signal) ? {} : void 0;
1339
+ const credential = await this.resolveRefreshCredential(provider, stored, signal);
1340
+ return credential ? { credential } : void 0;
1341
+ }
1342
+ async resolveRefreshCredential(provider, stored, signal) {
1343
+ if (stored?.type === "oauth") {
1344
+ const oauth = provider.auth.oauth;
1345
+ if (!oauth) return void 0;
1346
+ if (Date.now() < stored.expires) return stored;
1347
+ if (signal.aborted) return void 0;
1348
+ return refreshStoredOAuthCredential(this.credentials, provider.id, oauth, (current) => Date.now() >= current.expires, signal);
1349
+ }
1350
+ const apiKey = provider.auth.apiKey;
1351
+ if (!apiKey) return void 0;
1352
+ const credential = stored?.type === "api_key" ? stored : void 0;
1353
+ const result = await apiKey.resolve({
1354
+ ctx: this.authContext,
1355
+ credential,
1356
+ signal
1357
+ });
1358
+ if (!result) return void 0;
1359
+ return {
1360
+ type: "api_key",
1361
+ key: result.auth.apiKey,
1362
+ env: result.env
1363
+ };
1364
+ }
1365
+ async readCredential(providerId, signal) {
1366
+ try {
1367
+ return await this.credentials.read(providerId, { signal });
1368
+ } catch (error) {
1369
+ throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
1370
+ }
1371
+ }
1372
+ async checkProviderAuth(provider, credential, signal) {
1373
+ if (credential?.type === "oauth") return provider.auth.oauth ? {
1374
+ source: "OAuth",
1375
+ type: "oauth"
1376
+ } : void 0;
1377
+ const apiKey = provider.auth.apiKey;
1378
+ if (!apiKey) return void 0;
1379
+ if (apiKey.check) try {
1380
+ return await apiKey.check({
1381
+ ctx: this.authContext,
1382
+ credential: credential?.type === "api_key" ? credential : void 0,
1383
+ signal
1384
+ });
1385
+ } catch (error) {
1386
+ throw new ModelsError("auth", `API key auth check failed for provider ${provider.id}`, { cause: error });
1387
+ }
1388
+ const resolution = await resolveProviderAuth(provider, this.credentials, this.authContext, { signal });
1389
+ return resolution ? {
1390
+ source: resolution.source,
1391
+ type: "api_key"
1392
+ } : void 0;
1393
+ }
1394
+ checkAuth(providerId, options) {
1395
+ const signal = operationSignal(options?.signal);
1396
+ return raceWithAbortSignal((async () => {
1397
+ signal.throwIfAborted();
1398
+ const provider = this.providers.get(providerId);
1399
+ if (!provider) return void 0;
1400
+ return this.checkProviderAuth(provider, await this.readCredential(providerId, signal), signal);
1401
+ })(), signal);
1402
+ }
1403
+ async getAuthenticatedProviders(providerId, signal) {
1404
+ signal.throwIfAborted();
1405
+ const providers = providerId ? [this.providers.get(providerId)].filter((entry) => entry !== void 0) : this.getProviders();
1406
+ return (await Promise.all(providers.map(async (provider) => {
1407
+ const credential = await this.readCredential(provider.id, signal);
1408
+ return {
1409
+ provider,
1410
+ credential,
1411
+ auth: await this.checkProviderAuth(provider, credential, signal)
1412
+ };
1413
+ }))).filter((entry) => entry.auth !== void 0);
1414
+ }
1415
+ getAvailable(providerId, options) {
1416
+ const signal = operationSignal(options?.signal);
1417
+ return raceWithAbortSignal((async () => {
1418
+ return (await this.getAuthenticatedProviders(providerId, signal)).flatMap(({ provider, credential }) => {
1419
+ const models = provider.getModels();
1420
+ return provider.filterModels?.(models, credential) ?? models;
1421
+ });
1422
+ })(), signal);
1423
+ }
1424
+ async getAvailableOfType(type, providerId, options) {
1425
+ return (await this.getAllAvailable(providerId, options)).filter((model) => isModelType(model, type));
1426
+ }
1427
+ getAllAvailable(providerId, options) {
1428
+ const signal = operationSignal(options?.signal);
1429
+ return raceWithAbortSignal((async () => {
1430
+ return (await this.getAuthenticatedProviders(providerId, signal)).flatMap(({ provider, credential }) => {
1431
+ const models = provider.getAllModels?.() ?? provider.getModels();
1432
+ if (provider.filterAllModels) return provider.filterAllModels(models, credential);
1433
+ if (!provider.filterModels) return models;
1434
+ const availableChatIds = new Set(provider.filterModels(provider.getModels(), credential).map((model) => model.id));
1435
+ return models.filter((model) => !isModelType(model, "chat") || availableChatIds.has(model.id));
1436
+ });
1437
+ })(), signal);
1438
+ }
1439
+ async getAuth(providerOrModel, overrides) {
1440
+ const signal = operationSignal(overrides?.signal);
1441
+ const providerId = typeof providerOrModel === "string" ? providerOrModel : providerOrModel.provider;
1442
+ const provider = this.providers.get(providerId);
1443
+ if (!provider) return void 0;
1444
+ const result = await resolveProviderAuth(provider, this.credentials, this.authContext, {
1445
+ ...overrides,
1446
+ signal
1447
+ });
1448
+ if (!result || typeof providerOrModel === "string" || !providerOrModel.headers) return result;
1449
+ return {
1450
+ ...result,
1451
+ auth: {
1452
+ ...result.auth,
1453
+ headers: mergeHeaders(result.auth.headers, providerOrModel.headers)
1454
+ }
1455
+ };
1456
+ }
1457
+ async login(providerId, type, interaction, options) {
1458
+ const signal = operationSignal(interaction.signal);
1459
+ signal.throwIfAborted();
1460
+ const provider = this.providers.get(providerId);
1461
+ if (!provider) throw new ModelsError("provider", `Unknown provider: ${providerId}`);
1462
+ const method = type === "oauth" ? provider.auth.oauth : provider.auth.apiKey;
1463
+ if (!method?.login) throw new ModelsError("auth", `${provider.name} does not support ${type} login`);
1464
+ const credential = await raceWithAbortSignal(method.login({
1465
+ ...interaction,
1466
+ signal
1467
+ }, options), signal);
1468
+ let mutationStarted = false;
1469
+ let markMutationStarted;
1470
+ const started = new Promise((resolve) => {
1471
+ markMutationStarted = resolve;
1472
+ });
1473
+ const mutation = this.credentials.modify(providerId, async () => {
1474
+ mutationStarted = true;
1475
+ markMutationStarted?.();
1476
+ return credential;
1477
+ }, { signal });
1478
+ mutation.catch(() => {});
1479
+ try {
1480
+ await new Promise((resolve, reject) => {
1481
+ const onAbort = () => {
1482
+ if (!mutationStarted) reject(signal.reason);
1483
+ };
1484
+ signal.addEventListener("abort", onAbort, { once: true });
1485
+ Promise.race([started, mutation]).then(() => {
1486
+ signal.removeEventListener("abort", onAbort);
1487
+ resolve();
1488
+ }, (error) => {
1489
+ signal.removeEventListener("abort", onAbort);
1490
+ reject(error);
1491
+ });
1492
+ if (signal.aborted) onAbort();
1493
+ });
1494
+ await mutation;
1495
+ } catch (error) {
1496
+ signal.throwIfAborted();
1497
+ throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
1498
+ }
1499
+ return credential;
1500
+ }
1501
+ async logout(providerId, options) {
1502
+ const signal = operationSignal(options?.signal);
1503
+ signal.throwIfAborted();
1504
+ try {
1505
+ await this.credentials.delete(providerId, { signal });
1506
+ } catch (error) {
1507
+ signal.throwIfAborted();
1508
+ throw new ModelsError("auth", `Credential store delete failed for ${providerId}`, { cause: error });
1509
+ }
1510
+ }
1511
+ requireProvider(model) {
1512
+ const provider = this.providers.get(model.provider);
1513
+ if (!provider) throw new ModelsError("provider", `Unknown provider: ${model.provider}`);
1514
+ return provider;
1515
+ }
1516
+ requireChatProvider(model) {
1517
+ assertChatModel(model);
1518
+ return this.requireProvider(model);
1519
+ }
1520
+ async applyAuth(model, options) {
1521
+ this.requireProvider(model);
1522
+ const resolution = await this.getAuth(model, {
1523
+ apiKey: options?.apiKey,
1524
+ env: options?.env,
1525
+ signal: options?.signal
1526
+ });
1527
+ if (!resolution) throw new ModelsError("auth", `Provider is not configured: ${model.provider}`);
1528
+ const auth = resolution.auth;
1529
+ const apiKey = options?.apiKey ?? auth.apiKey;
1530
+ const requestModel = auth.baseUrl ? {
1531
+ ...model,
1532
+ baseUrl: auth.baseUrl
1533
+ } : model;
1534
+ let headers = mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel, options && "sessionId" in options && typeof options.sessionId === "string" ? options.sessionId : void 0), auth.headers), options?.headers);
1535
+ if (options?.transformHeaders) headers = await options.transformHeaders(headers ?? {});
1536
+ const env = resolution.env || options?.env ? {
1537
+ ...resolution.env ?? {},
1538
+ ...options?.env ?? {}
1539
+ } : void 0;
1540
+ const identity = mergeClientIdentity(this.identity, options?.identity);
1541
+ const { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};
1542
+ return {
1543
+ requestModel,
1544
+ requestOptions: {
1545
+ ...providerOptions,
1546
+ apiKey,
1547
+ headers,
1548
+ env,
1549
+ ...identity === void 0 ? {} : { identity }
1550
+ }
1551
+ };
1552
+ }
1553
+ stream(model, context, options) {
1554
+ const transcript = normalizeContext(context);
1555
+ return lazyStream(model, async () => {
1556
+ const provider = this.requireChatProvider(model);
1557
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
1558
+ return provider.stream(requestModel, transcript, requestOptions);
1559
+ }, observeModelRequest(model, options, false), options?.signal);
1560
+ }
1561
+ async complete(model, context, options) {
1562
+ return this.stream(model, context, options).result();
1563
+ }
1564
+ streamSimple(model, context, options) {
1565
+ const transcript = normalizeContext(context);
1566
+ return lazyStream(model, async () => {
1567
+ const provider = this.requireChatProvider(model);
1568
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
1569
+ return provider.streamSimple(requestModel, transcript, requestOptions);
1570
+ }, observeModelRequest(model, options, false), options?.signal);
1571
+ }
1572
+ async completeSimple(model, context, options) {
1573
+ return this.streamSimple(model, context, options).result();
1574
+ }
1575
+ streamDeferred(model, handle, options) {
1576
+ return lazyStream(model, async () => {
1577
+ const provider = this.requireChatProvider(model);
1578
+ if (!provider.fetchDeferred) throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
1579
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
1580
+ return provider.fetchDeferred(requestModel, handle, requestOptions);
1581
+ }, observeModelRequest(model, options, true), options?.signal);
1582
+ }
1583
+ async fetchDeferred(model, handle, options) {
1584
+ return this.streamDeferred(model, handle, options).result();
1585
+ }
1586
+ async cancelDeferred(model, handle, options) {
1587
+ const provider = this.requireChatProvider(model);
1588
+ if (!provider.cancelDeferred) throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
1589
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
1590
+ await provider.cancelDeferred(requestModel, handle, requestOptions);
1591
+ }
1592
+ async generateImages(model, context, options) {
1593
+ try {
1594
+ assertImageModel(model);
1595
+ const provider = this.requireProvider(model);
1596
+ if (!provider.generateImages) throw new ModelsError("provider", `Provider ${model.provider} does not support image generation`);
1597
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
1598
+ return await provider.generateImages(requestModel, context, requestOptions);
1599
+ } catch (error) {
1600
+ return imageErrorResult(model, error, options?.signal?.aborted);
1601
+ }
1602
+ }
1603
+ async classify(model, context, options) {
1604
+ try {
1605
+ assertClassifierModel(model);
1606
+ assertClassifierInputSupported(model, context);
1607
+ const provider = this.requireProvider(model);
1608
+ if (!provider.classify) throw new ModelsError("provider", `Provider ${model.provider} does not support classification`);
1609
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
1610
+ return await provider.classify(requestModel, context, requestOptions);
1611
+ } catch (error) {
1612
+ return classifierErrorResult(model, error, options?.signal?.aborted);
1613
+ }
1614
+ }
1615
+ };
1616
+ function createModels(options) {
1617
+ return new ModelsImpl(options);
1618
+ }
1619
+ /**
1620
+ * Builds a provider from parts. Built-in provider factories and models.json
1621
+ * custom providers both go through this. A single `api` streams all chat
1622
+ * models; an `api` map dispatches on `model.api`, and a model whose api has
1623
+ * no entry produces a stream error. One-shot operation maps dispatch on
1624
+ * `model.api` the same way. At least one concrete implementation across
1625
+ * `api`/`images`/`classifiers` is required; empty maps are rejected.
1626
+ */
1627
+ function createProvider(input) {
1628
+ const single = input.api && typeof input.api.stream === "function" ? input.api : void 0;
1629
+ const byApi = single || !input.api ? void 0 : input.api;
1630
+ const images = input.images;
1631
+ const classifiers = input.classifiers;
1632
+ const streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== void 0);
1633
+ const imageImplementations = Object.values(images ?? {}).filter((entry) => entry !== void 0);
1634
+ const classifierImplementations = Object.values(classifiers ?? {}).filter((entry) => entry !== void 0);
1635
+ if (streams.length === 0 && imageImplementations.length === 0 && classifierImplementations.length === 0) throw new Error(`Provider ${input.id}: at least one of "api", "images", or "classifiers" is required.`);
1636
+ const baselineModels = input.models;
1637
+ let dynamicModels = [];
1638
+ const fetchModels = input.fetchModels;
1639
+ const currentModels = () => {
1640
+ const merged = [...baselineModels];
1641
+ for (const model of dynamicModels) {
1642
+ const index = merged.findIndex((entry) => getModelType(entry) === getModelType(model) && entry.id === model.id);
1643
+ if (index >= 0) merged[index] = model;
1644
+ else merged.push(model);
1645
+ }
1646
+ return merged;
1647
+ };
1648
+ const apiFor = (model) => single ?? byApi?.[model.api];
1649
+ const dispatch = (model, run, signal) => {
1650
+ const streams = apiFor(model);
1651
+ if (!streams) return lazyStream(model, async () => {
1652
+ throw new ModelsError("stream", `Provider ${input.id} has no API implementation for "${model.api}"`);
1653
+ }, void 0, signal);
1654
+ return run(streams);
1655
+ };
1656
+ const provider = {
1657
+ id: input.id,
1658
+ name: input.name ?? input.id,
1659
+ baseUrl: input.baseUrl,
1660
+ headers: input.headers,
1661
+ auth: input.auth,
1662
+ getModels: () => currentModels().filter((model) => isModelType(model, "chat")),
1663
+ getAllModels: currentModels,
1664
+ refreshModels: fetchModels ? async (context) => {
1665
+ if (context.stored) {
1666
+ const restored = context.stored.models.filter((model) => model.provider === input.id).map((model) => model);
1667
+ if (!await context.publish({ update: () => {
1668
+ dynamicModels = restored;
1669
+ } })) return;
1670
+ }
1671
+ if (!context.allowNetwork || context.signal.aborted) return;
1672
+ const fetched = await fetchModels(context);
1673
+ if (context.signal.aborted) return;
1674
+ const refreshed = fetched.filter(hasKnownModelType);
1675
+ await context.publish({
1676
+ persist: {
1677
+ models: refreshed,
1678
+ checkedAt: Date.now()
1679
+ },
1680
+ update: () => {
1681
+ dynamicModels = refreshed;
1682
+ }
1683
+ });
1684
+ } : void 0,
1685
+ filterModels: input.filterModels,
1686
+ filterAllModels: input.filterAllModels,
1687
+ stream: (model, context, options) => dispatch(model, (streams) => streams.stream(model, context, options), options?.signal),
1688
+ streamSimple: (model, context, options) => dispatch(model, (streams) => streams.streamSimple(model, context, options), options?.signal)
1689
+ };
1690
+ if (streams.some((entry) => entry.fetchDeferred !== void 0)) provider.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
1691
+ const implementation = apiFor(model);
1692
+ if (!implementation?.fetchDeferred) throw new ModelsError("provider", `Provider ${input.id} does not support deferred responses for "${model.api}"`);
1693
+ return implementation.fetchDeferred(model, handle, options);
1694
+ }, void 0, options?.signal);
1695
+ if (streams.some((entry) => entry.cancelDeferred !== void 0)) provider.cancelDeferred = async (model, handle, options) => {
1696
+ const implementation = apiFor(model);
1697
+ if (!implementation?.cancelDeferred) throw new ModelsError("provider", `Provider ${input.id} cannot cancel deferred responses for "${model.api}"`);
1698
+ await implementation.cancelDeferred(model, handle, options);
1699
+ };
1700
+ if (images && imageImplementations.length > 0) provider.generateImages = async (model, context, options) => {
1701
+ const implementation = images[model.api];
1702
+ if (!implementation) return imageErrorResult(model, new ModelsError("provider", `Provider ${input.id} has no image generation implementation for "${model.api}"`));
1703
+ return implementation.generateImages(model, context, options);
1704
+ };
1705
+ if (classifiers && classifierImplementations.length > 0) provider.classify = async (model, context, options) => {
1706
+ const implementation = classifiers[model.api];
1707
+ if (!implementation) return classifierErrorResult(model, new ModelsError("provider", `Provider ${input.id} has no classifier implementation for "${model.api}"`));
1708
+ return implementation.classify(model, context, options);
1709
+ };
1710
+ return provider;
1711
+ }
1712
+ function calculateCost(model, usage) {
1713
+ const inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;
1714
+ let rates = model.cost;
1715
+ let matchedThreshold = -1;
1716
+ for (const tier of model.cost.tiers ?? []) if (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {
1717
+ rates = tier;
1718
+ matchedThreshold = tier.inputTokensAbove;
1719
+ }
1720
+ const longWrite = usage.cacheWrite1h ?? 0;
1721
+ const shortWrite = usage.cacheWrite - longWrite;
1722
+ usage.cost.input = rates.input / 1e6 * usage.input;
1723
+ usage.cost.output = rates.output / 1e6 * usage.output;
1724
+ usage.cost.cacheRead = rates.cacheRead / 1e6 * usage.cacheRead;
1725
+ usage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1e6;
1726
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
1727
+ usage.cost.totalFromProvider = false;
1728
+ return usage.cost;
1729
+ }
1730
+ const EXTENDED_THINKING_LEVELS = [
1731
+ "off",
1732
+ "minimal",
1733
+ "low",
1734
+ "medium",
1735
+ "high",
1736
+ "xhigh",
1737
+ "max"
1738
+ ];
1739
+ function getSupportedThinkingLevels(model) {
1740
+ if (!model.reasoning) return ["off"];
1741
+ return EXTENDED_THINKING_LEVELS.filter((level) => {
1742
+ const mapped = model.thinkingLevelMap?.[level];
1743
+ if (mapped === null) return false;
1744
+ if (level === "xhigh" || level === "max") return mapped !== void 0;
1745
+ return true;
1746
+ });
1747
+ }
1748
+ function clampThinkingLevel(model, level) {
1749
+ const availableLevels = getSupportedThinkingLevels(model);
1750
+ if (availableLevels.includes(level)) return level;
1751
+ const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);
1752
+ if (requestedIndex === -1) return availableLevels[0] ?? "off";
1753
+ for (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {
1754
+ const candidate = EXTENDED_THINKING_LEVELS[i];
1755
+ if (availableLevels.includes(candidate)) return candidate;
1756
+ }
1757
+ for (let i = requestedIndex - 1; i >= 0; i--) {
1758
+ const candidate = EXTENDED_THINKING_LEVELS[i];
1759
+ if (availableLevels.includes(candidate)) return candidate;
1760
+ }
1761
+ return availableLevels[0] ?? "off";
1762
+ }
1763
+ export { AssistantMessageEventStream as _, getDeclaredTools as a, resolveTranscriptTools as c, ownedSlice as d, renderSystemMessageUpdate as f, lazyApi as g, formatThrownValue as h, createProvider as i, getIdentityHeaders as l, createAssistantMessageDiagnostic as m, clampThinkingLevel as n, normalizeContext as o, appendAssistantMessageDiagnostic as p, createModels as r, resolveTranscript as s, calculateCost as t, getSystemMessageText as u, __commonJSMin as v, __require as y };