@goah/cli 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/dist/LICENSE +201 -0
  2. package/dist/THIRD-PARTY-NOTICES.md +2319 -0
  3. package/dist/anthropic-messages-WBFOHES5.js +7214 -0
  4. package/dist/azure-openai-responses-NZFH3PO6.js +253 -0
  5. package/dist/chunk-25XSBFX6.js +639 -0
  6. package/dist/chunk-2QBQZGXF.js +110 -0
  7. package/dist/chunk-2ZP2NBW3.js +345 -0
  8. package/dist/chunk-4KA63VNZ.js +2 -0
  9. package/dist/chunk-4M6TXTT5.js +86 -0
  10. package/dist/chunk-4US7ZHT3.js +20 -0
  11. package/dist/chunk-6M3OOCKO.js +11809 -0
  12. package/dist/chunk-7AXAFDPG.js +17 -0
  13. package/dist/chunk-7E7V6OIU.js +920 -0
  14. package/dist/chunk-BXA47DTF.js +548 -0
  15. package/dist/chunk-D2DVAH37.js +25 -0
  16. package/dist/chunk-FSBUS2BI.js +26 -0
  17. package/dist/chunk-GKDRAHLI.js +4787 -0
  18. package/dist/chunk-H462EFJP.js +89 -0
  19. package/dist/chunk-IIJQ3DW4.js +35 -0
  20. package/dist/chunk-JQD5EWJY.js +34 -0
  21. package/dist/chunk-K26BVR6O.js +61 -0
  22. package/dist/chunk-KAO7WIXG.js +31 -0
  23. package/dist/chunk-KJ4HJCTK.js +1178 -0
  24. package/dist/chunk-LBKI23CC.js +9810 -0
  25. package/dist/chunk-LKBKZEHT.js +41 -0
  26. package/dist/chunk-MD7TLTXZ.js +18 -0
  27. package/dist/chunk-MPXK7QBL.js +868 -0
  28. package/dist/chunk-NRLGWZJC.js +11 -0
  29. package/dist/chunk-QBD6EJ2Z.js +1746 -0
  30. package/dist/chunk-R6I3VKME.js +132 -0
  31. package/dist/chunk-TJON22J4.js +87 -0
  32. package/dist/chunk-ULY36ME4.js +33097 -0
  33. package/dist/chunk-XALZLRYK.js +9221 -0
  34. package/dist/chunk-XPQKM3L7.js +57 -0
  35. package/dist/chunk-YH6YJ2IB.js +1773 -0
  36. package/dist/cli.d.ts +0 -2
  37. package/dist/cli.js +13716 -580
  38. package/dist/console/assets/{index-Rtc_B7cs.js → index-B1vGMXKr.js} +11 -11
  39. package/dist/console/assets/{index-Rtc_B7cs.js.map → index-B1vGMXKr.js.map} +1 -1
  40. package/dist/console/index.html +1 -1
  41. package/dist/dist-65MDQA4Q.js +1126 -0
  42. package/dist/dist-KNR2XL6J.js +39 -0
  43. package/dist/execution.d.ts +557 -2
  44. package/dist/execution.js +37 -2
  45. package/dist/faux-runner-worker.js +128 -0
  46. package/dist/google-generative-ai-YMHXZSFE.js +422 -0
  47. package/dist/google-vertex-X6DB3ZQ6.js +471 -0
  48. package/dist/index.d.ts +853 -25
  49. package/dist/index.js +84 -385
  50. package/dist/kernel.d.ts +39 -2
  51. package/dist/kernel.js +21 -2
  52. package/dist/mistral-conversations-TY3MMD6G.js +718 -0
  53. package/dist/multipart-parser-F6M4NJZU.js +373 -0
  54. package/dist/openai-codex-responses-BRDUMLN5.js +1374 -0
  55. package/dist/openai-completions-CX634XN3.js +1139 -0
  56. package/dist/openai-responses-HMCXJIHT.js +300 -0
  57. package/dist/openrouter-images-KTWET2H2.js +148 -0
  58. package/dist/pi-messages-XL5OEC4K.js +307 -0
  59. package/dist/pi-worker.js +671 -0
  60. package/dist/runner-pi.d.ts +342 -2
  61. package/dist/runner-pi.js +46 -2
  62. package/dist/runner-registry-GD4BYCQC.js +22 -0
  63. package/dist/sqlite.d.ts +446 -2
  64. package/dist/sqlite.js +15 -2
  65. package/dist/src-F2KBSV4T.js +1398 -0
  66. package/dist/supervisor.d.ts +625 -2
  67. package/dist/supervisor.js +39 -2
  68. package/dist/testkit.d.ts +564 -2
  69. package/dist/testkit.js +127 -2
  70. package/dist/transcript.d.ts +84 -2
  71. package/dist/transcript.js +25 -2
  72. package/dist/verification-worker.js +72 -0
  73. package/package.json +2 -26
  74. package/dist/cli.d.ts.map +0 -1
  75. package/dist/cli.js.map +0 -1
  76. package/dist/control.d.ts +0 -106
  77. package/dist/control.d.ts.map +0 -1
  78. package/dist/control.js +0 -242
  79. package/dist/control.js.map +0 -1
  80. package/dist/execution.d.ts.map +0 -1
  81. package/dist/execution.js.map +0 -1
  82. package/dist/index.d.ts.map +0 -1
  83. package/dist/index.js.map +0 -1
  84. package/dist/kernel.d.ts.map +0 -1
  85. package/dist/kernel.js.map +0 -1
  86. package/dist/live-config.d.ts +0 -10
  87. package/dist/live-config.d.ts.map +0 -1
  88. package/dist/live-config.js +0 -44
  89. package/dist/live-config.js.map +0 -1
  90. package/dist/prompt-queue.d.ts +0 -13
  91. package/dist/prompt-queue.d.ts.map +0 -1
  92. package/dist/prompt-queue.js +0 -35
  93. package/dist/prompt-queue.js.map +0 -1
  94. package/dist/runner-pi.d.ts.map +0 -1
  95. package/dist/runner-pi.js.map +0 -1
  96. package/dist/runner-registry.d.ts +0 -8
  97. package/dist/runner-registry.d.ts.map +0 -1
  98. package/dist/runner-registry.js +0 -12
  99. package/dist/runner-registry.js.map +0 -1
  100. package/dist/searchable-select.d.ts +0 -24
  101. package/dist/searchable-select.d.ts.map +0 -1
  102. package/dist/searchable-select.js +0 -61
  103. package/dist/searchable-select.js.map +0 -1
  104. package/dist/secret-input.d.ts +0 -8
  105. package/dist/secret-input.d.ts.map +0 -1
  106. package/dist/secret-input.js +0 -14
  107. package/dist/secret-input.js.map +0 -1
  108. package/dist/setup-wizard.d.ts +0 -22
  109. package/dist/setup-wizard.d.ts.map +0 -1
  110. package/dist/setup-wizard.js +0 -154
  111. package/dist/setup-wizard.js.map +0 -1
  112. package/dist/sqlite.d.ts.map +0 -1
  113. package/dist/sqlite.js.map +0 -1
  114. package/dist/supervisor.d.ts.map +0 -1
  115. package/dist/supervisor.js.map +0 -1
  116. package/dist/testkit.d.ts.map +0 -1
  117. package/dist/testkit.js.map +0 -1
  118. package/dist/thread-inspect.d.ts +0 -47
  119. package/dist/thread-inspect.d.ts.map +0 -1
  120. package/dist/thread-inspect.js +0 -78
  121. package/dist/thread-inspect.js.map +0 -1
  122. package/dist/transcript.d.ts.map +0 -1
  123. package/dist/transcript.js.map +0 -1
  124. package/dist/tui-theme.d.ts +0 -17
  125. package/dist/tui-theme.d.ts.map +0 -1
  126. package/dist/tui-theme.js +0 -19
  127. package/dist/tui-theme.js.map +0 -1
  128. package/dist/tui.d.ts +0 -24
  129. package/dist/tui.d.ts.map +0 -1
  130. package/dist/tui.js +0 -784
  131. package/dist/tui.js.map +0 -1
  132. package/dist/update.d.ts +0 -16
  133. package/dist/update.d.ts.map +0 -1
  134. package/dist/update.js +0 -67
  135. package/dist/update.js.map +0 -1
  136. package/dist/web-console.d.ts +0 -33
  137. package/dist/web-console.d.ts.map +0 -1
  138. package/dist/web-console.js +0 -242
  139. package/dist/web-console.js.map +0 -1
  140. package/dist/welcome.d.ts +0 -30
  141. package/dist/welcome.d.ts.map +0 -1
  142. package/dist/welcome.js +0 -69
  143. package/dist/welcome.js.map +0 -1
  144. package/node_modules/goah-ledger-contract/dist/execution.d.ts +0 -544
  145. package/node_modules/goah-ledger-contract/dist/execution.d.ts.map +0 -1
  146. package/node_modules/goah-ledger-contract/dist/execution.js +0 -52
  147. package/node_modules/goah-ledger-contract/dist/execution.js.map +0 -1
  148. package/node_modules/goah-ledger-contract/dist/index.d.ts +0 -4
  149. package/node_modules/goah-ledger-contract/dist/index.d.ts.map +0 -1
  150. package/node_modules/goah-ledger-contract/dist/index.js +0 -4
  151. package/node_modules/goah-ledger-contract/dist/index.js.map +0 -1
  152. package/node_modules/goah-ledger-contract/dist/kernel.d.ts +0 -37
  153. package/node_modules/goah-ledger-contract/dist/kernel.d.ts.map +0 -1
  154. package/node_modules/goah-ledger-contract/dist/kernel.js +0 -8
  155. package/node_modules/goah-ledger-contract/dist/kernel.js.map +0 -1
  156. package/node_modules/goah-ledger-contract/dist/transcript.d.ts +0 -63
  157. package/node_modules/goah-ledger-contract/dist/transcript.d.ts.map +0 -1
  158. package/node_modules/goah-ledger-contract/dist/transcript.js +0 -115
  159. package/node_modules/goah-ledger-contract/dist/transcript.js.map +0 -1
  160. package/node_modules/goah-ledger-contract/package.json +0 -28
  161. package/node_modules/goah-ledger-sqlite/dist/index.d.ts +0 -86
  162. package/node_modules/goah-ledger-sqlite/dist/index.d.ts.map +0 -1
  163. package/node_modules/goah-ledger-sqlite/dist/index.js +0 -1254
  164. package/node_modules/goah-ledger-sqlite/dist/index.js.map +0 -1
  165. package/node_modules/goah-ledger-sqlite/package.json +0 -26
  166. package/node_modules/goah-runner-pi/dist/configurator.d.ts +0 -20
  167. package/node_modules/goah-runner-pi/dist/configurator.d.ts.map +0 -1
  168. package/node_modules/goah-runner-pi/dist/configurator.js +0 -423
  169. package/node_modules/goah-runner-pi/dist/configurator.js.map +0 -1
  170. package/node_modules/goah-runner-pi/dist/credential-store.d.ts +0 -14
  171. package/node_modules/goah-runner-pi/dist/credential-store.d.ts.map +0 -1
  172. package/node_modules/goah-runner-pi/dist/credential-store.js +0 -163
  173. package/node_modules/goah-runner-pi/dist/credential-store.js.map +0 -1
  174. package/node_modules/goah-runner-pi/dist/env-spec.d.ts +0 -17
  175. package/node_modules/goah-runner-pi/dist/env-spec.d.ts.map +0 -1
  176. package/node_modules/goah-runner-pi/dist/env-spec.js +0 -95
  177. package/node_modules/goah-runner-pi/dist/env-spec.js.map +0 -1
  178. package/node_modules/goah-runner-pi/dist/index.d.ts +0 -76
  179. package/node_modules/goah-runner-pi/dist/index.d.ts.map +0 -1
  180. package/node_modules/goah-runner-pi/dist/index.js +0 -326
  181. package/node_modules/goah-runner-pi/dist/index.js.map +0 -1
  182. package/node_modules/goah-runner-pi/dist/model-provider.d.ts +0 -30
  183. package/node_modules/goah-runner-pi/dist/model-provider.d.ts.map +0 -1
  184. package/node_modules/goah-runner-pi/dist/model-provider.js +0 -96
  185. package/node_modules/goah-runner-pi/dist/model-provider.js.map +0 -1
  186. package/node_modules/goah-runner-pi/dist/pi-worker.d.ts +0 -31
  187. package/node_modules/goah-runner-pi/dist/pi-worker.d.ts.map +0 -1
  188. package/node_modules/goah-runner-pi/dist/pi-worker.js +0 -579
  189. package/node_modules/goah-runner-pi/dist/pi-worker.js.map +0 -1
  190. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.d.ts +0 -2
  191. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.d.ts.map +0 -1
  192. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.js +0 -3
  193. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.js.map +0 -1
  194. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.d.ts +0 -2
  195. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.d.ts.map +0 -1
  196. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.js +0 -5
  197. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.js.map +0 -1
  198. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.d.ts +0 -2
  199. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.d.ts.map +0 -1
  200. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.js +0 -5
  201. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.js.map +0 -1
  202. package/node_modules/goah-runner-pi/dist/test-helpers.d.ts +0 -4
  203. package/node_modules/goah-runner-pi/dist/test-helpers.d.ts.map +0 -1
  204. package/node_modules/goah-runner-pi/dist/test-helpers.js +0 -13
  205. package/node_modules/goah-runner-pi/dist/test-helpers.js.map +0 -1
  206. package/node_modules/goah-runner-pi/dist/verification-worker.d.ts +0 -2
  207. package/node_modules/goah-runner-pi/dist/verification-worker.d.ts.map +0 -1
  208. package/node_modules/goah-runner-pi/dist/verification-worker.js +0 -46
  209. package/node_modules/goah-runner-pi/dist/verification-worker.js.map +0 -1
  210. package/node_modules/goah-runner-pi/package.json +0 -28
  211. package/node_modules/goah-supervisor/dist/context-view.d.ts +0 -30
  212. package/node_modules/goah-supervisor/dist/context-view.d.ts.map +0 -1
  213. package/node_modules/goah-supervisor/dist/context-view.js +0 -58
  214. package/node_modules/goah-supervisor/dist/context-view.js.map +0 -1
  215. package/node_modules/goah-supervisor/dist/index.d.ts +0 -96
  216. package/node_modules/goah-supervisor/dist/index.d.ts.map +0 -1
  217. package/node_modules/goah-supervisor/dist/index.js +0 -1075
  218. package/node_modules/goah-supervisor/dist/index.js.map +0 -1
  219. package/node_modules/goah-supervisor/dist/roles.d.ts +0 -4
  220. package/node_modules/goah-supervisor/dist/roles.d.ts.map +0 -1
  221. package/node_modules/goah-supervisor/dist/roles.js +0 -29
  222. package/node_modules/goah-supervisor/dist/roles.js.map +0 -1
  223. package/node_modules/goah-supervisor/dist/verification.d.ts +0 -61
  224. package/node_modules/goah-supervisor/dist/verification.d.ts.map +0 -1
  225. package/node_modules/goah-supervisor/dist/verification.js +0 -135
  226. package/node_modules/goah-supervisor/dist/verification.js.map +0 -1
  227. package/node_modules/goah-supervisor/package.json +0 -26
  228. package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts +0 -2
  229. package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts.map +0 -1
  230. package/node_modules/goah-testkit/dist/faux-runner-worker.js +0 -82
  231. package/node_modules/goah-testkit/dist/faux-runner-worker.js.map +0 -1
  232. package/node_modules/goah-testkit/dist/index.d.ts +0 -49
  233. package/node_modules/goah-testkit/dist/index.d.ts.map +0 -1
  234. package/node_modules/goah-testkit/dist/index.js +0 -96
  235. package/node_modules/goah-testkit/dist/index.js.map +0 -1
  236. package/node_modules/goah-testkit/package.json +0 -29
@@ -0,0 +1,868 @@
1
+ import { createRequire as __goahCreateRequire } from "node:module";
2
+ const require = __goahCreateRequire(import.meta.url);
3
+ import {
4
+ AssistantMessageEventStream,
5
+ formatThrownValue
6
+ } from "./chunk-2QBQZGXF.js";
7
+
8
+ // ../../node_modules/@earendil-works/pi-ai/dist/api/lazy.js
9
+ function createSetupErrorMessage(model, error) {
10
+ return {
11
+ role: "assistant",
12
+ content: [],
13
+ api: model.api,
14
+ provider: model.provider,
15
+ model: model.id,
16
+ usage: {
17
+ input: 0,
18
+ output: 0,
19
+ cacheRead: 0,
20
+ cacheWrite: 0,
21
+ totalTokens: 0,
22
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
23
+ },
24
+ stopReason: "error",
25
+ errorMessage: error instanceof Error ? error.message : String(error),
26
+ timestamp: Date.now()
27
+ };
28
+ }
29
+ function hasResult(source) {
30
+ return typeof source.result === "function";
31
+ }
32
+ async function forwardStream(target, source) {
33
+ for await (const event of source) {
34
+ target.push(event);
35
+ }
36
+ target.end(hasResult(source) ? await source.result() : void 0);
37
+ }
38
+ function lazyStream(model, setup) {
39
+ const outer = new AssistantMessageEventStream();
40
+ setup().then((inner) => forwardStream(outer, inner)).catch((error) => {
41
+ const message = createSetupErrorMessage(model, error);
42
+ outer.push({ type: "error", reason: "error", error: message });
43
+ outer.end(message);
44
+ });
45
+ return outer;
46
+ }
47
+ function lazyApi(load, capabilities) {
48
+ const api = {
49
+ stream: (model, context, options) => lazyStream(model, async () => (await load()).stream(model, context, options)),
50
+ streamSimple: (model, context, options) => lazyStream(model, async () => (await load()).streamSimple(model, context, options))
51
+ };
52
+ if (capabilities?.fetchDeferred) {
53
+ api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
54
+ const implementation = await load();
55
+ if (!implementation.fetchDeferred)
56
+ throw new Error("API does not support deferred responses");
57
+ return implementation.fetchDeferred(model, handle, options);
58
+ });
59
+ }
60
+ if (capabilities?.cancelDeferred) {
61
+ api.cancelDeferred = async (model, handle, options) => {
62
+ const implementation = await load();
63
+ if (!implementation.cancelDeferred)
64
+ throw new Error("API cannot cancel deferred responses");
65
+ await implementation.cancelDeferred(model, handle, options);
66
+ };
67
+ }
68
+ return api;
69
+ }
70
+
71
+ // ../../node_modules/@earendil-works/pi-ai/dist/auth/context.js
72
+ var __rewriteRelativeImportExtension = function(path, preserveJsx) {
73
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
74
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
75
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
76
+ });
77
+ }
78
+ return path;
79
+ };
80
+ var importNodeModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));
81
+ function getProcessEnv() {
82
+ const proc = globalThis.process;
83
+ return proc?.env;
84
+ }
85
+ function defaultProviderAuthContext() {
86
+ return {
87
+ async env(name) {
88
+ const value = getProcessEnv()?.[name];
89
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
90
+ },
91
+ async fileExists(path) {
92
+ try {
93
+ const fs = await importNodeModule("node:fs/promises");
94
+ let resolved = path;
95
+ if (resolved.startsWith("~")) {
96
+ const os = await importNodeModule("node:os");
97
+ resolved = os.homedir() + resolved.slice(1);
98
+ }
99
+ await fs.access(resolved);
100
+ return true;
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+ };
106
+ }
107
+
108
+ // ../../node_modules/@earendil-works/pi-ai/dist/utils/abort.js
109
+ function abortReason(signal) {
110
+ if (signal.reason !== void 0)
111
+ return signal.reason;
112
+ const error = new Error("The operation was aborted");
113
+ error.name = "AbortError";
114
+ return error;
115
+ }
116
+ function operationSignal(signal) {
117
+ return signal ?? new AbortController().signal;
118
+ }
119
+ function raceWithAbortSignal(operation, signal) {
120
+ if (signal.aborted) {
121
+ void operation.catch(() => {
122
+ });
123
+ return Promise.reject(abortReason(signal));
124
+ }
125
+ return new Promise((resolve, reject) => {
126
+ let settled = false;
127
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
128
+ const onAbort = () => {
129
+ if (settled)
130
+ return;
131
+ settled = true;
132
+ cleanup();
133
+ reject(abortReason(signal));
134
+ };
135
+ signal.addEventListener("abort", onAbort, { once: true });
136
+ void operation.then((value) => {
137
+ if (settled)
138
+ return;
139
+ settled = true;
140
+ cleanup();
141
+ resolve(value);
142
+ }, (error) => {
143
+ if (settled)
144
+ return;
145
+ settled = true;
146
+ cleanup();
147
+ reject(error);
148
+ });
149
+ if (signal.aborted)
150
+ onAbort();
151
+ });
152
+ }
153
+
154
+ // ../../node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js
155
+ var InMemoryCredentialStore = class {
156
+ credentials = /* @__PURE__ */ new Map();
157
+ chains = /* @__PURE__ */ new Map();
158
+ /** Serialize tasks per provider id without releasing the chain before active work settles. */
159
+ enqueue(providerId, task, options) {
160
+ const signal = operationSignal(options?.signal);
161
+ const previous = this.chains.get(providerId) ?? Promise.resolve();
162
+ const queued = (async () => {
163
+ await previous.catch(() => {
164
+ });
165
+ signal.throwIfAborted();
166
+ return task();
167
+ })();
168
+ const tail = queued.catch(() => {
169
+ });
170
+ this.chains.set(providerId, tail);
171
+ void tail.then(() => {
172
+ if (this.chains.get(providerId) === tail)
173
+ this.chains.delete(providerId);
174
+ });
175
+ return raceWithAbortSignal(queued, signal);
176
+ }
177
+ async read(providerId, options) {
178
+ options?.signal?.throwIfAborted();
179
+ return this.credentials.get(providerId);
180
+ }
181
+ async list(options) {
182
+ options?.signal?.throwIfAborted();
183
+ return [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));
184
+ }
185
+ modify(providerId, fn, options) {
186
+ return this.enqueue(providerId, async () => {
187
+ const current = this.credentials.get(providerId);
188
+ const next = await fn(current);
189
+ options?.signal?.throwIfAborted();
190
+ if (next !== void 0)
191
+ this.credentials.set(providerId, next);
192
+ return next ?? current;
193
+ }, options);
194
+ }
195
+ delete(providerId, options) {
196
+ return this.enqueue(providerId, async () => {
197
+ this.credentials.delete(providerId);
198
+ }, options);
199
+ }
200
+ };
201
+
202
+ // ../../node_modules/@earendil-works/pi-ai/dist/auth/resolve.js
203
+ var ModelsError = class extends Error {
204
+ code;
205
+ constructor(code, message, options) {
206
+ super(withCauseDetail(message, options?.cause), options);
207
+ this.name = "ModelsError";
208
+ this.code = code;
209
+ }
210
+ };
211
+ function withCauseDetail(message, cause) {
212
+ if (cause === void 0 || cause === null)
213
+ return message;
214
+ const detail = formatThrownValue(cause).trim();
215
+ if (!detail || message.includes(detail))
216
+ return message;
217
+ return `${message}: ${detail}`;
218
+ }
219
+ function resolveProviderAuth(provider, credentials, authContext, overrides) {
220
+ const signal = operationSignal(overrides?.signal);
221
+ return raceWithAbortSignal(resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal), signal);
222
+ }
223
+ async function resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal) {
224
+ signal.throwIfAborted();
225
+ const requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;
226
+ if (overrides?.apiKey !== void 0 && provider.auth.apiKey) {
227
+ return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, {
228
+ type: "api_key",
229
+ key: overrides.apiKey,
230
+ env: overrides.env
231
+ }, signal);
232
+ }
233
+ const stored = await readCredential(credentials, provider.id, signal);
234
+ if (stored) {
235
+ if (stored.type === "oauth" && provider.auth.oauth) {
236
+ return resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored, signal, overrides?.minOAuthValidityMs);
237
+ }
238
+ if (stored.type === "api_key" && provider.auth.apiKey) {
239
+ const credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;
240
+ return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);
241
+ }
242
+ return void 0;
243
+ }
244
+ return provider.auth.apiKey ? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, void 0, signal) : void 0;
245
+ }
246
+ function overlayEnvAuthContext(base, env) {
247
+ return {
248
+ env: async (name) => env[name] || await base.env(name),
249
+ fileExists: (path) => base.fileExists(path)
250
+ };
251
+ }
252
+ var DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1e3;
253
+ var DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15e3;
254
+ async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal, minOAuthValidityMs) {
255
+ const minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);
256
+ const expiresSoon = (credential2) => Date.now() + minimumValidityMs >= credential2.expires;
257
+ let credential = stored;
258
+ if (expiresSoon(credential)) {
259
+ let post;
260
+ try {
261
+ post = await credentials.modify(providerId, async (current) => {
262
+ if (current?.type !== "oauth")
263
+ return void 0;
264
+ if (!expiresSoon(current))
265
+ return void 0;
266
+ try {
267
+ const refreshSignal = AbortSignal.any([
268
+ signal,
269
+ AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS)
270
+ ]);
271
+ return await oauth.refresh(current, refreshSignal);
272
+ } catch (error) {
273
+ throw new ModelsError("oauth", `OAuth refresh failed for ${providerId}`, { cause: error });
274
+ }
275
+ }, { signal });
276
+ } catch (error) {
277
+ if (error instanceof ModelsError)
278
+ throw error;
279
+ throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
280
+ }
281
+ if (post?.type !== "oauth")
282
+ return void 0;
283
+ credential = post;
284
+ if (minOAuthValidityMs !== void 0 && expiresSoon(credential)) {
285
+ throw new ModelsError("oauth", `OAuth refresh returned a token that expires too soon for ${providerId}`);
286
+ }
287
+ }
288
+ try {
289
+ return { auth: await oauth.toAuth(credential), source: "OAuth" };
290
+ } catch (error) {
291
+ throw new ModelsError("oauth", `OAuth auth derivation failed for ${providerId}`, { cause: error });
292
+ }
293
+ }
294
+ async function resolveApiKey(authContext, apiKey, providerId, credential, signal) {
295
+ try {
296
+ return await apiKey.resolve({ ctx: authContext, credential, signal });
297
+ } catch (error) {
298
+ throw new ModelsError("auth", `API key auth failed for provider ${providerId}`, { cause: error });
299
+ }
300
+ }
301
+ async function readCredential(credentials, providerId, signal) {
302
+ try {
303
+ return await credentials.read(providerId, { signal });
304
+ } catch (error) {
305
+ throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
306
+ }
307
+ }
308
+
309
+ // ../../node_modules/@earendil-works/pi-ai/dist/models-store.js
310
+ var InMemoryModelsStore = class {
311
+ entries = /* @__PURE__ */ new Map();
312
+ async read(providerId, options) {
313
+ options?.signal?.throwIfAborted();
314
+ const entry = this.entries.get(providerId);
315
+ return entry ? structuredClone(entry) : void 0;
316
+ }
317
+ async write(providerId, entry, options) {
318
+ options?.signal?.throwIfAborted();
319
+ this.entries.set(providerId, structuredClone(entry));
320
+ }
321
+ async delete(providerId, options) {
322
+ options?.signal?.throwIfAborted();
323
+ this.entries.delete(providerId);
324
+ }
325
+ };
326
+
327
+ // ../../node_modules/@earendil-works/pi-ai/dist/models.js
328
+ function mergeHeaders(base, override) {
329
+ if (!base && !override)
330
+ return void 0;
331
+ const merged = { ...base };
332
+ for (const [name, value] of Object.entries(override ?? {})) {
333
+ const lowerName = name.toLowerCase();
334
+ for (const existingName of Object.keys(merged)) {
335
+ if (existingName.toLowerCase() === lowerName)
336
+ delete merged[existingName];
337
+ }
338
+ merged[name] = value;
339
+ }
340
+ return merged;
341
+ }
342
+ var ModelsImpl = class {
343
+ providers = /* @__PURE__ */ new Map();
344
+ credentials;
345
+ modelsStore;
346
+ authContext;
347
+ refreshGenerations = /* @__PURE__ */ new Map();
348
+ refreshControllers = /* @__PURE__ */ new Map();
349
+ publicationChains = /* @__PURE__ */ new Map();
350
+ constructor(options) {
351
+ this.credentials = options?.credentials ?? new InMemoryCredentialStore();
352
+ this.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();
353
+ this.authContext = options?.authContext ?? defaultProviderAuthContext();
354
+ }
355
+ setProvider(provider) {
356
+ this.supersedeProviderRefresh(provider.id);
357
+ this.providers.set(provider.id, provider);
358
+ }
359
+ deleteProvider(id) {
360
+ this.supersedeProviderRefresh(id);
361
+ this.providers.delete(id);
362
+ }
363
+ clearProviders() {
364
+ for (const id of /* @__PURE__ */ new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) {
365
+ this.supersedeProviderRefresh(id);
366
+ }
367
+ this.providers.clear();
368
+ }
369
+ getProviders() {
370
+ return Array.from(this.providers.values());
371
+ }
372
+ getProvider(id) {
373
+ return this.providers.get(id);
374
+ }
375
+ getModels(provider) {
376
+ if (provider !== void 0) {
377
+ const entry = this.providers.get(provider);
378
+ if (!entry)
379
+ return [];
380
+ try {
381
+ return entry.getModels();
382
+ } catch {
383
+ return [];
384
+ }
385
+ }
386
+ const models = [];
387
+ for (const entry of this.providers.values()) {
388
+ try {
389
+ models.push(...entry.getModels());
390
+ } catch {
391
+ }
392
+ }
393
+ return models;
394
+ }
395
+ getModel(provider, id) {
396
+ return this.getModels(provider).find((model) => model.id === id);
397
+ }
398
+ supersedeProviderRefresh(providerId) {
399
+ const generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;
400
+ this.refreshGenerations.set(providerId, generation);
401
+ const previous = this.refreshControllers.get(providerId);
402
+ if (previous) {
403
+ this.refreshControllers.delete(providerId);
404
+ previous.abort();
405
+ }
406
+ return generation;
407
+ }
408
+ beginProviderRefresh(providerId) {
409
+ const generation = this.supersedeProviderRefresh(providerId);
410
+ const controller = new AbortController();
411
+ this.refreshControllers.set(providerId, controller);
412
+ return { generation, controller };
413
+ }
414
+ publishProviderModels(providerId, generation, signal, publication) {
415
+ const previous = this.publicationChains.get(providerId) ?? Promise.resolve();
416
+ const queued = (async () => {
417
+ await previous.catch(() => {
418
+ });
419
+ if (signal.aborted || this.refreshGenerations.get(providerId) !== generation)
420
+ return false;
421
+ if (publication.persist === null) {
422
+ await this.modelsStore.delete(providerId, { signal });
423
+ } else if (publication.persist !== void 0) {
424
+ await this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });
425
+ }
426
+ if (signal.aborted || this.refreshGenerations.get(providerId) !== generation)
427
+ return false;
428
+ publication.update?.();
429
+ return true;
430
+ })();
431
+ const tail = queued.catch(() => {
432
+ });
433
+ this.publicationChains.set(providerId, tail);
434
+ void tail.then(() => {
435
+ if (this.publicationChains.get(providerId) === tail)
436
+ this.publicationChains.delete(providerId);
437
+ });
438
+ return raceWithAbortSignal(queued, signal);
439
+ }
440
+ async runProviderRefreshPhase(provider, credential, allowNetwork, force, generation, signal) {
441
+ const stored = await this.modelsStore.read(provider.id, { signal });
442
+ await provider.refreshModels({
443
+ credential,
444
+ stored: stored ? structuredClone(stored) : void 0,
445
+ publish: (publication) => this.publishProviderModels(provider.id, generation, signal, publication),
446
+ allowNetwork,
447
+ force: allowNetwork ? force : void 0,
448
+ signal
449
+ });
450
+ }
451
+ async refresh(options = {}) {
452
+ const allowNetwork = options.allowNetwork ?? true;
453
+ const callerSignal = operationSignal(options.signal);
454
+ const errors = /* @__PURE__ */ new Map();
455
+ if (callerSignal.aborted)
456
+ return { aborted: true, errors };
457
+ const selected = options.providers ? new Set(options.providers) : void 0;
458
+ const refreshable = Array.from(this.providers.values()).filter((provider) => provider.refreshModels !== void 0 && (!selected || selected.has(provider.id)));
459
+ const refresh = Promise.all(refreshable.map(async (provider) => {
460
+ const { generation, controller } = this.beginProviderRefresh(provider.id);
461
+ const signal = AbortSignal.any([callerSignal, controller.signal]);
462
+ const operation = (async () => {
463
+ let storedCredential;
464
+ let credentialError;
465
+ try {
466
+ storedCredential = await this.readCredential(provider.id, signal);
467
+ } catch (error) {
468
+ credentialError = error;
469
+ }
470
+ await this.runProviderRefreshPhase(provider, storedCredential, false, void 0, generation, signal);
471
+ if (credentialError !== void 0)
472
+ throw credentialError;
473
+ if (!allowNetwork || signal.aborted)
474
+ return;
475
+ const credential = await this.resolveRefreshCredential(provider, storedCredential, signal);
476
+ if (!credential)
477
+ return;
478
+ await this.runProviderRefreshPhase(provider, credential, true, options.force, generation, signal);
479
+ })();
480
+ try {
481
+ await raceWithAbortSignal(operation, signal);
482
+ } catch (error) {
483
+ if (!signal.aborted) {
484
+ errors.set(provider.id, error instanceof Error ? error : new ModelsError("model_source", `Model refresh failed for ${provider.id}`, { cause: error }));
485
+ }
486
+ } finally {
487
+ if (this.refreshControllers.get(provider.id) === controller) {
488
+ this.refreshControllers.delete(provider.id);
489
+ }
490
+ }
491
+ }));
492
+ try {
493
+ await raceWithAbortSignal(refresh, callerSignal);
494
+ } catch (error) {
495
+ if (!callerSignal.aborted)
496
+ throw error;
497
+ }
498
+ return { aborted: callerSignal.aborted, errors: new Map(errors) };
499
+ }
500
+ async resolveRefreshCredential(provider, stored, signal) {
501
+ if (stored?.type === "oauth") {
502
+ const oauth = provider.auth.oauth;
503
+ if (!oauth)
504
+ return void 0;
505
+ if (Date.now() < stored.expires)
506
+ return stored;
507
+ if (signal.aborted)
508
+ return void 0;
509
+ const post = await this.credentials.modify(provider.id, async (current) => {
510
+ if (current?.type !== "oauth" || Date.now() < current.expires)
511
+ return void 0;
512
+ return oauth.refresh(current, signal);
513
+ }, { signal });
514
+ return post?.type === "oauth" ? post : void 0;
515
+ }
516
+ const apiKey = provider.auth.apiKey;
517
+ if (!apiKey)
518
+ return void 0;
519
+ const credential = stored?.type === "api_key" ? stored : void 0;
520
+ const result = await apiKey.resolve({ ctx: this.authContext, credential, signal });
521
+ if (!result)
522
+ return void 0;
523
+ return { type: "api_key", key: result.auth.apiKey, env: result.env };
524
+ }
525
+ async readCredential(providerId, signal) {
526
+ try {
527
+ return await this.credentials.read(providerId, { signal });
528
+ } catch (error) {
529
+ throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
530
+ }
531
+ }
532
+ async checkProviderAuth(provider, credential, signal) {
533
+ if (credential?.type === "oauth") {
534
+ return provider.auth.oauth ? { source: "OAuth", type: "oauth" } : void 0;
535
+ }
536
+ const apiKey = provider.auth.apiKey;
537
+ if (!apiKey)
538
+ return void 0;
539
+ if (apiKey.check) {
540
+ try {
541
+ return await apiKey.check({
542
+ ctx: this.authContext,
543
+ credential: credential?.type === "api_key" ? credential : void 0,
544
+ signal
545
+ });
546
+ } catch (error) {
547
+ throw new ModelsError("auth", `API key auth check failed for provider ${provider.id}`, { cause: error });
548
+ }
549
+ }
550
+ const resolution = await resolveProviderAuth(provider, this.credentials, this.authContext, { signal });
551
+ return resolution ? { source: resolution.source, type: "api_key" } : void 0;
552
+ }
553
+ checkAuth(providerId, options) {
554
+ const signal = operationSignal(options?.signal);
555
+ const check = (async () => {
556
+ signal.throwIfAborted();
557
+ const provider = this.providers.get(providerId);
558
+ if (!provider)
559
+ return void 0;
560
+ return this.checkProviderAuth(provider, await this.readCredential(providerId, signal), signal);
561
+ })();
562
+ return raceWithAbortSignal(check, signal);
563
+ }
564
+ getAvailable(providerId, options) {
565
+ const signal = operationSignal(options?.signal);
566
+ const available = (async () => {
567
+ signal.throwIfAborted();
568
+ const providers = providerId ? [this.providers.get(providerId)].filter((entry) => entry !== void 0) : this.getProviders();
569
+ const checks = await Promise.all(providers.map(async (provider) => {
570
+ const credential = await this.readCredential(provider.id, signal);
571
+ return { provider, credential, auth: await this.checkProviderAuth(provider, credential, signal) };
572
+ }));
573
+ return checks.flatMap(({ provider, credential, auth }) => {
574
+ if (!auth)
575
+ return [];
576
+ const models = provider.getModels();
577
+ return provider.filterModels?.(models, credential) ?? models;
578
+ });
579
+ })();
580
+ return raceWithAbortSignal(available, signal);
581
+ }
582
+ async getAuth(providerOrModel, overrides) {
583
+ const signal = operationSignal(overrides?.signal);
584
+ const providerId = typeof providerOrModel === "string" ? providerOrModel : providerOrModel.provider;
585
+ const provider = this.providers.get(providerId);
586
+ if (!provider)
587
+ return void 0;
588
+ const result = await resolveProviderAuth(provider, this.credentials, this.authContext, { ...overrides, signal });
589
+ if (!result || typeof providerOrModel === "string" || !providerOrModel.headers)
590
+ return result;
591
+ return {
592
+ ...result,
593
+ auth: {
594
+ ...result.auth,
595
+ headers: mergeHeaders(result.auth.headers, providerOrModel.headers)
596
+ }
597
+ };
598
+ }
599
+ async login(providerId, type, interaction) {
600
+ const signal = operationSignal(interaction.signal);
601
+ signal.throwIfAborted();
602
+ const provider = this.providers.get(providerId);
603
+ if (!provider)
604
+ throw new ModelsError("provider", `Unknown provider: ${providerId}`);
605
+ const method = type === "oauth" ? provider.auth.oauth : provider.auth.apiKey;
606
+ if (!method?.login) {
607
+ throw new ModelsError("auth", `${provider.name} does not support ${type} login`);
608
+ }
609
+ const loginOperation = method.login({ ...interaction, signal });
610
+ const credential = await raceWithAbortSignal(loginOperation, signal);
611
+ let mutationStarted = false;
612
+ let markMutationStarted;
613
+ const started = new Promise((resolve) => {
614
+ markMutationStarted = resolve;
615
+ });
616
+ const mutation = this.credentials.modify(providerId, async () => {
617
+ mutationStarted = true;
618
+ markMutationStarted?.();
619
+ return credential;
620
+ }, { signal });
621
+ void mutation.catch(() => {
622
+ });
623
+ try {
624
+ await new Promise((resolve, reject) => {
625
+ const onAbort = () => {
626
+ if (!mutationStarted)
627
+ reject(signal.reason);
628
+ };
629
+ signal.addEventListener("abort", onAbort, { once: true });
630
+ void Promise.race([started, mutation]).then(() => {
631
+ signal.removeEventListener("abort", onAbort);
632
+ resolve();
633
+ }, (error) => {
634
+ signal.removeEventListener("abort", onAbort);
635
+ reject(error);
636
+ });
637
+ if (signal.aborted)
638
+ onAbort();
639
+ });
640
+ await mutation;
641
+ } catch (error) {
642
+ signal.throwIfAborted();
643
+ throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
644
+ }
645
+ return credential;
646
+ }
647
+ async logout(providerId, options) {
648
+ const signal = operationSignal(options?.signal);
649
+ signal.throwIfAborted();
650
+ try {
651
+ await this.credentials.delete(providerId, { signal });
652
+ } catch (error) {
653
+ signal.throwIfAborted();
654
+ throw new ModelsError("auth", `Credential store delete failed for ${providerId}`, { cause: error });
655
+ }
656
+ }
657
+ requireProvider(model) {
658
+ const provider = this.providers.get(model.provider);
659
+ if (!provider) {
660
+ throw new ModelsError("provider", `Unknown provider: ${model.provider}`);
661
+ }
662
+ return provider;
663
+ }
664
+ async applyAuth(model, options) {
665
+ this.requireProvider(model);
666
+ const resolution = await this.getAuth(model, {
667
+ apiKey: options?.apiKey,
668
+ env: options?.env,
669
+ signal: options?.signal
670
+ });
671
+ if (!resolution) {
672
+ throw new ModelsError("auth", `Provider is not configured: ${model.provider}`);
673
+ }
674
+ const auth = resolution.auth;
675
+ const apiKey = options?.apiKey ?? auth.apiKey;
676
+ let headers = mergeHeaders(auth.headers, options?.headers);
677
+ if (options?.transformHeaders)
678
+ headers = await options.transformHeaders(headers ?? {});
679
+ const env = resolution.env || options?.env ? { ...resolution.env ?? {}, ...options?.env ?? {} } : void 0;
680
+ const requestModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;
681
+ const { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};
682
+ const requestOptions = { ...providerOptions, apiKey, headers, env };
683
+ return { requestModel, requestOptions };
684
+ }
685
+ stream(model, context, options) {
686
+ return lazyStream(model, async () => {
687
+ const provider = this.requireProvider(model);
688
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
689
+ return provider.stream(requestModel, context, requestOptions);
690
+ });
691
+ }
692
+ async complete(model, context, options) {
693
+ return this.stream(model, context, options).result();
694
+ }
695
+ streamSimple(model, context, options) {
696
+ return lazyStream(model, async () => {
697
+ const provider = this.requireProvider(model);
698
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
699
+ return provider.streamSimple(requestModel, context, requestOptions);
700
+ });
701
+ }
702
+ async completeSimple(model, context, options) {
703
+ return this.streamSimple(model, context, options).result();
704
+ }
705
+ async fetchDeferred(model, handle, options) {
706
+ return lazyStream(model, async () => {
707
+ const provider = this.requireProvider(model);
708
+ if (!provider.fetchDeferred) {
709
+ throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
710
+ }
711
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
712
+ return provider.fetchDeferred(requestModel, handle, requestOptions);
713
+ }).result();
714
+ }
715
+ async cancelDeferred(model, handle, options) {
716
+ const provider = this.requireProvider(model);
717
+ if (!provider.cancelDeferred) {
718
+ throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
719
+ }
720
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
721
+ await provider.cancelDeferred(requestModel, handle, requestOptions);
722
+ }
723
+ };
724
+ function createModels(options) {
725
+ return new ModelsImpl(options);
726
+ }
727
+ function createProvider(input) {
728
+ const baselineModels = input.models;
729
+ let dynamicModels = [];
730
+ const fetchModels = input.fetchModels;
731
+ const currentModels = () => {
732
+ const merged = [...baselineModels];
733
+ for (const model of dynamicModels) {
734
+ const index = merged.findIndex((entry) => entry.id === model.id);
735
+ if (index >= 0)
736
+ merged[index] = model;
737
+ else
738
+ merged.push(model);
739
+ }
740
+ return merged;
741
+ };
742
+ const single = typeof input.api.stream === "function" ? input.api : void 0;
743
+ const byApi = single ? void 0 : input.api;
744
+ const apiFor = (model) => single ?? byApi?.[model.api];
745
+ const dispatch = (model, run) => {
746
+ const streams2 = apiFor(model);
747
+ if (!streams2) {
748
+ return lazyStream(model, async () => {
749
+ throw new ModelsError("stream", `Provider ${input.id} has no API implementation for "${model.api}"`);
750
+ });
751
+ }
752
+ return run(streams2);
753
+ };
754
+ const provider = {
755
+ id: input.id,
756
+ name: input.name ?? input.id,
757
+ baseUrl: input.baseUrl,
758
+ headers: input.headers,
759
+ auth: input.auth,
760
+ getModels: currentModels,
761
+ refreshModels: fetchModels ? async (context) => {
762
+ if (context.stored) {
763
+ const restored = context.stored.models.filter((model) => model.provider === input.id).map((model) => model);
764
+ if (!await context.publish({
765
+ update: () => {
766
+ dynamicModels = restored;
767
+ }
768
+ })) {
769
+ return;
770
+ }
771
+ }
772
+ if (!context.allowNetwork || context.signal.aborted)
773
+ return;
774
+ const refreshed = await fetchModels(context);
775
+ if (context.signal.aborted)
776
+ return;
777
+ await context.publish({
778
+ persist: { models: refreshed, checkedAt: Date.now() },
779
+ update: () => {
780
+ dynamicModels = refreshed;
781
+ }
782
+ });
783
+ } : void 0,
784
+ filterModels: input.filterModels,
785
+ stream: (model, context, options) => dispatch(model, (streams2) => streams2.stream(model, context, options)),
786
+ streamSimple: (model, context, options) => dispatch(model, (streams2) => streams2.streamSimple(model, context, options))
787
+ };
788
+ const streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== void 0);
789
+ if (streams.some((entry) => entry.fetchDeferred !== void 0)) {
790
+ provider.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
791
+ const implementation = apiFor(model);
792
+ if (!implementation?.fetchDeferred) {
793
+ throw new ModelsError("provider", `Provider ${input.id} does not support deferred responses for "${model.api}"`);
794
+ }
795
+ return implementation.fetchDeferred(model, handle, options);
796
+ });
797
+ }
798
+ if (streams.some((entry) => entry.cancelDeferred !== void 0)) {
799
+ provider.cancelDeferred = async (model, handle, options) => {
800
+ const implementation = apiFor(model);
801
+ if (!implementation?.cancelDeferred) {
802
+ throw new ModelsError("provider", `Provider ${input.id} cannot cancel deferred responses for "${model.api}"`);
803
+ }
804
+ await implementation.cancelDeferred(model, handle, options);
805
+ };
806
+ }
807
+ return provider;
808
+ }
809
+ function calculateCost(model, usage) {
810
+ const inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;
811
+ let rates = model.cost;
812
+ let matchedThreshold = -1;
813
+ for (const tier of model.cost.tiers ?? []) {
814
+ if (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {
815
+ rates = tier;
816
+ matchedThreshold = tier.inputTokensAbove;
817
+ }
818
+ }
819
+ const longWrite = usage.cacheWrite1h ?? 0;
820
+ const shortWrite = usage.cacheWrite - longWrite;
821
+ usage.cost.input = rates.input / 1e6 * usage.input;
822
+ usage.cost.output = rates.output / 1e6 * usage.output;
823
+ usage.cost.cacheRead = rates.cacheRead / 1e6 * usage.cacheRead;
824
+ usage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1e6;
825
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
826
+ return usage.cost;
827
+ }
828
+ var EXTENDED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
829
+ function getSupportedThinkingLevels(model) {
830
+ if (!model.reasoning)
831
+ return ["off"];
832
+ return EXTENDED_THINKING_LEVELS.filter((level) => {
833
+ const mapped = model.thinkingLevelMap?.[level];
834
+ if (mapped === null)
835
+ return false;
836
+ if (level === "xhigh" || level === "max")
837
+ return mapped !== void 0;
838
+ return true;
839
+ });
840
+ }
841
+ function clampThinkingLevel(model, level) {
842
+ const availableLevels = getSupportedThinkingLevels(model);
843
+ if (availableLevels.includes(level))
844
+ return level;
845
+ const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);
846
+ if (requestedIndex === -1)
847
+ return availableLevels[0] ?? "off";
848
+ for (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {
849
+ const candidate = EXTENDED_THINKING_LEVELS[i];
850
+ if (availableLevels.includes(candidate))
851
+ return candidate;
852
+ }
853
+ for (let i = requestedIndex - 1; i >= 0; i--) {
854
+ const candidate = EXTENDED_THINKING_LEVELS[i];
855
+ if (availableLevels.includes(candidate))
856
+ return candidate;
857
+ }
858
+ return availableLevels[0] ?? "off";
859
+ }
860
+
861
+ export {
862
+ lazyApi,
863
+ defaultProviderAuthContext,
864
+ createModels,
865
+ createProvider,
866
+ calculateCost,
867
+ clampThinkingLevel
868
+ };