@hop-top/kit 0.5.0-alpha.2 → 0.5.0-alpha.4

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 (188) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/LICENSE +1 -1
  3. package/README.md +48 -480
  4. package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
  5. package/dist/aim.d.ts +1 -1
  6. package/dist/aim.js +13 -414
  7. package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
  8. package/dist/alias.d.ts +1 -1
  9. package/dist/alias.js +18 -206
  10. package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
  11. package/dist/api.d.ts +1 -1
  12. package/dist/api.js +10 -164
  13. package/dist/auth.js +6 -40
  14. package/dist/chunk-3FIKGFKI.js +54 -0
  15. package/dist/chunk-4UE5TCMQ.js +104 -0
  16. package/dist/chunk-6HFAEZ52.js +29 -0
  17. package/dist/chunk-6SVOHNIC.js +17 -0
  18. package/dist/chunk-72XZWQX7.js +504 -0
  19. package/dist/chunk-ABQSE7AI.js +513 -0
  20. package/dist/chunk-BDNNPRX6.js +41 -0
  21. package/dist/chunk-BRNEKPWX.js +37 -0
  22. package/dist/chunk-CSJWB6D3.js +151 -0
  23. package/dist/chunk-GGWJRWWA.js +309 -0
  24. package/dist/chunk-IQXEISMC.js +142 -0
  25. package/dist/chunk-JTMPNXVQ.js +1491 -0
  26. package/dist/chunk-KVG7YCTS.js +115 -0
  27. package/dist/chunk-L23O2FFE.js +51 -0
  28. package/dist/chunk-MQXYDYRD.js +968 -0
  29. package/dist/chunk-MUIQVU6E.js +251 -0
  30. package/dist/chunk-POR5L2DG.js +247 -0
  31. package/dist/chunk-PSFYJGDG.js +1445 -0
  32. package/dist/chunk-QJVSKKRQ.js +369 -0
  33. package/dist/chunk-QPUCXQXT.js +67 -0
  34. package/dist/chunk-R5U7XKVJ.js +16 -0
  35. package/dist/chunk-S45UHXQF.js +182 -0
  36. package/dist/chunk-T46YPHKN.js +669 -0
  37. package/dist/chunk-UIOOOK6M.js +334 -0
  38. package/dist/chunk-UKZIAQA7.js +26 -0
  39. package/dist/chunk-WBVO43HU.js +355 -0
  40. package/dist/chunk-WTYDHXPW.js +574 -0
  41. package/dist/chunk-WUOAQVOA.js +86 -0
  42. package/dist/chunk-WWUKGJB5.js +90 -0
  43. package/dist/chunk-YGYQUFGY.js +219 -0
  44. package/dist/chunk-YOBAUCVN.js +583 -0
  45. package/dist/{cli-DgOEOsPB.d.ts → cli-8rfITnv4.d.ts} +13 -4
  46. package/dist/cli.d.ts +4 -3
  47. package/dist/cli.js +50 -1056
  48. package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
  49. package/dist/config.d.ts +1 -1
  50. package/dist/config.js +6 -78
  51. package/dist/errcorrect.js +8 -68
  52. package/dist/error-Do8Qji43.d.ts +231 -0
  53. package/dist/id/index.d.ts +1 -1
  54. package/dist/id/index.js +14 -65
  55. package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
  56. package/dist/{index--C7Mtsmm.d.ts → index-DEyjGoo2.d.ts} +1 -1
  57. package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
  58. package/dist/index.d.ts +18 -13
  59. package/dist/index.js +40 -5792
  60. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  61. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  62. package/dist/llm-anthropic.d.ts +2 -0
  63. package/dist/llm-anthropic.js +13 -0
  64. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  65. package/dist/llm-openai.d.ts +2 -0
  66. package/dist/llm-openai.js +19 -0
  67. package/dist/llm.d.ts +1 -1
  68. package/dist/llm.js +101 -356
  69. package/dist/mcp/index.d.ts +2 -1
  70. package/dist/mcp/index.js +155 -1453
  71. package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
  72. package/dist/netpolicy.d.ts +1 -1
  73. package/dist/netpolicy.js +25 -118
  74. package/dist/{output-VFFLqor9.d.ts → output-CjZWmL8s.d.ts} +29 -130
  75. package/dist/output.d.ts +2 -1
  76. package/dist/output.js +137 -958
  77. package/dist/progress.js +6 -55
  78. package/dist/provenance.js +6 -31
  79. package/dist/routellm-B0nv59mH.d.ts +111 -0
  80. package/dist/routellm.d.ts +2 -2
  81. package/dist/routellm.js +13 -255
  82. package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
  83. package/dist/rpc.d.ts +2 -2
  84. package/dist/rpc.js +4 -98
  85. package/dist/safety.js +6 -43
  86. package/dist/scope.js +20 -377
  87. package/dist/serve-D8yWMrTc.d.ts +646 -0
  88. package/dist/serve.d.ts +3 -0
  89. package/dist/serve.js +75 -0
  90. package/dist/sqlstore.js +6 -39
  91. package/dist/stream.js +8 -51
  92. package/dist/telemetry/index.js +24 -608
  93. package/dist/tui/index.d.ts +5 -4
  94. package/dist/tui/index.js +17 -373
  95. package/dist/upgrade.js +6 -114
  96. package/dist/xdg.js +14 -128
  97. package/package.json +135 -25
  98. package/src/README.md +15 -0
  99. package/src/cli.test.ts +56 -1
  100. package/src/cli.ts +24 -4
  101. package/src/completion-values.test.ts +10 -10
  102. package/src/compliance.test.ts +196 -2
  103. package/src/compliance.ts +440 -20
  104. package/src/config.test.ts +187 -1
  105. package/src/config.ts +173 -7
  106. package/src/gen/crud_pb.ts +7 -7
  107. package/src/id/README.md +38 -0
  108. package/src/id/contract.test.ts +1 -1
  109. package/src/id/index.test.ts +1 -1
  110. package/src/id/index.ts +3 -2
  111. package/src/index.test.ts +12 -0
  112. package/src/index.ts +3 -0
  113. package/src/llm-anthropic.conformance.test.ts +1135 -0
  114. package/src/llm-anthropic.test.ts +152 -0
  115. package/src/llm-anthropic.ts +940 -0
  116. package/src/llm-choice-hermetic.test.ts +335 -0
  117. package/src/llm-config.test.ts +232 -0
  118. package/src/llm-config.ts +106 -0
  119. package/src/llm-endpoint.ts +254 -0
  120. package/src/llm-error.ts +17 -0
  121. package/src/llm-errors.ts +152 -0
  122. package/src/llm-file.ts +126 -0
  123. package/src/llm-http.ts +317 -0
  124. package/src/llm-keys.ts +167 -0
  125. package/src/llm-media.conformance.test.ts +87 -0
  126. package/src/llm-media.test.ts +279 -0
  127. package/src/llm-media.ts +322 -0
  128. package/src/llm-openai.conformance.test.ts +407 -0
  129. package/src/llm-openai.test.ts +510 -0
  130. package/src/llm-openai.ts +708 -0
  131. package/src/llm-payload.ts +155 -0
  132. package/src/llm-quote.ts +46 -0
  133. package/src/llm-routellm.conformance.test.ts +44 -0
  134. package/src/llm-toolnames.conformance.test.ts +112 -0
  135. package/src/llm-toolnames.test.ts +132 -0
  136. package/src/llm-toolnames.ts +298 -0
  137. package/src/llm-uri.ts +99 -0
  138. package/src/llm.test.ts +43 -15
  139. package/src/llm.toolcall.test.ts +175 -0
  140. package/src/llm.ts +602 -190
  141. package/src/mcp/README.md +57 -0
  142. package/src/mcp/conformance.test.ts +24 -3
  143. package/src/mcp/dispatch.ts +4 -4
  144. package/src/mcp/identity.test.ts +166 -0
  145. package/src/mcp/identity.ts +72 -0
  146. package/src/mcp/index.ts +6 -0
  147. package/src/mcp/legacy.ts +21 -8
  148. package/src/mcp/mcp.test.ts +14 -4
  149. package/src/mcp/modern-confirm.ts +1 -1
  150. package/src/mcp/modern.ts +12 -11
  151. package/src/mcp/tasks.ts +1 -1
  152. package/src/mcp/types.ts +80 -8
  153. package/src/netpolicy.test.ts +78 -0
  154. package/src/netpolicy.ts +28 -3
  155. package/src/output/README.md +46 -0
  156. package/src/output/builtins.ts +5 -5
  157. package/src/output/error.ts +167 -1
  158. package/src/output/formatters/README.md +50 -0
  159. package/src/output.ts +26 -1
  160. package/src/published-types.test.ts +115 -0
  161. package/src/routellm.test.ts +209 -28
  162. package/src/routellm.toolcall.test.ts +521 -0
  163. package/src/routellm.ts +213 -177
  164. package/src/router/README.md +44 -0
  165. package/src/router/server.test.ts +41 -0
  166. package/src/router/server.ts +11 -0
  167. package/src/safety.test.ts +19 -9
  168. package/src/scope-defaults.json +29 -29
  169. package/src/serve.test.ts +1257 -0
  170. package/src/serve.ts +1665 -0
  171. package/src/telemetry/README.md +48 -0
  172. package/src/telemetry/client.ts +5 -5
  173. package/src/toolspec.test.ts +2 -2
  174. package/src/triton/README.md +34 -0
  175. package/src/tui/README.md +42 -0
  176. package/src/wizard.test.ts +7 -7
  177. package/test/llm/conformance-helpers.ts +100 -0
  178. package/test/output/dispatch.test.ts +1 -2
  179. package/test/output/error.test.ts +38 -2
  180. package/test/output/smoke-capture.ts +2 -2
  181. package/test/output/smoke.test.ts +2 -2
  182. package/test/output/taxonomy-contract.test.ts +148 -0
  183. package/test/setup-env.ts +16 -0
  184. package/tsconfig.json +3 -1
  185. package/tsconfig.test.json +10 -0
  186. package/vitest.config.ts +9 -0
  187. package/dist/llm-B5XUWH8T.d.ts +0 -231
  188. package/dist/routellm-PGSt2D1y.d.ts +0 -75
@@ -0,0 +1,513 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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
+
4
+
5
+
6
+
7
+
8
+ var _chunkYGYQUFGYjs = require('./chunk-YGYQUFGY.js');
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+ var _chunkPSFYJGDGjs = require('./chunk-PSFYJGDG.js');
27
+
28
+
29
+ var _chunkR5U7XKVJjs = require('./chunk-R5U7XKVJ.js');
30
+
31
+ // src/llm-openai.ts
32
+ var llm_openai_exports = {};
33
+ _chunkR5U7XKVJjs.__export.call(void 0, llm_openai_exports, {
34
+ OPENAI_BASE_URLS: () => OPENAI_BASE_URLS,
35
+ OPENAI_DEFAULT_BASE_URL: () => OPENAI_DEFAULT_BASE_URL,
36
+ OPENAI_SCHEMES: () => OPENAI_SCHEMES,
37
+ OpenAIAdapter: () => OpenAIAdapter,
38
+ apiRootV1: () => apiRootV1
39
+ });
40
+ var OPENAI_SCHEMES = [
41
+ "openai",
42
+ "openrouter",
43
+ "xai",
44
+ "lmstudio",
45
+ "groq",
46
+ "together",
47
+ "fireworks",
48
+ "deepseek",
49
+ "mistral"
50
+ ];
51
+ var OPENAI_DEFAULT_BASE_URL = "https://api.openai.com/v1";
52
+ var OPENAI_BASE_URLS = Object.freeze({
53
+ openrouter: "https://openrouter.ai/api/v1",
54
+ xai: "https://api.x.ai/v1",
55
+ groq: "https://api.groq.com/openai/v1",
56
+ together: "https://api.together.xyz/v1",
57
+ fireworks: "https://api.fireworks.ai/inference/v1",
58
+ deepseek: "https://api.deepseek.com",
59
+ mistral: "https://api.mistral.ai/v1",
60
+ // LM Studio's local server; name another host or port with a
61
+ // host-form URI or ?base_url=.
62
+ lmstudio: "http://localhost:1234/v1"
63
+ });
64
+ var OpenAIAdapter = class {
65
+ constructor(cfg, opts = {}) {
66
+ this.scheme = _optionalChain([cfg, 'access', _2 => _2.uri, 'optionalAccess', _3 => _3.scheme]) || "openai";
67
+ this.label = _nullishCoalesce(opts.label, () => ( this.scheme));
68
+ this.limits = _chunkYGYQUFGYjs.limitsFrom.call(void 0, this.label, cfg.provider.params);
69
+ try {
70
+ this.toolNames = _chunkPSFYJGDGjs.toolNameModeOf.call(void 0, cfg.provider.params);
71
+ } catch (err) {
72
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${this.label}: ${err.message}`);
73
+ }
74
+ let base = cfg.provider.baseURL || OPENAI_BASE_URLS[this.scheme] || OPENAI_DEFAULT_BASE_URL;
75
+ if (this.scheme === "lmstudio" || this.scheme === "openai" && isHostForm(cfg)) {
76
+ base = apiRootV1(base);
77
+ }
78
+ try {
79
+ new URL(base);
80
+ } catch (e2) {
81
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(
82
+ `${this.label}: invalid base URL: ${JSON.stringify(_chunkPSFYJGDGjs.redactURI.call(void 0, base))}`
83
+ );
84
+ }
85
+ this.baseURL = base;
86
+ this.model = cfg.provider.model || _optionalChain([cfg, 'access', _4 => _4.uri, 'optionalAccess', _5 => _5.model]) || "";
87
+ const key = _nullishCoalesce(cfg.provider.apiKey, () => ( ""));
88
+ _chunkPSFYJGDGjs.checkKeyEndpoint.call(void 0, this.scheme, key, base);
89
+ this.headers = {
90
+ "content-type": "application/json",
91
+ accept: "application/json"
92
+ };
93
+ if (key.trim() !== "") this.headers["authorization"] = `Bearer ${key}`;
94
+ this.secrets = key.trim() !== "" ? [key] : [];
95
+ }
96
+ close() {
97
+ }
98
+ async complete(req) {
99
+ const names = this.toolNameMap([]);
100
+ const c = await this.send(await this.buildBody(req, names, []), req);
101
+ const choice = _optionalChain([c, 'access', _6 => _6.choices, 'optionalAccess', _7 => _7[0]]);
102
+ return {
103
+ content: _nullishCoalesce(_optionalChain([choice, 'optionalAccess', _8 => _8.message, 'optionalAccess', _9 => _9.content]), () => ( "")),
104
+ role: _nullishCoalesce(_optionalChain([choice, 'optionalAccess', _10 => _10.message, 'optionalAccess', _11 => _11.role]), () => ( "assistant")),
105
+ finishReason: _nullishCoalesce(_optionalChain([choice, 'optionalAccess', _12 => _12.finish_reason]), () => ( "")),
106
+ usage: usageOf(c.usage)
107
+ };
108
+ }
109
+ async callWithTools(req, tools) {
110
+ const names = this.toolNameMap(tools);
111
+ const body = await this.buildBody(req, names, tools);
112
+ body["tools"] = mapTools(names.defs(tools));
113
+ const c = await this.send(body, req);
114
+ const choice = _optionalChain([c, 'access', _13 => _13.choices, 'optionalAccess', _14 => _14[0]]);
115
+ return {
116
+ content: _nullishCoalesce(_optionalChain([choice, 'optionalAccess', _15 => _15.message, 'optionalAccess', _16 => _16.content]), () => ( "")),
117
+ toolCalls: (_nullishCoalesce(_optionalChain([choice, 'optionalAccess', _17 => _17.message, 'optionalAccess', _18 => _18.tool_calls]), () => ( []))).map((tc) => ({
118
+ id: _nullishCoalesce(tc.id, () => ( "")),
119
+ name: names.original(_nullishCoalesce(_optionalChain([tc, 'access', _19 => _19.function, 'optionalAccess', _20 => _20.name]), () => ( ""))),
120
+ arguments: parseArguments(_optionalChain([tc, 'access', _21 => _21.function, 'optionalAccess', _22 => _22.arguments]))
121
+ })),
122
+ finishReason: _nullishCoalesce(_optionalChain([choice, 'optionalAccess', _23 => _23.finish_reason]), () => ( "")),
123
+ usage: usageOf(c.usage)
124
+ };
125
+ }
126
+ stream(req) {
127
+ return this.openStream(req, void 0);
128
+ }
129
+ streamWithTools(req, tools) {
130
+ return this.openStream(req, tools);
131
+ }
132
+ // ── private ────────────────────────────────────────────────────
133
+ toolNameMap(tools) {
134
+ return _chunkPSFYJGDGjs.ToolNames.build(_chunkPSFYJGDGjs.OPENAI_TOOL_NAMES, this.toolNames, tools);
135
+ }
136
+ url() {
137
+ return _chunkYGYQUFGYjs.joinURL.call(void 0, this.baseURL, "chat/completions");
138
+ }
139
+ transport(req) {
140
+ const model = req.model || this.model;
141
+ return {
142
+ provider: this.label,
143
+ secrets: this.secrets,
144
+ limits: this.limits,
145
+ mapError: (r) => mapErrorResponse(r, this.label, this.scheme, model)
146
+ };
147
+ }
148
+ async send(body, req) {
149
+ const resp = await _chunkYGYQUFGYjs.post.call(void 0, this.transport(req), this.url(), this.headers, body);
150
+ const text = await _chunkYGYQUFGYjs.readBody.call(void 0, resp, this.limits.body, this.label).catch((e) => {
151
+ throw _chunkYGYQUFGYjs.scrubError.call(void 0, e, this.secrets);
152
+ });
153
+ try {
154
+ return JSON.parse(text);
155
+ } catch (e3) {
156
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${this.label}: response is not valid JSON`);
157
+ }
158
+ }
159
+ openStream(req, tools) {
160
+ let outcome;
161
+ const gen = this.run(req, tools, (o) => {
162
+ outcome = o;
163
+ });
164
+ return {
165
+ [Symbol.asyncIterator]: () => gen,
166
+ outcome: () => outcome
167
+ };
168
+ }
169
+ async *run(req, tools, done) {
170
+ const names = this.toolNameMap(_nullishCoalesce(tools, () => ( [])));
171
+ const body = await this.buildBody(req, names, _nullishCoalesce(tools, () => ( [])));
172
+ if (tools) body["tools"] = mapTools(names.defs(tools));
173
+ body["stream"] = true;
174
+ if (req.streamEvents) {
175
+ body["stream_options"] = { include_usage: true };
176
+ }
177
+ const resp = await _chunkYGYQUFGYjs.post.call(void 0, this.transport(req), this.url(), {
178
+ ...this.headers,
179
+ accept: "text/event-stream"
180
+ }, body);
181
+ const acc = new Accumulator(names, req.streamEvents === true);
182
+ try {
183
+ for await (const ev of _chunkYGYQUFGYjs.sseEvents.call(void 0, resp, this.limits.event, this.label)) {
184
+ if (ev.data === "[DONE]") {
185
+ done(acc.outcome());
186
+ yield { content: "", done: true };
187
+ return;
188
+ }
189
+ let chunk;
190
+ try {
191
+ chunk = JSON.parse(ev.data);
192
+ } catch (e4) {
193
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${this.label}: stream event is not valid JSON`);
194
+ }
195
+ if (chunk.error) {
196
+ const e = chunk.error;
197
+ throw new (0, _chunkPSFYJGDGjs.APIError)(
198
+ this.label,
199
+ 0,
200
+ _nullishCoalesce(e.type, () => ( "")),
201
+ `${this.label}: stream error: ${_nullishCoalesce(e.type, () => ( "error"))}: ${_nullishCoalesce(e.message, () => ( ""))}`
202
+ );
203
+ }
204
+ yield* acc.add(chunk);
205
+ }
206
+ } catch (err) {
207
+ throw _chunkYGYQUFGYjs.scrubError.call(void 0, err, this.secrets);
208
+ }
209
+ if (!acc.finished()) throw new (0, _chunkPSFYJGDGjs.StreamTruncatedError)(this.label);
210
+ done(acc.outcome());
211
+ yield { content: "", done: true };
212
+ }
213
+ /**
214
+ * Maps `req`; `tools` are the call's tools, which `req.toolChoice` is
215
+ * checked against (none for a call without tools).
216
+ */
217
+ async buildBody(req, names, tools) {
218
+ try {
219
+ _chunkPSFYJGDGjs.checkToolChoice.call(void 0, req.toolChoice, tools);
220
+ } catch (err) {
221
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${this.label}: ${err.message}`);
222
+ }
223
+ const messages = [];
224
+ for (const m of req.messages) {
225
+ messages.push(await mapMessage(m, names, this.label));
226
+ }
227
+ const body = { model: req.model || this.model, messages };
228
+ if (req.temperature !== void 0) body["temperature"] = req.temperature;
229
+ if (req.maxTokens !== void 0 && req.maxTokens > 0) {
230
+ body["max_tokens"] = req.maxTokens;
231
+ }
232
+ if (_optionalChain([req, 'access', _24 => _24.stopSequences, 'optionalAccess', _25 => _25.length])) body["stop"] = req.stopSequences;
233
+ const c = req.toolChoice;
234
+ if (c) {
235
+ body["tool_choice"] = c.mode === "tool" ? { type: "function", function: { name: names.wire(_nullishCoalesce(c.name, () => ( ""))) } } : c.mode === "any" ? "required" : c.mode;
236
+ }
237
+ return body;
238
+ }
239
+ };
240
+ function isHostForm(cfg) {
241
+ if (_optionalChain([cfg, 'access', _26 => _26.uri, 'optionalAccess', _27 => _27.params, 'optionalAccess', _28 => _28["base_url"]]) !== void 0) return false;
242
+ return !!_optionalChain([cfg, 'access', _29 => _29.uri, 'optionalAccess', _30 => _30.host]) && cfg.provider.baseURL === `http://${cfg.uri.host}`;
243
+ }
244
+ function apiRootV1(base) {
245
+ const trimmed = base.replace(/\/+$/, "");
246
+ return trimmed.endsWith("/v1") ? base : `${trimmed}/v1`;
247
+ }
248
+ async function mapMessage(m, names, label) {
249
+ if (m.role === "tool" && !m.toolCallId) {
250
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${label}: tool result needs toolCallId`);
251
+ }
252
+ _chunkPSFYJGDGjs.checkToolLinkage.call(void 0, m);
253
+ if (m.role === "tool") {
254
+ return { role: "tool", content: m.content, tool_call_id: m.toolCallId };
255
+ }
256
+ if (_optionalChain([m, 'access', _31 => _31.toolCalls, 'optionalAccess', _32 => _32.length])) {
257
+ if (_optionalChain([m, 'access', _33 => _33.parts, 'optionalAccess', _34 => _34.length])) {
258
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${label}: assistant tool calls do not support content parts`);
259
+ }
260
+ const out = { role: "assistant" };
261
+ if (m.content) out["content"] = m.content;
262
+ out["tool_calls"] = m.toolCalls.map((tc) => {
263
+ if (!tc.id) {
264
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${label}: tool call ${JSON.stringify(tc.name)} needs an id`);
265
+ }
266
+ return {
267
+ id: tc.id,
268
+ type: "function",
269
+ function: {
270
+ name: names.wire(tc.name),
271
+ arguments: encodeArguments(tc, label)
272
+ }
273
+ };
274
+ });
275
+ return out;
276
+ }
277
+ if (!_optionalChain([m, 'access', _35 => _35.parts, 'optionalAccess', _36 => _36.length])) return { role: m.role, content: m.content };
278
+ if (m.role !== "" && m.role !== "user") {
279
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(
280
+ `${label}: message role ${JSON.stringify(m.role)} does not support content parts`
281
+ );
282
+ }
283
+ const content = [];
284
+ for (const p of m.parts) content.push(await mapPart(p, label));
285
+ return { role: "user", content };
286
+ }
287
+ function encodeArguments(tc, label) {
288
+ const args = tc.arguments;
289
+ if (args === void 0 || args === null) return "{}";
290
+ if (typeof args !== "string") return JSON.stringify(args);
291
+ try {
292
+ JSON.parse(args);
293
+ } catch (e5) {
294
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(
295
+ `${label}: tool call ${JSON.stringify(tc.id)} arguments are not valid JSON`
296
+ );
297
+ }
298
+ return args;
299
+ }
300
+ async function mapPart(p, label) {
301
+ switch (p.type) {
302
+ case "text":
303
+ return { type: "text", text: _nullishCoalesce(p.text, () => ( "")) };
304
+ case "image": {
305
+ const mime = p.mimeType || _optionalChain([p, 'access', _37 => _37.source, 'optionalAccess', _38 => _38.mimeType, 'call', _39 => _39()]) || "";
306
+ if (mime === "application/pdf") {
307
+ return { type: "file", file: { file_data: await readBase64(p, label) } };
308
+ }
309
+ const url = _optionalChain([p, 'access', _40 => _40.source, 'optionalAccess', _41 => _41.url, 'call', _42 => _42()]);
310
+ if (url) return { type: "image_url", image_url: { url } };
311
+ if (!mime) {
312
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${label}: image part needs a MIME type or URL`);
313
+ }
314
+ return {
315
+ type: "image_url",
316
+ image_url: { url: `data:${mime};base64,${await readBase64(p, label)}` }
317
+ };
318
+ }
319
+ default:
320
+ throw new (0, _chunkPSFYJGDGjs.LLMError)(`${label}: unsupported modality ${JSON.stringify(p.type)}`);
321
+ }
322
+ }
323
+ async function readBase64(p, label) {
324
+ if (!p.source) throw new (0, _chunkPSFYJGDGjs.LLMError)(`${label}: nil media source`);
325
+ return Buffer.from(await p.source.read()).toString("base64");
326
+ }
327
+ function mapTools(defs) {
328
+ return defs.map((d) => {
329
+ const fn = { name: d.name };
330
+ if (d.description) fn["description"] = d.description;
331
+ const params = parametersOf(d.parameters);
332
+ if (params) fn["parameters"] = params;
333
+ return { type: "function", function: fn };
334
+ });
335
+ }
336
+ function parametersOf(params) {
337
+ let v = params;
338
+ if (typeof v === "string") {
339
+ try {
340
+ v = JSON.parse(v);
341
+ } catch (e6) {
342
+ return void 0;
343
+ }
344
+ }
345
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return void 0;
346
+ return v;
347
+ }
348
+ function usageOf(u) {
349
+ return {
350
+ promptTokens: _nullishCoalesce(_optionalChain([u, 'optionalAccess', _43 => _43.prompt_tokens]), () => ( 0)),
351
+ completionTokens: _nullishCoalesce(_optionalChain([u, 'optionalAccess', _44 => _44.completion_tokens]), () => ( 0)),
352
+ totalTokens: _nullishCoalesce(_optionalChain([u, 'optionalAccess', _45 => _45.total_tokens]), () => ( 0))
353
+ };
354
+ }
355
+ function parseArguments(raw) {
356
+ if (raw === void 0 || raw === "") return {};
357
+ try {
358
+ return JSON.parse(raw);
359
+ } catch (e7) {
360
+ return raw;
361
+ }
362
+ }
363
+ var Accumulator = class {
364
+ constructor(names, events) {
365
+ this.names = names;
366
+ this.events = events;
367
+ this.text = "";
368
+ this.finish = "";
369
+ this.calls = [];
370
+ this.byWire = /* @__PURE__ */ new Map();
371
+ }
372
+ /** Folds `c`; returns the tokens it yields: text, then tool-call events, then usage. */
373
+ add(c) {
374
+ const out = [];
375
+ const choice = _optionalChain([c, 'access', _46 => _46.choices, 'optionalAccess', _47 => _47[0]]);
376
+ if (choice) {
377
+ const content = _nullishCoalesce(_optionalChain([choice, 'access', _48 => _48.delta, 'optionalAccess', _49 => _49.content]), () => ( ""));
378
+ if (content) {
379
+ this.text += content;
380
+ out.push({ content, done: false });
381
+ }
382
+ if (!this.finish) {
383
+ for (const d of _nullishCoalesce(_optionalChain([choice, 'access', _50 => _50.delta, 'optionalAccess', _51 => _51.tool_calls]), () => ( []))) this.fragment(d, out);
384
+ }
385
+ if (choice.finish_reason && !this.finish) {
386
+ this.finish = choice.finish_reason;
387
+ this.endCalls(out);
388
+ }
389
+ }
390
+ if (c.usage) {
391
+ this.usage = c.usage;
392
+ if (this.events) out.push({ content: "", done: false, usage: usageOf(c.usage) });
393
+ }
394
+ return out;
395
+ }
396
+ fragment(d, out) {
397
+ const wire = _nullishCoalesce(d.index, () => ( this.calls.length));
398
+ let i = this.byWire.get(wire);
399
+ if (i === void 0) {
400
+ i = this.calls.length;
401
+ this.byWire.set(wire, i);
402
+ this.calls.push({ wire, id: "", name: "", args: "", pending: "", started: false });
403
+ }
404
+ const cur = this.calls[i];
405
+ if (!cur.id) cur.id = _nullishCoalesce(d.id, () => ( ""));
406
+ if (!cur.name) cur.name = _nullishCoalesce(_optionalChain([d, 'access', _52 => _52.function, 'optionalAccess', _53 => _53.name]), () => ( ""));
407
+ const frag = _nullishCoalesce(_optionalChain([d, 'access', _54 => _54.function, 'optionalAccess', _55 => _55.arguments]), () => ( ""));
408
+ cur.args += frag;
409
+ if (!this.events) return;
410
+ if (!cur.started) {
411
+ cur.pending += frag;
412
+ if (cur.id && cur.name) this.start(i, cur, out);
413
+ return;
414
+ }
415
+ if (frag) {
416
+ out.push({ content: "", done: false, toolCall: { kind: "delta", index: i, argumentsDelta: frag } });
417
+ }
418
+ }
419
+ start(i, cur, out) {
420
+ cur.started = true;
421
+ out.push({
422
+ content: "",
423
+ done: false,
424
+ toolCall: { kind: "start", index: i, id: cur.id, name: this.names.original(cur.name) }
425
+ });
426
+ if (cur.pending) {
427
+ out.push({
428
+ content: "",
429
+ done: false,
430
+ toolCall: { kind: "delta", index: i, argumentsDelta: cur.pending }
431
+ });
432
+ cur.pending = "";
433
+ }
434
+ }
435
+ /** Closes every open call, in index order; a call that never got its id or name starts first. */
436
+ endCalls(out) {
437
+ if (!this.events) return;
438
+ const order = this.calls.map((_, i) => i).sort((a, b) => this.calls[a].wire - this.calls[b].wire);
439
+ for (const i of order) {
440
+ const cur = this.calls[i];
441
+ if (!cur.started) this.start(i, cur, out);
442
+ const call = this.call(cur);
443
+ out.push({
444
+ content: "",
445
+ done: false,
446
+ toolCall: { kind: "end", index: i, id: call.id, name: call.name, call }
447
+ });
448
+ }
449
+ }
450
+ call(c) {
451
+ return { id: c.id, name: this.names.original(c.name), arguments: parseArguments(c.args) };
452
+ }
453
+ finished() {
454
+ return this.finish !== "";
455
+ }
456
+ outcome() {
457
+ return {
458
+ content: this.text,
459
+ thinking: [],
460
+ toolCalls: this.calls.map((c) => this.call(c)),
461
+ finishReason: this.finish,
462
+ usage: usageOf(this.usage)
463
+ };
464
+ }
465
+ };
466
+ function mapErrorResponse(r, label, scheme, model) {
467
+ let e = {};
468
+ try {
469
+ e = _nullishCoalesce(JSON.parse(r.body).error, () => ( {}));
470
+ } catch (e8) {
471
+ }
472
+ const detail = e.message !== void 0 ? `${_nullishCoalesce(e.type, () => ( "error"))}: ${e.message}` : r.body.slice(0, 2048);
473
+ const message = `${label}: ${r.status} ${detail}`.trim();
474
+ const api = new (0, _chunkPSFYJGDGjs.APIError)(scheme, r.status, _nullishCoalesce(e.type, () => ( "")), message);
475
+ switch (r.status) {
476
+ case 401:
477
+ return new (0, _chunkPSFYJGDGjs.AuthError)(scheme, api);
478
+ case 403:
479
+ return new (0, _chunkPSFYJGDGjs.PermissionDeniedError)(scheme, api);
480
+ case 429:
481
+ return new (0, _chunkPSFYJGDGjs.RateLimitError)(scheme);
482
+ case 404:
483
+ return new (0, _chunkPSFYJGDGjs.ModelError)(model, scheme);
484
+ }
485
+ if (r.status >= 500) return new (0, _chunkPSFYJGDGjs.HTTPStatusError)(r.status, message);
486
+ return api;
487
+ }
488
+ function openaiFactory(cfg) {
489
+ const a = new OpenAIAdapter(cfg);
490
+ return {
491
+ complete: (req) => a.complete(req),
492
+ stream: (req) => a.stream(req),
493
+ callWithTools: (req, tools) => a.callWithTools(req, tools),
494
+ streamWithTools: (req, tools) => a.streamWithTools(req, tools),
495
+ close: () => a.close()
496
+ };
497
+ }
498
+ for (const s of OPENAI_SCHEMES) {
499
+ _chunkPSFYJGDGjs.register.call(void 0, s, openaiFactory, {
500
+ endpoints: [_nullishCoalesce(OPENAI_BASE_URLS[s], () => ( OPENAI_DEFAULT_BASE_URL))],
501
+ // LM Studio's local server takes no key: none is resolved for it.
502
+ ...s === "lmstudio" ? { key: { envVars: [], optional: true } } : {}
503
+ });
504
+ }
505
+
506
+
507
+
508
+
509
+
510
+
511
+
512
+
513
+ exports.OPENAI_SCHEMES = OPENAI_SCHEMES; exports.OPENAI_DEFAULT_BASE_URL = OPENAI_DEFAULT_BASE_URL; exports.OPENAI_BASE_URLS = OPENAI_BASE_URLS; exports.OpenAIAdapter = OpenAIAdapter; exports.apiRootV1 = apiRootV1; exports.llm_openai_exports = llm_openai_exports;
@@ -0,0 +1,41 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkR5U7XKVJjs = require('./chunk-R5U7XKVJ.js');
4
+
5
+ // src/progress.ts
6
+ var progress_exports = {};
7
+ _chunkR5U7XKVJjs.__export.call(void 0, progress_exports, {
8
+ ProgressReporter: () => ProgressReporter
9
+ });
10
+ var ProgressReporter = class {
11
+ constructor(w, isTTY) {
12
+ this.w = w;
13
+ this.tty = isTTY;
14
+ }
15
+ emit(event) {
16
+ if (this.tty) {
17
+ const msg = event.message ? ` ${event.message}` : "";
18
+ this.w.write(
19
+ `[${event.phase}] ${event.step} ${event.current}/${event.total} (${event.percent}%)${msg}
20
+ `
21
+ );
22
+ return;
23
+ }
24
+ this.w.write(JSON.stringify(event) + "\n");
25
+ }
26
+ done(message) {
27
+ if (this.tty) {
28
+ this.w.write(`done: ${message}
29
+ `);
30
+ return;
31
+ }
32
+ this.w.write(
33
+ JSON.stringify({ done: true, message }) + "\n"
34
+ );
35
+ }
36
+ };
37
+
38
+
39
+
40
+
41
+ exports.ProgressReporter = ProgressReporter; exports.progress_exports = progress_exports;
@@ -0,0 +1,37 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _chunkR5U7XKVJjs = require('./chunk-R5U7XKVJ.js');
4
+
5
+ // src/stream.ts
6
+ var stream_exports = {};
7
+ _chunkR5U7XKVJjs.__export.call(void 0, stream_exports, {
8
+ ExitCode: () => ExitCode,
9
+ createStreamWriter: () => createStreamWriter
10
+ });
11
+ var ExitCode = /* @__PURE__ */ ((ExitCode2) => {
12
+ ExitCode2[ExitCode2["OK"] = 0] = "OK";
13
+ ExitCode2[ExitCode2["Error"] = 1] = "Error";
14
+ ExitCode2[ExitCode2["Usage"] = 2] = "Usage";
15
+ ExitCode2[ExitCode2["NotFound"] = 3] = "NotFound";
16
+ ExitCode2[ExitCode2["Conflict"] = 4] = "Conflict";
17
+ ExitCode2[ExitCode2["Auth"] = 5] = "Auth";
18
+ ExitCode2[ExitCode2["Permission"] = 6] = "Permission";
19
+ ExitCode2[ExitCode2["Timeout"] = 7] = "Timeout";
20
+ ExitCode2[ExitCode2["Cancelled"] = 8] = "Cancelled";
21
+ return ExitCode2;
22
+ })(ExitCode || {});
23
+ function createStreamWriter(opts) {
24
+ const data = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _ => _.data]), () => ( process.stdout));
25
+ const human = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _2 => _2.human]), () => ( process.stderr));
26
+ return {
27
+ data,
28
+ human,
29
+ isTTY: !!process.stdout.isTTY
30
+ };
31
+ }
32
+
33
+
34
+
35
+
36
+
37
+ exports.ExitCode = ExitCode; exports.createStreamWriter = createStreamWriter; exports.stream_exports = stream_exports;