@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.10

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 (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
@@ -0,0 +1,1445 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunk4UE5TCMQjs = require('./chunk-4UE5TCMQ.js');
4
+
5
+
6
+
7
+
8
+ var _chunkKVG7YCTSjs = require('./chunk-KVG7YCTS.js');
9
+
10
+
11
+ var _chunkR5U7XKVJjs = require('./chunk-R5U7XKVJ.js');
12
+
13
+ // src/llm.ts
14
+ var llm_exports = {};
15
+ _chunkR5U7XKVJjs.__export.call(void 0, llm_exports, {
16
+ ANTHROPIC_TOOL_NAMES: () => ANTHROPIC_TOOL_NAMES,
17
+ APIError: () => APIError,
18
+ AuthError: () => AuthError,
19
+ CapabilityNotSupportedError: () => CapabilityNotSupportedError,
20
+ DEFAULT_MAX_MEDIA_BYTES: () => DEFAULT_MAX_MEDIA_BYTES,
21
+ FallbackExhaustedError: () => FallbackExhaustedError,
22
+ GEMINI_TOOL_NAMES: () => GEMINI_TOOL_NAMES,
23
+ HTTPStatusError: () => HTTPStatusError,
24
+ KeyEndpointError: () => KeyEndpointError,
25
+ LLMError: () => LLMError,
26
+ MediaTooLargeError: () => MediaTooLargeError,
27
+ MediaURLRefusedError: () => MediaURLRefusedError,
28
+ MissingKeyError: () => MissingKeyError,
29
+ ModelError: () => ModelError,
30
+ OPENAI_TOOL_NAMES: () => OPENAI_TOOL_NAMES,
31
+ PermissionDeniedError: () => PermissionDeniedError,
32
+ ProviderNotFoundError: () => ProviderNotFoundError,
33
+ RateLimitError: () => RateLimitError,
34
+ ResponseTooLargeError: () => ResponseTooLargeError,
35
+ StreamTruncatedError: () => StreamTruncatedError,
36
+ TOOL_NAMES_PARAM: () => TOOL_NAMES_PARAM,
37
+ ToolNameError: () => ToolNameError,
38
+ ToolNames: () => ToolNames,
39
+ applyAPIKey: () => applyAPIKey,
40
+ checkKeyEndpoint: () => checkKeyEndpoint,
41
+ checkToolChoice: () => checkToolChoice,
42
+ checkToolLinkage: () => checkToolLinkage,
43
+ clearRegistry: () => clearRegistry,
44
+ createLLM: () => createLLM,
45
+ credentialsTrusted: () => credentialsTrusted,
46
+ declarationOf: () => declarationOf,
47
+ fileSource: () => fileSource,
48
+ inlineSource: () => inlineSource,
49
+ isFallbackable: () => isFallbackable,
50
+ isPublicAddress: () => isPublicAddress,
51
+ isValidToolName: () => isValidToolName,
52
+ loadConfig: () => loadConfig,
53
+ parseURI: () => parseURI,
54
+ redactURI: () => redactURI,
55
+ register: () => register,
56
+ requestStartedPayload: () => requestStartedPayload,
57
+ resolve: () => resolve2,
58
+ responseReceivedPayload: () => responseReceivedPayload,
59
+ sanitizeToolName: () => sanitizeToolName,
60
+ toolNameModeOf: () => toolNameModeOf,
61
+ urlSource: () => urlSource,
62
+ usageCost: () => usageCost
63
+ });
64
+ var _promises = require('fs/promises');
65
+ var _path = require('path');
66
+
67
+ // src/llm-error.ts
68
+ var LLMError = class extends Error {
69
+ constructor(message) {
70
+ super(message);
71
+ this.name = "LLMError";
72
+ Object.setPrototypeOf(this, new.target.prototype);
73
+ }
74
+ };
75
+
76
+ // src/llm-quote.ts
77
+ var ESCAPES = {
78
+ '"': '\\"',
79
+ "\\": "\\\\",
80
+ "\x07": "\\a",
81
+ "\b": "\\b",
82
+ "\f": "\\f",
83
+ "\n": "\\n",
84
+ "\r": "\\r",
85
+ " ": "\\t",
86
+ "\v": "\\v"
87
+ };
88
+ var PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;
89
+ function goQuote(s) {
90
+ let out = '"';
91
+ for (const ch of s) {
92
+ const esc = ESCAPES[ch];
93
+ if (esc !== void 0) {
94
+ out += esc;
95
+ continue;
96
+ }
97
+ const c = ch.codePointAt(0);
98
+ if (c >= 55296 && c <= 57343) {
99
+ out += "\uFFFD";
100
+ } else if (ch === " " || PRINTABLE.test(ch)) {
101
+ out += ch;
102
+ } else if (c < 32 || c === 127) {
103
+ out += "\\x" + c.toString(16).padStart(2, "0");
104
+ } else if (c < 65536) {
105
+ out += "\\u" + c.toString(16).padStart(4, "0");
106
+ } else {
107
+ out += "\\U" + c.toString(16).padStart(8, "0");
108
+ }
109
+ }
110
+ return out + '"';
111
+ }
112
+
113
+ // src/llm-errors.ts
114
+ var HTTPStatusError = class extends LLMError {
115
+ constructor(statusCode, status) {
116
+ super(`http ${statusCode}: ${status}`);
117
+ this.name = "HTTPStatusError";
118
+ this.statusCode = statusCode;
119
+ this.status = status;
120
+ }
121
+ };
122
+ var APIError = class extends LLMError {
123
+ constructor(provider, statusCode, type, message) {
124
+ super(message);
125
+ this.name = "APIError";
126
+ this.provider = provider;
127
+ this.statusCode = statusCode;
128
+ this.type = type;
129
+ }
130
+ };
131
+ var StreamTruncatedError = class extends LLMError {
132
+ constructor(provider) {
133
+ super(
134
+ `stream truncated (provider ${JSON.stringify(provider)}): ended before its final event`
135
+ );
136
+ this.name = "StreamTruncatedError";
137
+ this.provider = provider;
138
+ }
139
+ };
140
+ var ResponseTooLargeError = class extends LLMError {
141
+ constructor(provider, what, limit) {
142
+ super(
143
+ `response ${what} exceeds ${limit} bytes (provider ${JSON.stringify(provider)})`
144
+ );
145
+ this.name = "ResponseTooLargeError";
146
+ this.provider = provider;
147
+ this.what = what;
148
+ this.limit = limit;
149
+ }
150
+ };
151
+ var KeyEndpointError = class extends LLMError {
152
+ constructor(scheme, endpoint, opts = {}) {
153
+ super(keyEndpointMessage(scheme, endpoint, opts));
154
+ this.name = "KeyEndpointError";
155
+ this.scheme = scheme;
156
+ this.endpoint = endpoint;
157
+ this.insecure = _nullishCoalesce(opts.insecure, () => ( false));
158
+ this.malformed = _nullishCoalesce(opts.malformed, () => ( false));
159
+ }
160
+ };
161
+ function keyEndpointMessage(scheme, endpoint, opts) {
162
+ const q = goQuote(endpoint);
163
+ if (opts.malformed) {
164
+ return `llm: refusing to send the ${scheme} API key to ${q}: an endpoint must parse and carry no userinfo, backslash, percent-escape, whitespace or control character`;
165
+ }
166
+ if (opts.insecure) {
167
+ return `llm: refusing to send the ${scheme} API key over plain http to ${q}; use https or a loopback host`;
168
+ }
169
+ return `llm: refusing to send the ${scheme} API key to ${q}, which only the URI names; set it as llm.yaml base_url or LLM_BASE_URL, or pass api_key in the URI`;
170
+ }
171
+ var MissingKeyError = class extends LLMError {
172
+ constructor(scheme, model, envVars) {
173
+ const m = model !== "" ? ` (model ${goQuote(model)})` : "";
174
+ super(`llm: no API key for provider ${goQuote(scheme)}${m}: set ${envVars.join(" or ")}`);
175
+ this.name = "MissingKeyError";
176
+ this.scheme = scheme;
177
+ this.model = model;
178
+ this.envVars = envVars;
179
+ }
180
+ };
181
+
182
+ // src/llm-toolnames.ts
183
+ var _crypto = require('crypto');
184
+ var TOOL_NAMES_PARAM = "tool_names";
185
+ var ANTHROPIC_TOOL_NAMES = Object.freeze({
186
+ provider: "anthropic",
187
+ maxLen: 128,
188
+ extra: "",
189
+ leadLetter: false
190
+ });
191
+ var OPENAI_TOOL_NAMES = Object.freeze({
192
+ provider: "openai",
193
+ maxLen: 64,
194
+ extra: "",
195
+ leadLetter: false
196
+ });
197
+ var GEMINI_TOOL_NAMES = Object.freeze({
198
+ provider: "gemini",
199
+ maxLen: 128,
200
+ extra: ".:",
201
+ leadLetter: true
202
+ });
203
+ var ToolNameError = class extends LLMError {
204
+ constructor(provider, reason, toolName, other = "") {
205
+ super(toolNameMessage(provider, reason, toolName, other));
206
+ this.name = "ToolNameError";
207
+ this.provider = provider;
208
+ this.reason = reason;
209
+ this.toolName = toolName;
210
+ this.other = other;
211
+ }
212
+ };
213
+ function toolNameMessage(provider, reason, name, other) {
214
+ const q = JSON.stringify;
215
+ switch (reason) {
216
+ case "empty":
217
+ return `tool name is empty (provider ${q(provider)})`;
218
+ case "invalid_utf8":
219
+ return `tool name ${q(name)} is not valid UTF-8 (provider ${q(provider)})`;
220
+ case "invalid":
221
+ return `tool name ${q(name)} is not valid for provider ${q(provider)}`;
222
+ case "duplicate":
223
+ return `tool name ${q(name)} is defined twice (provider ${q(provider)})`;
224
+ case "collision":
225
+ return `tool names ${q(other)} and ${q(name)} map to the same provider name (provider ${q(provider)})`;
226
+ }
227
+ }
228
+ function toolNameModeOf(params) {
229
+ const v = _optionalChain([params, 'optionalAccess', _ => _[TOOL_NAMES_PARAM]]);
230
+ if (v === void 0) return "sanitize";
231
+ const m = v.trim();
232
+ if (m === "sanitize" || m === "strict") return m;
233
+ throw new LLMError(
234
+ `${TOOL_NAMES_PARAM} must be "sanitize" or "strict", got ${JSON.stringify(v)}`
235
+ );
236
+ }
237
+ var HASH_LEN = 8;
238
+ var UNDERSCORE = 95;
239
+ var encoder = new TextEncoder();
240
+ var decoder = new TextDecoder();
241
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
242
+ function isAlnum(c) {
243
+ return c >= 97 && c <= 122 || c >= 65 && c <= 90 || c >= 48 && c <= 57;
244
+ }
245
+ function allowed(rule, c) {
246
+ if (isAlnum(c) || c === UNDERSCORE || c === 45) return true;
247
+ return c < 128 && rule.extra.includes(String.fromCharCode(c));
248
+ }
249
+ function leadOK(rule, c) {
250
+ if (!rule.leadLetter) return true;
251
+ return c === UNDERSCORE || c >= 97 && c <= 122 || c >= 65 && c <= 90;
252
+ }
253
+ function validBytes(rule, b) {
254
+ if (b.length === 0 || b.length > rule.maxLen || !leadOK(rule, b[0])) {
255
+ return false;
256
+ }
257
+ for (const c of b) if (!allowed(rule, c)) return false;
258
+ return true;
259
+ }
260
+ function ascii(b) {
261
+ return decoder.decode(Uint8Array.from(b));
262
+ }
263
+ function isValidToolName(rule, name) {
264
+ if (LONE_SURROGATE.test(name)) return false;
265
+ return validBytes(rule, encoder.encode(name));
266
+ }
267
+ function sanitizeToolName(rule, name) {
268
+ if (name === "") throw new ToolNameError(rule.provider, "empty", name);
269
+ if (LONE_SURROGATE.test(name)) {
270
+ throw new ToolNameError(rule.provider, "invalid_utf8", name);
271
+ }
272
+ const src = encoder.encode(name);
273
+ if (validBytes(rule, src)) return name;
274
+ const out = [];
275
+ let run = false;
276
+ for (const c of src) {
277
+ if (allowed(rule, c)) {
278
+ out.push(c);
279
+ run = false;
280
+ continue;
281
+ }
282
+ if (!run) out.push(UNDERSCORE);
283
+ run = true;
284
+ }
285
+ if (!leadOK(rule, out[0])) out.unshift(UNDERSCORE);
286
+ if (out.length <= rule.maxLen && out.some(isAlnum)) return ascii(out);
287
+ const hash = _crypto.createHash.call(void 0, "sha256").update(src).digest("hex").slice(0, HASH_LEN);
288
+ const keep = Math.min(out.length, rule.maxLen - HASH_LEN - 1);
289
+ return `${ascii(out.slice(0, keep))}_${hash}`;
290
+ }
291
+ var ToolNames = class _ToolNames {
292
+ constructor(rule, mode) {
293
+ this.rule = rule;
294
+ this.mode = mode;
295
+ this.toWire = /* @__PURE__ */ new Map();
296
+ this.toOrig = /* @__PURE__ */ new Map();
297
+ }
298
+ /**
299
+ * Checks `defs` against `rule` and builds their mapping. The first
300
+ * failing def, in order, throws a {@link ToolNameError}: `empty`,
301
+ * `invalid_utf8`, `invalid` (strict only), `duplicate`, `collision`
302
+ * (`other` names the earlier def with the same wire name).
303
+ */
304
+ static build(rule, mode, defs) {
305
+ const t = new _ToolNames(rule, mode);
306
+ for (const { name } of defs) {
307
+ let wire;
308
+ if (name === "") {
309
+ throw new ToolNameError(rule.provider, "empty", name);
310
+ } else if (LONE_SURROGATE.test(name)) {
311
+ throw new ToolNameError(rule.provider, "invalid_utf8", name);
312
+ } else if (mode === "strict") {
313
+ if (!isValidToolName(rule, name)) {
314
+ throw new ToolNameError(rule.provider, "invalid", name);
315
+ }
316
+ wire = name;
317
+ } else {
318
+ wire = sanitizeToolName(rule, name);
319
+ }
320
+ if (t.toWire.has(name)) {
321
+ throw new ToolNameError(rule.provider, "duplicate", name);
322
+ }
323
+ const other = t.toOrig.get(wire);
324
+ if (other !== void 0) {
325
+ throw new ToolNameError(rule.provider, "collision", name, other);
326
+ }
327
+ t.toWire.set(name, wire);
328
+ t.toOrig.set(wire, name);
329
+ }
330
+ return t;
331
+ }
332
+ /**
333
+ * The name to send: a def's wire name; otherwise, as for a call
334
+ * replayed from history, `name` sanitized (`sanitize`) or unchanged
335
+ * (`strict`, or a name the sanitizer refuses).
336
+ */
337
+ wire(name) {
338
+ const w = this.toWire.get(name);
339
+ if (w !== void 0) return w;
340
+ if (this.mode === "strict") return name;
341
+ try {
342
+ return sanitizeToolName(this.rule, name);
343
+ } catch (e2) {
344
+ return name;
345
+ }
346
+ }
347
+ /** The def name a returned wire name stands for; unknown names pass through. */
348
+ original(wire) {
349
+ return _nullishCoalesce(this.toOrig.get(wire), () => ( wire));
350
+ }
351
+ /** `defs` with each name replaced by its wire name; input untouched. */
352
+ defs(defs) {
353
+ return defs.map((d) => ({ ...d, name: this.wire(d.name) }));
354
+ }
355
+ /** `calls` with each name replaced by its original; input untouched. */
356
+ calls(calls) {
357
+ return calls.map((c) => ({ ...c, name: this.original(c.name) }));
358
+ }
359
+ };
360
+
361
+ // src/llm-media.ts
362
+ var _dns = require('dns'); var dns = _interopRequireWildcard(_dns);
363
+ var _http = require('http'); var http = _interopRequireWildcard(_http);
364
+ var _https = require('https'); var https = _interopRequireWildcard(_https);
365
+ var _net = require('net');
366
+ var DEFAULT_MAX_MEDIA_BYTES = 32 << 20;
367
+ var TIMEOUT_MS = 3e4;
368
+ var MediaURLRefusedError = class extends LLMError {
369
+ constructor(destination, reason) {
370
+ super(`media: refusing to fetch ${destination}: ${reason}`);
371
+ this.name = "MediaURLRefusedError";
372
+ this.destination = destination;
373
+ this.reason = reason;
374
+ }
375
+ };
376
+ var MediaTooLargeError = class extends LLMError {
377
+ constructor(size, limit, provider) {
378
+ super(`media too large (${size} bytes, limit ${limit}) for provider ${JSON.stringify(provider)}`);
379
+ this.name = "MediaTooLargeError";
380
+ this.size = size;
381
+ this.limit = limit;
382
+ this.provider = provider;
383
+ }
384
+ };
385
+ function prefix(cidr) {
386
+ const [addr, bits] = cidr.split("/");
387
+ const bytes2 = addressBytes(addr);
388
+ if (!bytes2) throw new Error(`bad prefix ${cidr}`);
389
+ return { bytes: bytes2, bits: Number(bits) };
390
+ }
391
+ var NON_PUBLIC_V4 = [
392
+ "0.0.0.0/8",
393
+ "10.0.0.0/8",
394
+ "100.64.0.0/10",
395
+ "127.0.0.0/8",
396
+ "169.254.0.0/16",
397
+ "172.16.0.0/12",
398
+ "192.0.0.0/24",
399
+ "192.0.2.0/24",
400
+ "192.168.0.0/16",
401
+ "198.18.0.0/15",
402
+ "198.51.100.0/24",
403
+ "203.0.113.0/24",
404
+ "224.0.0.0/4",
405
+ "240.0.0.0/4"
406
+ ].map(prefix);
407
+ var NON_PUBLIC_V6 = [
408
+ "::/96",
409
+ "64:ff9b:1::/48",
410
+ "100::/64",
411
+ "2001::/23",
412
+ "2001:db8::/32",
413
+ "2002::/16",
414
+ "3fff::/20",
415
+ "5f00::/16",
416
+ "fc00::/7",
417
+ "fe80::/10",
418
+ "fec0::/10",
419
+ "ff00::/8"
420
+ ].map(prefix);
421
+ var MAPPED = prefix("::ffff:0:0/96");
422
+ var NAT64 = prefix("64:ff9b::/96");
423
+ function contains(p, b) {
424
+ if (p.bytes.length !== b.length) return false;
425
+ let bits = p.bits;
426
+ for (let i = 0; bits > 0; i++, bits -= 8) {
427
+ const mask = bits >= 8 ? 255 : 255 << 8 - bits & 255;
428
+ if ((p.bytes[i] & mask) !== (b[i] & mask)) return false;
429
+ }
430
+ return true;
431
+ }
432
+ function addressBytes(addr) {
433
+ const a = addr.replace(/%.*$/, "");
434
+ const kind = _net.isIP.call(void 0, a);
435
+ if (kind === 4) return a.split(".").map(Number);
436
+ if (kind !== 6) return void 0;
437
+ const canon = new URL(`http://[${a}]/`).hostname.slice(1, -1);
438
+ const [head, tail] = canon.includes("::") ? canon.split("::") : [canon, void 0];
439
+ const h = head ? head.split(":") : [];
440
+ const t = tail ? tail.split(":") : [];
441
+ const groups = tail === void 0 ? h : [...h, ...Array(8 - h.length - t.length).fill("0"), ...t];
442
+ return groups.flatMap((g) => {
443
+ const n = parseInt(g, 16);
444
+ return [n >> 8, n & 255];
445
+ });
446
+ }
447
+ function isPublicAddress(addr) {
448
+ let b = addressBytes(addr);
449
+ if (!b) return false;
450
+ if (b.length === 16 && (contains(MAPPED, b) || contains(NAT64, b))) b = b.slice(12);
451
+ if (b.length === 4) {
452
+ if (b.every((x) => x === 255)) return false;
453
+ return !NON_PUBLIC_V4.some((p) => contains(p, b));
454
+ }
455
+ return !NON_PUBLIC_V6.some((p) => contains(p, b));
456
+ }
457
+ var systemResolver = async (host) => (await dns.promises.lookup(host, { all: true, verbatim: true })).map((a) => a.address);
458
+ var addressAllowed = isPublicAddress;
459
+ var resolve = systemResolver;
460
+ function mediaDestination(url) {
461
+ let u;
462
+ try {
463
+ u = new URL(url);
464
+ } catch (e3) {
465
+ return "<unparseable URL>";
466
+ }
467
+ if (u.host === "" && !u.pathname.startsWith("/")) return u.protocol;
468
+ return `${u.protocol}//${u.host}${u.pathname}`;
469
+ }
470
+ async function vettedAddresses(dest, host) {
471
+ const literal = _net.isIP.call(void 0, host.replace(/%.*$/, ""));
472
+ const addrs = literal ? [host] : await resolve(host);
473
+ if (addrs.length === 0) throw new MediaURLRefusedError(dest, "host resolves to no address");
474
+ for (const a of addrs) {
475
+ if (!addressAllowed(a)) throw new MediaURLRefusedError(dest, `non-public address ${a}`);
476
+ }
477
+ return addrs.map((a) => ({ address: a, family: _net.isIP.call(void 0, a.replace(/%.*$/, "")) }));
478
+ }
479
+ async function fetchMedia(url, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
480
+ const dest = mediaDestination(url);
481
+ let u;
482
+ try {
483
+ u = new URL(url);
484
+ } catch (e4) {
485
+ throw new MediaURLRefusedError(dest, "URL does not parse");
486
+ }
487
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
488
+ throw new MediaURLRefusedError(dest, "only http or https URLs are fetched");
489
+ }
490
+ if (u.username !== "" || u.password !== "") throw new MediaURLRefusedError(dest, "URL carries userinfo");
491
+ const host = u.hostname.replace(/^\[(.*)\]$/, "$1");
492
+ if (host === "") throw new MediaURLRefusedError(dest, "URL has no host");
493
+ if (_chunkKVG7YCTSjs.isOffline.call(void 0, ) && !_chunkKVG7YCTSjs.isLoopback.call(void 0, host)) throw new (0, _chunkKVG7YCTSjs.OfflineError)("GET", url);
494
+ const addrs = await vettedAddresses(dest, host);
495
+ const lookup = (_hostname, options, cb) => {
496
+ const fam = typeof options === "object" ? options.family : void 0;
497
+ const pick = addrs.filter((a) => !fam || a.family === fam);
498
+ if (pick.length === 0) {
499
+ cb(Object.assign(new Error(`no ${fam === 6 ? "IPv6" : "IPv4"} address`), { code: "ENOTFOUND" }), "", 0);
500
+ return;
501
+ }
502
+ if (typeof options === "object" && options.all) {
503
+ cb(null, pick);
504
+ } else {
505
+ cb(null, pick[0].address, pick[0].family);
506
+ }
507
+ };
508
+ const mod = u.protocol === "https:" ? https : http;
509
+ return await new Promise((resolveBody, reject) => {
510
+ const req = mod.request(
511
+ u,
512
+ {
513
+ method: "GET",
514
+ headers: { accept: "*/*" },
515
+ lookup,
516
+ agent: false,
517
+ timeout: TIMEOUT_MS
518
+ },
519
+ (res) => {
520
+ const status = _nullishCoalesce(res.statusCode, () => ( 0));
521
+ const fail = (err) => {
522
+ res.destroy();
523
+ reject(err);
524
+ };
525
+ if (status >= 300 && status < 400) {
526
+ fail(new HTTPStatusError(status, `media: redirect not followed (${dest})`));
527
+ return;
528
+ }
529
+ if (status < 200 || status >= 300) {
530
+ fail(new LLMError(`media: fetch ${dest}: http ${status}`));
531
+ return;
532
+ }
533
+ const declared = Number(res.headers["content-length"]);
534
+ if (Number.isFinite(declared) && declared > maxBytes) {
535
+ fail(new MediaTooLargeError(declared, maxBytes, "media"));
536
+ return;
537
+ }
538
+ const chunks = [];
539
+ let n = 0;
540
+ res.on("data", (c) => {
541
+ n += c.length;
542
+ if (n > maxBytes) {
543
+ fail(new MediaTooLargeError(n, maxBytes, "media"));
544
+ return;
545
+ }
546
+ chunks.push(c);
547
+ });
548
+ res.on("end", () => resolveBody(new Uint8Array(Buffer.concat(chunks))));
549
+ res.on("error", (e) => reject(new LLMError(`media: fetch ${dest}: ${e.message}`)));
550
+ }
551
+ );
552
+ const deadline = setTimeout(() => req.destroy(new Error("timeout")), TIMEOUT_MS);
553
+ req.on("close", () => clearTimeout(deadline));
554
+ req.on("timeout", () => req.destroy(new Error("timeout")));
555
+ req.on("error", (e) => reject(e instanceof LLMError ? e : new LLMError(`media: fetch ${dest}: ${e.message}`)));
556
+ req.end();
557
+ });
558
+ }
559
+
560
+ // src/llm-file.ts
561
+ var _fs = require('fs');
562
+
563
+ var _jsyaml = require('js-yaml'); var yaml = _interopRequireWildcard(_jsyaml);
564
+ var EMPTY = { default: "", fallback: [], providers: /* @__PURE__ */ new Map() };
565
+ var FIELDS = /* @__PURE__ */ new Set(["api_key", "api_key_env", "base_url", "model"]);
566
+ function readLLMFile() {
567
+ let text;
568
+ try {
569
+ text = _fs.readFileSync.call(void 0, _path.join.call(void 0, _chunk4UE5TCMQjs.configDir.call(void 0, "hop"), "llm.yaml"), "utf8");
570
+ } catch (e5) {
571
+ return emptyFile();
572
+ }
573
+ try {
574
+ return decode(
575
+ yaml.load(text, { schema: yaml.FAILSAFE_SCHEMA }),
576
+ yaml.load(text, { schema: yaml.CORE_SCHEMA })
577
+ );
578
+ } catch (e6) {
579
+ return emptyFile();
580
+ }
581
+ }
582
+ function providerBlock(file, scheme) {
583
+ return file.providers.get(scheme);
584
+ }
585
+ function emptyFile() {
586
+ return { ...EMPTY, fallback: [], providers: /* @__PURE__ */ new Map() };
587
+ }
588
+ var Shape = class extends Error {
589
+ };
590
+ function isMap(v) {
591
+ return typeof v === "object" && v !== null && !Array.isArray(v);
592
+ }
593
+ function str(v) {
594
+ if (v === void 0 || v === null) return "";
595
+ if (typeof v !== "string") throw new Shape();
596
+ return v;
597
+ }
598
+ function decode(raw, typed) {
599
+ if (raw === void 0 || raw === null) return emptyFile();
600
+ if (!isMap(raw)) throw new Shape();
601
+ const t = isMap(typed) ? typed : {};
602
+ const out = emptyFile();
603
+ out.default = str(raw["default"]);
604
+ const fb = raw["fallback"];
605
+ if (fb !== void 0 && fb !== null) {
606
+ if (!Array.isArray(fb)) throw new Shape();
607
+ out.fallback = fb.map(str);
608
+ }
609
+ const ps = raw["providers"];
610
+ if (ps === void 0 || ps === null) return out;
611
+ if (!isMap(ps)) throw new Shape();
612
+ const tps = isMap(t["providers"]) ? t["providers"] : {};
613
+ for (const [name, block] of Object.entries(ps)) {
614
+ const b = block === null ? {} : block;
615
+ if (!isMap(b)) throw new Shape();
616
+ const tb = isMap(tps[name]) ? tps[name] : {};
617
+ const extras = {};
618
+ for (const k of Object.keys(b)) {
619
+ if (!FIELDS.has(k) && k !== "__proto__") extras[k] = tb[k];
620
+ }
621
+ out.providers.set(name, {
622
+ apiKey: str(b["api_key"]),
623
+ apiKeyEnv: str(b["api_key_env"]),
624
+ baseURL: str(b["base_url"]),
625
+ model: str(b["model"]),
626
+ extras
627
+ });
628
+ }
629
+ return out;
630
+ }
631
+
632
+ // src/llm-endpoint.ts
633
+ var REDACTED = "REDACTED";
634
+ function redactURI(raw) {
635
+ let out = "";
636
+ for (; ; ) {
637
+ const m = /[?&]/.exec(raw);
638
+ if (!m) return out + redactSegment(raw);
639
+ out += redactSegment(raw.slice(0, m.index)) + m[0];
640
+ raw = raw.slice(m.index + 1);
641
+ }
642
+ }
643
+ function redactSegment(seg) {
644
+ const eq = seg.indexOf("=");
645
+ if (eq < 0) return redactUserinfo(seg, false);
646
+ const k = seg.slice(0, eq);
647
+ const v = seg.slice(eq + 1);
648
+ if (k.includes("://")) return redactUserinfo(seg, false);
649
+ if (credentialParam(k)) return v === "" ? seg : `${k}=${REDACTED}`;
650
+ return `${k}=${redactUserinfo(v, true)}`;
651
+ }
652
+ function redactUserinfo(s, strict) {
653
+ let start = 0;
654
+ let scheme = "";
655
+ const i = s.indexOf("://");
656
+ if (i >= 0) {
657
+ start = i + 3;
658
+ scheme = s.slice(0, i).toLowerCase();
659
+ }
660
+ const rest = s.slice(start);
661
+ let end = rest.indexOf("/");
662
+ const hasPath = end >= 0;
663
+ if (!hasPath) end = rest.length;
664
+ const at = rest.slice(0, end).lastIndexOf("@");
665
+ if (at <= 0) return s;
666
+ const credential = strict || scheme === "http" || scheme === "https" || hasPath && start > 0 || rest.slice(0, at).includes(":");
667
+ if (!credential) return s;
668
+ return s.slice(0, start) + REDACTED + rest.slice(at);
669
+ }
670
+ var CREDENTIAL_NAMES = /* @__PURE__ */ new Set([
671
+ "key",
672
+ "apikey",
673
+ "token",
674
+ "secret",
675
+ "password",
676
+ "passwd",
677
+ "pwd",
678
+ "auth",
679
+ "authorization",
680
+ "signature",
681
+ "sig",
682
+ "credential",
683
+ "credentials"
684
+ ]);
685
+ var CREDENTIAL_SUFFIXES = [
686
+ "_key",
687
+ "apikey",
688
+ "_token",
689
+ "_secret",
690
+ "_password",
691
+ "_signature",
692
+ "_credential",
693
+ "_credentials"
694
+ ];
695
+ function credentialParam(name) {
696
+ try {
697
+ name = decodeURIComponent(name.replace(/\+/g, " "));
698
+ } catch (e7) {
699
+ }
700
+ name = name.trim().toLowerCase().replace(/-/g, "_");
701
+ if (CREDENTIAL_NAMES.has(name)) return true;
702
+ return CREDENTIAL_SUFFIXES.some((s) => name.endsWith(s));
703
+ }
704
+ function scrubSecrets(msg, secrets) {
705
+ for (const s of secrets) {
706
+ if (s.trim() !== "") msg = msg.split(s).join(REDACTED);
707
+ }
708
+ return msg;
709
+ }
710
+ function parseEndpoint(raw) {
711
+ if (/[\\%]/.test(raw) || /[\u0000- \u007f\s]/.test(raw)) {
712
+ return void 0;
713
+ }
714
+ let u;
715
+ try {
716
+ u = new URL(raw);
717
+ } catch (e8) {
718
+ return void 0;
719
+ }
720
+ const authority = _nullishCoalesce(raw.slice(raw.indexOf("//") + 2).split(/[/?#]/)[0], () => ( ""));
721
+ if (!u.host || !u.hostname || u.username || u.password || authority.includes("@")) {
722
+ return void 0;
723
+ }
724
+ const scheme = u.protocol.replace(/:$/, "").toLowerCase();
725
+ let port = u.port;
726
+ if (port === "") {
727
+ if (scheme === "https") port = "443";
728
+ else if (scheme === "http") port = "80";
729
+ }
730
+ return { scheme, host: u.hostname.toLowerCase(), port };
731
+ }
732
+ function origin(e) {
733
+ return `${e.scheme}://${e.host}:${e.port}`;
734
+ }
735
+ function blankKey(key) {
736
+ return (_nullishCoalesce(key, () => ( ""))).trim() === "";
737
+ }
738
+ function checkKeyEndpoint(scheme, key, baseURL) {
739
+ if (blankKey(key) || baseURL === "") return;
740
+ const e = parseEndpoint(baseURL);
741
+ if (!e) {
742
+ throw new KeyEndpointError(scheme, redactURI(baseURL), { malformed: true });
743
+ }
744
+ if (e.scheme === "http" && !_chunkKVG7YCTSjs.isLoopback.call(void 0, e.host)) {
745
+ throw new KeyEndpointError(scheme, redactURI(baseURL), { insecure: true });
746
+ }
747
+ }
748
+ var declarations = /* @__PURE__ */ new Map();
749
+ var registered = /* @__PURE__ */ new Set();
750
+ function setDeclaration(scheme, decl) {
751
+ registered.add(scheme);
752
+ if (decl) declarations.set(scheme, decl);
753
+ }
754
+ function clearDeclarations() {
755
+ declarations.clear();
756
+ registered.clear();
757
+ }
758
+ function declarationOf(scheme) {
759
+ return declarations.get(scheme);
760
+ }
761
+ function isRegistered(scheme) {
762
+ return registered.has(scheme);
763
+ }
764
+ function credentialsTrusted(scheme, baseURL, ...extra) {
765
+ return trustedOrigin(scheme, baseURL, extra, true);
766
+ }
767
+ function trustedOrigin(scheme, baseURL, extra, ambient) {
768
+ const e = parseEndpoint(baseURL);
769
+ if (!e) return false;
770
+ if (_chunkKVG7YCTSjs.isLoopback.call(void 0, e.host)) return true;
771
+ const trusted = [..._nullishCoalesce(_optionalChain([declarations, 'access', _2 => _2.get, 'call', _3 => _3(scheme), 'optionalAccess', _4 => _4.endpoints]), () => ( [])), ...extra];
772
+ if (ambient) {
773
+ const file = _optionalChain([providerBlock, 'call', _5 => _5(readLLMFile(), scheme), 'optionalAccess', _6 => _6.baseURL]);
774
+ if (file) trusted.push(file);
775
+ const env = process.env["LLM_BASE_URL"];
776
+ if (env) trusted.push(env);
777
+ }
778
+ return trusted.some((t) => {
779
+ const te = t ? parseEndpoint(t) : void 0;
780
+ return te !== void 0 && origin(te) === origin(e);
781
+ });
782
+ }
783
+
784
+ // src/llm-uri.ts
785
+ function parseURI(raw) {
786
+ if (raw === "") throw new LLMError("empty URI");
787
+ const idx = raw.indexOf("://");
788
+ if (idx < 0) throw new LLMError(`missing scheme in URI ${goQuote(redactURI(raw))}`);
789
+ const scheme = raw.slice(0, idx);
790
+ if (scheme === "") throw new LLMError(`empty scheme in URI ${goQuote(redactURI(raw))}`);
791
+ let rest = raw.slice(idx + 3);
792
+ let params;
793
+ const q = rest.indexOf("?");
794
+ if (q >= 0) {
795
+ params = parseQuery(rest.slice(q + 1));
796
+ rest = rest.slice(0, q);
797
+ }
798
+ let host = "";
799
+ let model = rest;
800
+ const slash = rest.indexOf("/");
801
+ if (slash > 0) {
802
+ const hp = splitHostPort(rest.slice(0, slash));
803
+ if (hp && hp[1] !== "") {
804
+ host = joinHostPort(hp[0], hp[1]);
805
+ model = rest.slice(slash + 1);
806
+ }
807
+ }
808
+ const uri = { scheme, model };
809
+ if (host !== "") uri.host = host;
810
+ if (params && Object.keys(params).length > 0) uri.params = params;
811
+ return uri;
812
+ }
813
+ function parseQuery(qs) {
814
+ if (qs === "") return void 0;
815
+ const m = {};
816
+ for (const pair of qs.split("&")) {
817
+ const eq = pair.indexOf("=");
818
+ const k = eq < 0 ? pair : pair.slice(0, eq);
819
+ const v = eq < 0 ? "" : pair.slice(eq + 1);
820
+ if (k === "") continue;
821
+ Object.defineProperty(m, k, { value: v, enumerable: true, writable: true, configurable: true });
822
+ }
823
+ return m;
824
+ }
825
+ function splitHostPort(hp) {
826
+ const i = hp.lastIndexOf(":");
827
+ if (i < 0) return void 0;
828
+ let host;
829
+ let j = 0;
830
+ let k = 0;
831
+ if (hp.startsWith("[")) {
832
+ const end = hp.indexOf("]");
833
+ if (end < 0 || end + 1 !== i) return void 0;
834
+ host = hp.slice(1, end);
835
+ j = 1;
836
+ k = end + 1;
837
+ } else {
838
+ host = hp.slice(0, i);
839
+ if (host.includes(":")) return void 0;
840
+ }
841
+ if (hp.slice(j).includes("[") || hp.slice(k).includes("]")) return void 0;
842
+ return [host, hp.slice(i + 1)];
843
+ }
844
+ function joinHostPort(host, port) {
845
+ return host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
846
+ }
847
+
848
+ // src/llm-keys.ts
849
+ var FALLBACK_ENV_KEY = "LLM_API_KEY";
850
+ function envKeyName(scheme) {
851
+ return `${scheme.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_API_KEY`;
852
+ }
853
+ function uriKey(u) {
854
+ const v = _optionalChain([u, 'access', _7 => _7.params, 'optionalAccess', _8 => _8["api_key"]]);
855
+ return v !== void 0 && !blankKey(v) ? v : void 0;
856
+ }
857
+ function resolveKey(u, file) {
858
+ const own = uriKey(u);
859
+ if (own !== void 0) return { value: own, source: "uri" };
860
+ const block = providerBlock(file, u.scheme);
861
+ if (block && !blankKey(block.apiKey)) return { value: block.apiKey, source: "config" };
862
+ const known = isRegistered(u.scheme);
863
+ const decl = _optionalChain([declarationOf, 'call', _9 => _9(u.scheme), 'optionalAccess', _10 => _10.key]);
864
+ let names = known ? [..._nullishCoalesce(_optionalChain([decl, 'optionalAccess', _11 => _11.envVars]), () => ( [envKeyName(u.scheme)]))] : [];
865
+ if (block && !blankKey(block.apiKeyEnv)) {
866
+ names = [block.apiKeyEnv, ...names.filter((n) => n !== block.apiKeyEnv)];
867
+ }
868
+ if (names.length === 0) return { value: "", source: "" };
869
+ for (const n of names) {
870
+ const v = process.env[n];
871
+ if (v !== void 0 && !blankKey(v)) return { value: v, source: "env" };
872
+ }
873
+ const required = known && _optionalChain([decl, 'optionalAccess', _12 => _12.optional]) !== true;
874
+ if (!required) return { value: "", source: "" };
875
+ const fb = process.env[FALLBACK_ENV_KEY];
876
+ if (fb !== void 0 && !blankKey(fb)) return { value: fb, source: "fallback" };
877
+ return {
878
+ value: "",
879
+ source: "",
880
+ missing: new MissingKeyError(u.scheme, u.model, [...names, FALLBACK_ENV_KEY])
881
+ };
882
+ }
883
+ function uriEndpoint(u) {
884
+ const b = _optionalChain([u, 'access', _13 => _13.params, 'optionalAccess', _14 => _14["base_url"]]);
885
+ if (b) return b;
886
+ return u.host ? `http://${u.host}` : "";
887
+ }
888
+ function guardKeyEndpoint(u, key, source) {
889
+ const endpoint = uriEndpoint(u);
890
+ if (blankKey(key) || endpoint === "") return;
891
+ checkKeyEndpoint(u.scheme, key, endpoint);
892
+ if (source === "uri") return;
893
+ if (!trustedOrigin(u.scheme, endpoint, [], true)) {
894
+ throw new KeyEndpointError(u.scheme, redactURI(endpoint));
895
+ }
896
+ }
897
+ function dropBlankURIKey(u) {
898
+ const v = _optionalChain([u, 'access', _15 => _15.params, 'optionalAccess', _16 => _16["api_key"]]);
899
+ if (v === void 0 || !blankKey(v)) return;
900
+ delete u.params["api_key"];
901
+ if (Object.keys(u.params).length === 0) delete u.params;
902
+ }
903
+ function stripURIParam(raw, name) {
904
+ const s = raw.indexOf("://");
905
+ if (s < 0) return raw;
906
+ const q = raw.indexOf("?", s + 3);
907
+ if (q < 0) return raw;
908
+ const kept = raw.slice(q + 1).split("&").filter((p) => p.split("=", 1)[0] !== name);
909
+ return kept.length === 0 ? raw.slice(0, q) : `${raw.slice(0, q + 1)}${kept.join("&")}`;
910
+ }
911
+ function applyAPIKey(uri) {
912
+ let parsed;
913
+ try {
914
+ parsed = parseURI(uri);
915
+ } catch (e9) {
916
+ throw new LLMError("llm: apply API key: provider URI must be scheme://model");
917
+ }
918
+ const named = _optionalChain([parsed, 'access', _17 => _17.params, 'optionalAccess', _18 => _18["api_key"]]);
919
+ if (named !== void 0 && blankKey(named)) {
920
+ uri = stripURIParam(uri, "api_key");
921
+ dropBlankURIKey(parsed);
922
+ }
923
+ const key = resolveKey(parsed, readLLMFile());
924
+ if (key.missing) throw key.missing;
925
+ guardKeyEndpoint(parsed, key.value, key.source);
926
+ if (key.source === "uri" || key.value === "") return uri;
927
+ if (/[&?#]/.test(key.value)) {
928
+ throw new LLMError(
929
+ `llm: ${parsed.scheme} API key contains a character a provider URI cannot carry (& ? #)`
930
+ );
931
+ }
932
+ return `${uri}${uri.includes("?") ? "&" : "?"}api_key=${key.value}`;
933
+ }
934
+
935
+ // src/llm-config.ts
936
+ function loadConfig(uriStr, opts = {}) {
937
+ if (opts.hermetic === true) return hermeticConfig(uriStr);
938
+ const file = readLLMFile();
939
+ const effective = uriStr || process.env["LLM_PROVIDER"] || file.default;
940
+ if (!effective) {
941
+ throw new LLMError(
942
+ "no LLM URI provided: LLM_PROVIDER is not set and llm.yaml names no default"
943
+ );
944
+ }
945
+ const uri = parseURI(effective);
946
+ dropBlankURIKey(uri);
947
+ const block = providerBlock(file, uri.scheme);
948
+ const key = resolveKey(uri, file);
949
+ guardKeyEndpoint(uri, key.value, key.source);
950
+ const provider = { model: uri.model || _optionalChain([block, 'optionalAccess', _19 => _19.model]) || "" };
951
+ if (uri.params) provider.params = { ...uri.params };
952
+ if (block && Object.keys(block.extras).length > 0) provider.extras = block.extras;
953
+ if (key.value !== "") provider.apiKey = key.value;
954
+ let base = process.env["LLM_BASE_URL"] || _optionalChain([block, 'optionalAccess', _20 => _20.baseURL]) || "";
955
+ if (uri.host) base = `http://${uri.host}`;
956
+ if (uri.params && "base_url" in uri.params) base = uri.params["base_url"];
957
+ if (base !== "") provider.baseURL = base;
958
+ checkKeyEndpoint(uri.scheme, key.value, base);
959
+ const fbEnv = process.env["LLM_FALLBACK"];
960
+ const fallbacks = fbEnv ? fbEnv.split(",").map((s) => s.trim()).filter(Boolean) : [...file.fallback];
961
+ return { uri, provider, fallbacks };
962
+ }
963
+ function hermeticConfig(uriStr) {
964
+ if (!uriStr) {
965
+ throw new LLMError("no LLM URI provided (hermetic: LLM_PROVIDER is not read)");
966
+ }
967
+ const uri = parseURI(uriStr);
968
+ dropBlankURIKey(uri);
969
+ const provider = { model: uri.model };
970
+ if (uri.params) provider.params = { ...uri.params };
971
+ const key = _nullishCoalesce(uriKey(uri), () => ( ""));
972
+ if (key !== "") provider.apiKey = key;
973
+ let base = uri.host ? `http://${uri.host}` : "";
974
+ if (uri.params && "base_url" in uri.params) base = uri.params["base_url"];
975
+ if (base !== "") provider.baseURL = base;
976
+ checkKeyEndpoint(uri.scheme, key, base);
977
+ return { uri, provider, fallbacks: [], hermetic: true };
978
+ }
979
+
980
+ // src/llm-payload.ts
981
+ function requestStartedPayload(op, req, tools) {
982
+ const p = {
983
+ op,
984
+ messages: req.messages.length,
985
+ content_bytes: 0,
986
+ tools,
987
+ max_tokens: _nullishCoalesce(req.maxTokens, () => ( 0)),
988
+ has_temperature: req.temperature !== void 0,
989
+ thinking: req.thinking !== void 0,
990
+ stop_sequences: _nullishCoalesce(_optionalChain([req, 'access', _21 => _21.stopSequences, 'optionalAccess', _22 => _22.length]), () => ( 0))
991
+ };
992
+ if (req.model) p.model = req.model;
993
+ for (const m of req.messages) {
994
+ _nullishCoalesce(p.roles, () => ( (p.roles = {})));
995
+ p.roles[m.role] = (_nullishCoalesce(p.roles[m.role], () => ( 0))) + 1;
996
+ p.content_bytes += messageBytes(m);
997
+ for (const part of _nullishCoalesce(m.parts, () => ( []))) {
998
+ _nullishCoalesce(p.parts, () => ( (p.parts = {})));
999
+ p.parts[part.type] = (_nullishCoalesce(p.parts[part.type], () => ( 0))) + 1;
1000
+ if (part.type === "text") p.content_bytes += bytes(part.text);
1001
+ }
1002
+ }
1003
+ const keys = Object.keys(_nullishCoalesce(req.extensions, () => ( {}))).sort();
1004
+ if (keys.length > 0) p.extension_keys = keys;
1005
+ return p;
1006
+ }
1007
+ function responseReceivedPayload(op, resp, toolCalls, durationMs) {
1008
+ const u = resp.usage;
1009
+ const p = {
1010
+ op,
1011
+ usage: {
1012
+ prompt_tokens: _nullishCoalesce(_optionalChain([u, 'optionalAccess', _23 => _23.promptTokens]), () => ( 0)),
1013
+ completion_tokens: _nullishCoalesce(_optionalChain([u, 'optionalAccess', _24 => _24.completionTokens]), () => ( 0)),
1014
+ cache_read_tokens: _nullishCoalesce(_optionalChain([u, 'optionalAccess', _25 => _25.cacheReadTokens]), () => ( 0)),
1015
+ cache_creation_tokens: _nullishCoalesce(_optionalChain([u, 'optionalAccess', _26 => _26.cacheCreationTokens]), () => ( 0)),
1016
+ total_tokens: _nullishCoalesce(_optionalChain([u, 'optionalAccess', _27 => _27.totalTokens]), () => ( 0))
1017
+ },
1018
+ content_bytes: bytes(resp.content) + callBytes(toolCalls) + thinkingBytes(resp.thinking),
1019
+ tool_calls: toolCalls.length,
1020
+ duration_ms: Math.max(0, Math.floor(durationMs))
1021
+ };
1022
+ if (resp.finishReason) p.finish_reason = resp.finishReason;
1023
+ return p;
1024
+ }
1025
+ function messageBytes(m) {
1026
+ return bytes(m.content) + callBytes(_nullishCoalesce(m.toolCalls, () => ( []))) + thinkingBytes(m.thinking);
1027
+ }
1028
+ function bytes(s) {
1029
+ return s ? Buffer.byteLength(s, "utf8") : 0;
1030
+ }
1031
+ function callBytes(calls) {
1032
+ let n = 0;
1033
+ for (const c of calls) {
1034
+ const a = c.arguments;
1035
+ if (a === void 0 || a === null) continue;
1036
+ n += bytes(typeof a === "string" ? a : JSON.stringify(a));
1037
+ }
1038
+ return n;
1039
+ }
1040
+ function thinkingBytes(tbs) {
1041
+ let n = 0;
1042
+ for (const tb of _nullishCoalesce(tbs, () => ( []))) n += bytes(tb.thinking);
1043
+ return n;
1044
+ }
1045
+
1046
+ // src/llm.ts
1047
+ var TOOL_CHOICE_MODES = ["auto", "any", "none", "tool"];
1048
+ function checkToolChoice(c, tools) {
1049
+ if (!c) return;
1050
+ const q = (v) => JSON.stringify(v);
1051
+ if (!TOOL_CHOICE_MODES.includes(c.mode)) {
1052
+ throw new LLMError(`unknown tool_choice mode ${q(String(c.mode))}`);
1053
+ }
1054
+ if (tools.length === 0) {
1055
+ throw new LLMError(`tool_choice ${q(c.mode)} needs tools`);
1056
+ }
1057
+ const name = _nullishCoalesce(c.name, () => ( ""));
1058
+ if (c.mode !== "tool") {
1059
+ if (name !== "") {
1060
+ throw new LLMError(`tool_choice ${q(c.mode)} takes no tool name`);
1061
+ }
1062
+ return;
1063
+ }
1064
+ if (name === "") {
1065
+ throw new LLMError(`tool_choice ${q(c.mode)} needs a tool name`);
1066
+ }
1067
+ if (!tools.some((t) => t.name === name)) {
1068
+ throw new LLMError(`tool_choice names unknown tool ${q(name)}`);
1069
+ }
1070
+ }
1071
+ function usageCost(u, p) {
1072
+ return (u.promptTokens * p.input + u.completionTokens * p.output + (_nullishCoalesce(u.cacheReadTokens, () => ( 0))) * p.cacheRead + (_nullishCoalesce(u.cacheCreationTokens, () => ( 0))) * p.cacheWrite) / 1e6;
1073
+ }
1074
+ var ProviderNotFoundError = class extends LLMError {
1075
+ constructor(scheme) {
1076
+ super(`provider not found: ${scheme}`);
1077
+ this.name = "ProviderNotFoundError";
1078
+ this.scheme = scheme;
1079
+ }
1080
+ };
1081
+ var CapabilityNotSupportedError = class extends LLMError {
1082
+ constructor(capability, provider) {
1083
+ super(
1084
+ `capability "${capability}" not supported by provider "${provider}"`
1085
+ );
1086
+ this.name = "CapabilityNotSupportedError";
1087
+ this.capability = capability;
1088
+ this.provider = provider;
1089
+ }
1090
+ };
1091
+ var AuthError = class extends LLMError {
1092
+ /** `cause` is the provider's error response, when there is one. */
1093
+ constructor(provider, cause) {
1094
+ super(
1095
+ `authentication failed for provider: ${provider}` + (cause ? `: ${cause.message}` : "")
1096
+ );
1097
+ this.name = "AuthError";
1098
+ this.provider = provider;
1099
+ if (cause) this.cause = cause;
1100
+ }
1101
+ };
1102
+ var PermissionDeniedError = class extends AuthError {
1103
+ constructor(provider, cause) {
1104
+ super(provider, cause);
1105
+ this.message = `permission denied for provider: ${provider}` + (cause ? `: ${cause.message}` : "");
1106
+ this.name = "PermissionDeniedError";
1107
+ }
1108
+ };
1109
+ var RateLimitError = class extends LLMError {
1110
+ constructor(provider, retryAfter) {
1111
+ super(`rate limit exceeded for provider: ${provider}`);
1112
+ this.name = "RateLimitError";
1113
+ this.provider = provider;
1114
+ this.retryAfter = retryAfter;
1115
+ this.statusCode = 429;
1116
+ }
1117
+ };
1118
+ var ModelError = class extends LLMError {
1119
+ constructor(model, provider) {
1120
+ super(`model "${model}" not available on provider "${provider}"`);
1121
+ this.name = "ModelError";
1122
+ this.model = model;
1123
+ this.provider = provider;
1124
+ }
1125
+ };
1126
+ var FallbackExhaustedError = class extends LLMError {
1127
+ constructor(errors) {
1128
+ super(
1129
+ `all providers exhausted (${errors.length} failures)`
1130
+ );
1131
+ this.name = "FallbackExhaustedError";
1132
+ this.errors = errors;
1133
+ }
1134
+ };
1135
+ function isFallbackable(err) {
1136
+ if (err instanceof ToolNameError) return false;
1137
+ if (err instanceof RateLimitError) return true;
1138
+ if (err instanceof LLMError) {
1139
+ if (err.code && isConnectionError(err.code)) return true;
1140
+ if (err.statusCode !== void 0 && err.statusCode >= 500) return true;
1141
+ return false;
1142
+ }
1143
+ const code = err.code;
1144
+ if (code && isConnectionError(code)) return true;
1145
+ return false;
1146
+ }
1147
+ var CONNECTION_CODES = /* @__PURE__ */ new Set([
1148
+ "ECONNREFUSED",
1149
+ "ETIMEDOUT",
1150
+ "ECONNRESET",
1151
+ "ENETUNREACH",
1152
+ "EHOSTUNREACH"
1153
+ ]);
1154
+ function isConnectionError(code) {
1155
+ return CONNECTION_CODES.has(code);
1156
+ }
1157
+ function checkToolLinkage(m) {
1158
+ const hasCalls = (_nullishCoalesce(_optionalChain([m, 'access', _28 => _28.toolCalls, 'optionalAccess', _29 => _29.length]), () => ( 0))) > 0;
1159
+ if (m.role === "tool") {
1160
+ if (hasCalls || (_nullishCoalesce(_optionalChain([m, 'access', _30 => _30.parts, 'optionalAccess', _31 => _31.length]), () => ( 0))) > 0) {
1161
+ throw new LLMError(
1162
+ `tool result "${_nullishCoalesce(m.toolCallId, () => ( ""))}" carries only content`
1163
+ );
1164
+ }
1165
+ return;
1166
+ }
1167
+ if (m.toolCallId) {
1168
+ throw new LLMError(
1169
+ `toolCallId is valid only on role tool, got "${m.role}"`
1170
+ );
1171
+ }
1172
+ if (hasCalls && m.role !== "assistant") {
1173
+ throw new LLMError(
1174
+ `toolCalls are valid only on role assistant, got "${m.role}"`
1175
+ );
1176
+ }
1177
+ }
1178
+ function inlineSource(data, mimeType) {
1179
+ return {
1180
+ url: () => "",
1181
+ mimeType: () => mimeType,
1182
+ read: async () => data
1183
+ };
1184
+ }
1185
+ function urlSource(url, opts = {}) {
1186
+ const maxBytes = opts.maxBytes && opts.maxBytes > 0 ? opts.maxBytes : DEFAULT_MAX_MEDIA_BYTES;
1187
+ return {
1188
+ url: () => url,
1189
+ mimeType: () => "",
1190
+ read: () => fetchMedia(url, maxBytes)
1191
+ };
1192
+ }
1193
+ var MIME_BY_EXT = {
1194
+ ".png": "image/png",
1195
+ ".jpg": "image/jpeg",
1196
+ ".jpeg": "image/jpeg",
1197
+ ".gif": "image/gif",
1198
+ ".webp": "image/webp",
1199
+ ".pdf": "application/pdf",
1200
+ ".mp3": "audio/mpeg",
1201
+ ".wav": "audio/wav",
1202
+ ".ogg": "audio/ogg",
1203
+ ".mp4": "video/mp4",
1204
+ ".webm": "video/webm",
1205
+ ".mov": "video/quicktime"
1206
+ };
1207
+ function fileSource(path) {
1208
+ return {
1209
+ url: () => "",
1210
+ mimeType: () => _nullishCoalesce(MIME_BY_EXT[_path.extname.call(void 0, path).toLowerCase()], () => ( "")),
1211
+ read: async () => new Uint8Array(await _promises.readFile.call(void 0, path))
1212
+ };
1213
+ }
1214
+ var registry = /* @__PURE__ */ new Map();
1215
+ function register(scheme, factory, decl) {
1216
+ if (registry.has(scheme)) {
1217
+ throw new LLMError(`provider already registered for scheme: ${scheme}`);
1218
+ }
1219
+ registry.set(scheme, factory);
1220
+ setDeclaration(scheme, decl);
1221
+ }
1222
+ function resolve2(uriStr, opts = {}) {
1223
+ const cfg = loadConfig(uriStr, opts);
1224
+ const factory = registry.get(cfg.uri.scheme);
1225
+ if (!factory) {
1226
+ throw new ProviderNotFoundError(cfg.uri.scheme);
1227
+ }
1228
+ return factory(cfg);
1229
+ }
1230
+ function clearRegistry() {
1231
+ registry.clear();
1232
+ clearDeclarations();
1233
+ }
1234
+ function createLLM(uri, opts) {
1235
+ const load2 = { hermetic: _optionalChain([opts, 'optionalAccess', _32 => _32.hermetic]) };
1236
+ const cfg = loadConfig(uri, load2);
1237
+ const fallbackURIs = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _33 => _33.fallback]), () => ( cfg.fallbacks));
1238
+ const primary = resolve2(uri, load2);
1239
+ const allURIs = [uri, ...fallbackURIs];
1240
+ const resolvedProviders = /* @__PURE__ */ new Map();
1241
+ resolvedProviders.set(0, primary);
1242
+ function resolveAt(index) {
1243
+ let p = resolvedProviders.get(index);
1244
+ if (!p) {
1245
+ p = resolve2(allURIs[index], load2);
1246
+ resolvedProviders.set(index, p);
1247
+ }
1248
+ return p;
1249
+ }
1250
+ async function withFallback(op, fn) {
1251
+ const errors = [];
1252
+ for (let i = 0; i < allURIs.length; i++) {
1253
+ try {
1254
+ const p = resolveAt(i);
1255
+ if (!(op in p) || typeof p[op] !== "function") {
1256
+ throw new CapabilityNotSupportedError(
1257
+ op,
1258
+ parseURI(allURIs[i]).scheme
1259
+ );
1260
+ }
1261
+ return await fn(p);
1262
+ } catch (err) {
1263
+ const e = err instanceof Error ? err : new Error(String(err));
1264
+ errors.push(e);
1265
+ _optionalChain([opts, 'optionalAccess', _34 => _34.onError, 'optionalCall', _35 => _35(e)]);
1266
+ const canContinue = isFallbackable(e) || e instanceof CapabilityNotSupportedError;
1267
+ if (!canContinue || i === allURIs.length - 1) {
1268
+ if (errors.length > 1) {
1269
+ throw new FallbackExhaustedError(errors);
1270
+ }
1271
+ throw e;
1272
+ }
1273
+ _optionalChain([opts, 'optionalAccess', _36 => _36.onFallback, 'optionalCall', _37 => _37(i, i + 1, e)]);
1274
+ }
1275
+ }
1276
+ throw new FallbackExhaustedError(errors);
1277
+ }
1278
+ function fallbackStream(request, op, open) {
1279
+ let inner = null;
1280
+ let source = null;
1281
+ let initialized = false;
1282
+ async function first() {
1283
+ _optionalChain([opts, 'optionalAccess', _38 => _38.onRequest, 'optionalCall', _39 => _39(request)]);
1284
+ const errors = [];
1285
+ for (let i = 0; i < allURIs.length; i++) {
1286
+ try {
1287
+ const p = resolveAt(i);
1288
+ if (typeof p[op] !== "function") {
1289
+ throw new CapabilityNotSupportedError(
1290
+ op,
1291
+ parseURI(allURIs[i]).scheme
1292
+ );
1293
+ }
1294
+ const iterable = open(p);
1295
+ const iter = iterable[Symbol.asyncIterator]();
1296
+ const head = await iter.next();
1297
+ inner = iter;
1298
+ source = iterable;
1299
+ return head;
1300
+ } catch (err) {
1301
+ const e = err instanceof Error ? err : new Error(String(err));
1302
+ errors.push(e);
1303
+ _optionalChain([opts, 'optionalAccess', _40 => _40.onError, 'optionalCall', _41 => _41(e)]);
1304
+ const canContinue = isFallbackable(e) || e instanceof CapabilityNotSupportedError;
1305
+ if (!canContinue || i === allURIs.length - 1) {
1306
+ if (errors.length > 1) throw new FallbackExhaustedError(errors);
1307
+ throw e;
1308
+ }
1309
+ _optionalChain([opts, 'optionalAccess', _42 => _42.onFallback, 'optionalCall', _43 => _43(i, i + 1, e)]);
1310
+ }
1311
+ }
1312
+ throw new FallbackExhaustedError(errors);
1313
+ }
1314
+ return {
1315
+ [Symbol.asyncIterator]() {
1316
+ return {
1317
+ async next() {
1318
+ if (!initialized) {
1319
+ initialized = true;
1320
+ return first();
1321
+ }
1322
+ return inner.next();
1323
+ },
1324
+ async return() {
1325
+ await _optionalChain([inner, 'optionalAccess', _44 => _44.return, 'optionalCall', _45 => _45()]);
1326
+ return { value: void 0, done: true };
1327
+ }
1328
+ };
1329
+ },
1330
+ outcome() {
1331
+ const s = source;
1332
+ return typeof _optionalChain([s, 'optionalAccess', _46 => _46.outcome]) === "function" ? s.outcome() : void 0;
1333
+ }
1334
+ };
1335
+ }
1336
+ return {
1337
+ async complete(request) {
1338
+ _optionalChain([opts, 'optionalAccess', _47 => _47.onRequest, 'optionalCall', _48 => _48(request)]);
1339
+ const start = Date.now();
1340
+ const resp = await withFallback(
1341
+ "complete",
1342
+ (p) => p.complete(request)
1343
+ );
1344
+ _optionalChain([opts, 'optionalAccess', _49 => _49.onResponse, 'optionalCall', _50 => _50(resp, Date.now() - start)]);
1345
+ return resp;
1346
+ },
1347
+ stream(request) {
1348
+ return fallbackStream(request, "stream", (p) => p.stream(request));
1349
+ },
1350
+ streamWithTools(request, tools) {
1351
+ return fallbackStream(
1352
+ request,
1353
+ "streamWithTools",
1354
+ (p) => p.streamWithTools(request, tools)
1355
+ );
1356
+ },
1357
+ async callWithTools(request, tools) {
1358
+ _optionalChain([opts, 'optionalAccess', _51 => _51.onRequest, 'optionalCall', _52 => _52(request)]);
1359
+ const start = Date.now();
1360
+ const resp = await withFallback(
1361
+ "callWithTools",
1362
+ (p) => p.callWithTools(request, tools)
1363
+ );
1364
+ _optionalChain([opts, 'optionalAccess', _53 => _53.onResponse, 'optionalCall', _54 => _54(
1365
+ {
1366
+ content: resp.content,
1367
+ role: "assistant",
1368
+ usage: resp.usage,
1369
+ finishReason: resp.finishReason,
1370
+ thinking: resp.thinking
1371
+ },
1372
+ Date.now() - start
1373
+ )]);
1374
+ return resp;
1375
+ },
1376
+ capabilities() {
1377
+ const caps = [];
1378
+ if (primary.complete) caps.push("complete");
1379
+ if (primary.stream) caps.push("stream");
1380
+ if (primary.callWithTools) caps.push("callWithTools");
1381
+ if (primary.streamWithTools) caps.push("streamWithTools");
1382
+ return caps;
1383
+ },
1384
+ provider() {
1385
+ return primary;
1386
+ },
1387
+ close() {
1388
+ for (const p of resolvedProviders.values()) {
1389
+ p.close();
1390
+ }
1391
+ }
1392
+ };
1393
+ }
1394
+
1395
+
1396
+
1397
+
1398
+
1399
+
1400
+
1401
+
1402
+
1403
+
1404
+
1405
+
1406
+
1407
+
1408
+
1409
+
1410
+
1411
+
1412
+
1413
+
1414
+
1415
+
1416
+
1417
+
1418
+
1419
+
1420
+
1421
+
1422
+
1423
+
1424
+
1425
+
1426
+
1427
+
1428
+
1429
+
1430
+
1431
+
1432
+
1433
+
1434
+
1435
+
1436
+
1437
+
1438
+
1439
+
1440
+
1441
+
1442
+
1443
+
1444
+
1445
+ exports.LLMError = LLMError; exports.HTTPStatusError = HTTPStatusError; exports.APIError = APIError; exports.StreamTruncatedError = StreamTruncatedError; exports.ResponseTooLargeError = ResponseTooLargeError; exports.KeyEndpointError = KeyEndpointError; exports.MissingKeyError = MissingKeyError; exports.TOOL_NAMES_PARAM = TOOL_NAMES_PARAM; exports.ANTHROPIC_TOOL_NAMES = ANTHROPIC_TOOL_NAMES; exports.OPENAI_TOOL_NAMES = OPENAI_TOOL_NAMES; exports.GEMINI_TOOL_NAMES = GEMINI_TOOL_NAMES; exports.ToolNameError = ToolNameError; exports.toolNameModeOf = toolNameModeOf; exports.isValidToolName = isValidToolName; exports.sanitizeToolName = sanitizeToolName; exports.ToolNames = ToolNames; exports.DEFAULT_MAX_MEDIA_BYTES = DEFAULT_MAX_MEDIA_BYTES; exports.MediaURLRefusedError = MediaURLRefusedError; exports.MediaTooLargeError = MediaTooLargeError; exports.isPublicAddress = isPublicAddress; exports.redactURI = redactURI; exports.scrubSecrets = scrubSecrets; exports.checkKeyEndpoint = checkKeyEndpoint; exports.declarationOf = declarationOf; exports.credentialsTrusted = credentialsTrusted; exports.parseURI = parseURI; exports.applyAPIKey = applyAPIKey; exports.loadConfig = loadConfig; exports.requestStartedPayload = requestStartedPayload; exports.responseReceivedPayload = responseReceivedPayload; exports.checkToolChoice = checkToolChoice; exports.usageCost = usageCost; exports.ProviderNotFoundError = ProviderNotFoundError; exports.CapabilityNotSupportedError = CapabilityNotSupportedError; exports.AuthError = AuthError; exports.PermissionDeniedError = PermissionDeniedError; exports.RateLimitError = RateLimitError; exports.ModelError = ModelError; exports.FallbackExhaustedError = FallbackExhaustedError; exports.isFallbackable = isFallbackable; exports.checkToolLinkage = checkToolLinkage; exports.inlineSource = inlineSource; exports.urlSource = urlSource; exports.fileSource = fileSource; exports.register = register; exports.resolve = resolve2; exports.clearRegistry = clearRegistry; exports.createLLM = createLLM; exports.llm_exports = llm_exports;