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

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 (293) hide show
  1. package/CHANGELOG.md +275 -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-3FIKGFKI.js +54 -0
  19. package/dist/chunk-4FMALWYB.js +669 -0
  20. package/dist/chunk-4GPCWBBA.js +143 -0
  21. package/dist/chunk-4UE5TCMQ.js +104 -0
  22. package/dist/chunk-65VPWMPV.js +1134 -0
  23. package/dist/chunk-6HFAEZ52.js +29 -0
  24. package/dist/chunk-6SVOHNIC.js +17 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BRNEKPWX.js +37 -0
  27. package/dist/chunk-BXJ2J27B.js +219 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-CXBZTONY.js +65 -0
  30. package/dist/chunk-EE4M2UOF.js +818 -0
  31. package/dist/chunk-GFRAYYRD.js +817 -0
  32. package/dist/chunk-IVQHLI56.js +1890 -0
  33. package/dist/chunk-IZ6Q4SE3.js +178 -0
  34. package/dist/chunk-JKMQSAJP.js +174 -0
  35. package/dist/chunk-K7E34Q3A.js +1445 -0
  36. package/dist/chunk-KVG7YCTS.js +115 -0
  37. package/dist/chunk-L23O2FFE.js +51 -0
  38. package/dist/chunk-MFVUENZR.js +1549 -0
  39. package/dist/chunk-ML7D5DWY.js +263 -0
  40. package/dist/chunk-MQXYDYRD.js +968 -0
  41. package/dist/chunk-POR5L2DG.js +247 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QQQYCWSC.js +240 -0
  44. package/dist/chunk-R5U7XKVJ.js +16 -0
  45. package/dist/chunk-RYKLVOVK.js +309 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T6OZMPPV.js +68 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-VGOA5Y7S.js +251 -0
  50. package/dist/chunk-VWGP4NVJ.js +513 -0
  51. package/dist/chunk-WBVO43HU.js +355 -0
  52. package/dist/chunk-WUOAQVOA.js +86 -0
  53. package/dist/chunk-XJTRY453.js +868 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-RSRk1M36.d.ts +707 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +125 -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-CGE5yLBj.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 +185 -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 +135 -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-C3RWGwRi.d.ts +125 -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.root.conformance.test.ts +166 -0
  150. package/src/cli.test.ts +95 -1
  151. package/src/cli.ts +234 -25
  152. package/src/completion-scripts.ts +16 -0
  153. package/src/completion-values.test.ts +76 -16
  154. package/src/completion-values.ts +170 -66
  155. package/src/completion.conformance.test.ts +298 -0
  156. package/src/completion.test.ts +268 -145
  157. package/src/completion.ts +772 -121
  158. package/src/compliance.test.ts +196 -2
  159. package/src/compliance.ts +440 -20
  160. package/src/config-merge.test.ts +425 -0
  161. package/src/config.test.ts +228 -1
  162. package/src/config.ts +429 -16
  163. package/src/delegation.test.ts +299 -0
  164. package/src/delegation.ts +807 -0
  165. package/src/gen/crud_pb.ts +7 -7
  166. package/src/id/README.md +38 -0
  167. package/src/id/contract.test.ts +1 -1
  168. package/src/id/index.test.ts +1 -1
  169. package/src/id/index.ts +3 -2
  170. package/src/index.test.ts +71 -0
  171. package/src/index.ts +46 -0
  172. package/src/llm-anthropic.conformance.test.ts +1135 -0
  173. package/src/llm-anthropic.test.ts +152 -0
  174. package/src/llm-anthropic.ts +940 -0
  175. package/src/llm-choice-hermetic.test.ts +335 -0
  176. package/src/llm-config.test.ts +232 -0
  177. package/src/llm-config.ts +106 -0
  178. package/src/llm-endpoint.ts +254 -0
  179. package/src/llm-error.ts +17 -0
  180. package/src/llm-errors.ts +152 -0
  181. package/src/llm-file.ts +126 -0
  182. package/src/llm-http.ts +317 -0
  183. package/src/llm-keys.ts +167 -0
  184. package/src/llm-media.conformance.test.ts +87 -0
  185. package/src/llm-media.test.ts +279 -0
  186. package/src/llm-media.ts +322 -0
  187. package/src/llm-openai.conformance.test.ts +407 -0
  188. package/src/llm-openai.test.ts +510 -0
  189. package/src/llm-openai.ts +708 -0
  190. package/src/llm-payload.ts +155 -0
  191. package/src/llm-quote.ts +46 -0
  192. package/src/llm-routellm.conformance.test.ts +44 -0
  193. package/src/llm-toolnames.conformance.test.ts +112 -0
  194. package/src/llm-toolnames.test.ts +132 -0
  195. package/src/llm-toolnames.ts +298 -0
  196. package/src/llm-uri.ts +99 -0
  197. package/src/llm.test.ts +43 -15
  198. package/src/llm.toolcall.test.ts +175 -0
  199. package/src/llm.ts +602 -190
  200. package/src/log.parity.test.ts +105 -0
  201. package/src/log.test.ts +270 -1
  202. package/src/log.ts +228 -49
  203. package/src/mcp/README.md +63 -0
  204. package/src/mcp/args-separator.test.ts +164 -0
  205. package/src/mcp/args.test.ts +223 -0
  206. package/src/mcp/args.ts +160 -0
  207. package/src/mcp/audit.test.ts +520 -0
  208. package/src/mcp/audit.ts +70 -0
  209. package/src/mcp/bridge.test.ts +250 -0
  210. package/src/mcp/bridge.ts +286 -0
  211. package/src/mcp/conformance.test.ts +357 -0
  212. package/src/mcp/dispatch.ts +359 -0
  213. package/src/mcp/identity.test.ts +166 -0
  214. package/src/mcp/identity.ts +72 -0
  215. package/src/mcp/index.ts +176 -0
  216. package/src/mcp/legacy-notify.test.ts +59 -0
  217. package/src/mcp/legacy.ts +367 -0
  218. package/src/mcp/mcp.test.ts +707 -0
  219. package/src/mcp/modern-confirm.test.ts +520 -0
  220. package/src/mcp/modern-confirm.ts +484 -0
  221. package/src/mcp/modern.ts +788 -0
  222. package/src/mcp/stdio.test.ts +313 -0
  223. package/src/mcp/stdio.ts +254 -0
  224. package/src/mcp/tasks.ts +82 -0
  225. package/src/mcp/testtree.ts +250 -0
  226. package/src/mcp/toolname.test.ts +147 -0
  227. package/src/mcp/types.ts +689 -0
  228. package/src/netpolicy.test.ts +280 -0
  229. package/src/netpolicy.ts +256 -0
  230. package/src/output/README.md +46 -0
  231. package/src/output/builtins.ts +5 -5
  232. package/src/output/dispatch.ts +10 -2
  233. package/src/output/error.ts +459 -0
  234. package/src/output/formatter.ts +29 -5
  235. package/src/output/formatters/README.md +50 -0
  236. package/src/output/formatters/csv.ts +48 -12
  237. package/src/output/formatters/json.ts +4 -25
  238. package/src/output/formatters/project.ts +34 -0
  239. package/src/output/formatters/table.ts +8 -6
  240. package/src/output/formatters/text.ts +7 -3
  241. package/src/output/formatters/yaml.ts +5 -22
  242. package/src/output/projection.test.ts +298 -0
  243. package/src/output/projection.ts +33 -59
  244. package/src/output/template.ts +11 -21
  245. package/src/output.surface.test.ts +41 -0
  246. package/src/output.ts +64 -3
  247. package/src/plan.ts +89 -0
  248. package/src/policy.ts +472 -0
  249. package/src/published-types.test.ts +133 -0
  250. package/src/routellm.test.ts +209 -28
  251. package/src/routellm.toolcall.test.ts +521 -0
  252. package/src/routellm.ts +213 -177
  253. package/src/router/README.md +44 -0
  254. package/src/router/server.test.ts +41 -0
  255. package/src/router/server.ts +11 -0
  256. package/src/safety.test.ts +19 -9
  257. package/src/scope-defaults.json +29 -29
  258. package/src/serve.test.ts +1257 -0
  259. package/src/serve.ts +1665 -0
  260. package/src/sideeffect.ts +105 -0
  261. package/src/telemetry/README.md +48 -0
  262. package/src/telemetry/client.test.ts +31 -0
  263. package/src/telemetry/client.ts +12 -6
  264. package/src/telemetry/offline.test.ts +64 -0
  265. package/src/toolspec-internal.ts +279 -0
  266. package/src/toolspec-manifest.test.ts +167 -0
  267. package/src/toolspec-manifest.ts +415 -0
  268. package/src/toolspec-spec-schemas.ts +12 -0
  269. package/src/toolspec-spec.test.ts +273 -0
  270. package/src/toolspec-spec.ts +458 -0
  271. package/src/toolspec.from-command.test.ts +350 -0
  272. package/src/toolspec.test.ts +2 -2
  273. package/src/toolspec.ts +222 -0
  274. package/src/triton/README.md +34 -0
  275. package/src/tui/README.md +42 -0
  276. package/src/tui/parity.test.ts +120 -31
  277. package/src/tui/parity.ts +58 -7
  278. package/src/upgrade.test.ts +291 -0
  279. package/src/upgrade.ts +116 -7
  280. package/src/wizard.test.ts +7 -7
  281. package/test/llm/conformance-helpers.ts +100 -0
  282. package/test/output/csv.test.ts +164 -0
  283. package/test/output/dispatch.test.ts +1 -2
  284. package/test/output/error.test.ts +277 -0
  285. package/test/output/smoke-capture.ts +2 -2
  286. package/test/output/smoke.test.ts +2 -2
  287. package/test/output/taxonomy-contract.test.ts +148 -0
  288. package/test/setup-env.ts +16 -0
  289. package/test/toolspec/fixture.ts +79 -0
  290. package/tsconfig.json +3 -1
  291. package/tsconfig.test.json +10 -0
  292. package/vitest.config.ts +9 -0
  293. package/src/tui/parity.json +0 -74
@@ -0,0 +1,708 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * OpenAI Chat Completions adapter — registers, on import, the schemes
5
+ * `openai`, `openrouter`, `xai`, `lmstudio`, `groq`, `together`,
6
+ * `fireworks`, `deepseek` and `mistral`. Implements complete, stream,
7
+ * callWithTools and streamWithTools.
8
+ *
9
+ * URI: `openai://<model>[?params]`; a host form
10
+ * (`openai://host:port/model`) names a self-hosted OpenAI-compatible
11
+ * server, reached at `http://host:port/v1`; a `base_url` param is used
12
+ * as given. `lmstudio` defaults to `http://localhost:1234/v1` and
13
+ * appends `/v1` to any base URL that lacks it. Params: `tool_names`
14
+ * (`sanitize` | `strict`), `max_body_bytes`, `max_event_bytes`. The key
15
+ * resolves as `loadConfig` resolves it (the URI's `api_key`, llm.yaml,
16
+ * `<SCHEME>_API_KEY`, then `LLM_API_KEY`; `lmstudio` sends none unless
17
+ * the URI or llm.yaml gives one); a blank key sends no
18
+ * Authorization header.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import "@hop-top/kit/openai";
23
+ * import { createLLM } from "@hop-top/kit/llm";
24
+ *
25
+ * const llm = createLLM("openai://gpt-4.1-mini");
26
+ * ```
27
+ */
28
+
29
+ import {
30
+ AuthError,
31
+ LLMError,
32
+ ModelError,
33
+ OPENAI_TOOL_NAMES,
34
+ PermissionDeniedError,
35
+ RateLimitError,
36
+ ToolNames,
37
+ checkToolChoice,
38
+ checkToolLinkage,
39
+ register,
40
+ toolNameModeOf,
41
+ type Completer,
42
+ type ContentPart,
43
+ type Message,
44
+ type Provider,
45
+ type Request,
46
+ type ResolvedConfig,
47
+ type Response,
48
+ type StreamOutcome,
49
+ type Streamer,
50
+ type Token,
51
+ type ToolCall,
52
+ type ToolCaller,
53
+ type ToolDef,
54
+ type ToolNameMode,
55
+ type ToolResponse,
56
+ type ToolStream,
57
+ type ToolStreamer,
58
+ type Usage,
59
+ } from "./llm";
60
+ import { checkKeyEndpoint, redactURI } from "./llm-endpoint";
61
+ import { APIError, HTTPStatusError, StreamTruncatedError } from "./llm-errors";
62
+ import {
63
+ joinURL,
64
+ limitsFrom,
65
+ post,
66
+ readBody,
67
+ scrubError,
68
+ sseEvents,
69
+ type ErrorResponse,
70
+ type Limits,
71
+ type TransportOptions,
72
+ } from "./llm-http";
73
+
74
+ /** Schemes this adapter registers. */
75
+ export const OPENAI_SCHEMES = [
76
+ "openai", "openrouter", "xai", "lmstudio",
77
+ "groq", "together", "fireworks", "deepseek", "mistral",
78
+ ] as const;
79
+
80
+ /** OpenAI's API root; schemes without a default below use it. */
81
+ export const OPENAI_DEFAULT_BASE_URL = "https://api.openai.com/v1";
82
+
83
+ /** Each scheme's default API root. */
84
+ export const OPENAI_BASE_URLS: Readonly<Record<string, string>> = Object.freeze({
85
+ openrouter: "https://openrouter.ai/api/v1",
86
+ xai: "https://api.x.ai/v1",
87
+ groq: "https://api.groq.com/openai/v1",
88
+ together: "https://api.together.xyz/v1",
89
+ fireworks: "https://api.fireworks.ai/inference/v1",
90
+ deepseek: "https://api.deepseek.com",
91
+ mistral: "https://api.mistral.ai/v1",
92
+ // LM Studio's local server; name another host or port with a
93
+ // host-form URI or ?base_url=.
94
+ lmstudio: "http://localhost:1234/v1",
95
+ });
96
+
97
+ /** Options for adapters that speak the OpenAI wire on their own scheme. */
98
+ export interface OpenAIAdapterOptions {
99
+ /** Prefix of error messages; defaults to the URI scheme. */
100
+ label?: string;
101
+ }
102
+
103
+ type Wire = Record<string, unknown>;
104
+
105
+ /**
106
+ * OpenAI Chat Completions adapter over fetch, for OpenAI and any
107
+ * compatible server.
108
+ */
109
+ export class OpenAIAdapter
110
+ implements Completer, Streamer, ToolCaller, ToolStreamer
111
+ {
112
+ readonly model: string;
113
+ readonly baseURL: string;
114
+ readonly scheme: string;
115
+ private readonly label: string;
116
+ private readonly headers: Record<string, string>;
117
+ private readonly secrets: string[];
118
+ private readonly limits: Limits;
119
+ private readonly toolNames: ToolNameMode;
120
+
121
+ constructor(cfg: ResolvedConfig, opts: OpenAIAdapterOptions = {}) {
122
+ this.scheme = cfg.uri?.scheme || "openai";
123
+ this.label = opts.label ?? this.scheme;
124
+ this.limits = limitsFrom(this.label, cfg.provider.params);
125
+ try {
126
+ this.toolNames = toolNameModeOf(cfg.provider.params);
127
+ } catch (err) {
128
+ throw new LLMError(`${this.label}: ${(err as Error).message}`);
129
+ }
130
+
131
+ let base =
132
+ cfg.provider.baseURL || OPENAI_BASE_URLS[this.scheme] || OPENAI_DEFAULT_BASE_URL;
133
+ if (this.scheme === "lmstudio" || (this.scheme === "openai" && isHostForm(cfg))) {
134
+ base = apiRootV1(base);
135
+ }
136
+ try {
137
+ new URL(base);
138
+ } catch {
139
+ throw new LLMError(
140
+ `${this.label}: invalid base URL: ${JSON.stringify(redactURI(base))}`
141
+ );
142
+ }
143
+ this.baseURL = base;
144
+ this.model = cfg.provider.model || cfg.uri?.model || "";
145
+
146
+ // A blank key is no key: no Authorization header rather than
147
+ // "Bearer " with nothing after it.
148
+ const key = cfg.provider.apiKey ?? "";
149
+ checkKeyEndpoint(this.scheme, key, base);
150
+ this.headers = {
151
+ "content-type": "application/json",
152
+ accept: "application/json",
153
+ };
154
+ if (key.trim() !== "") this.headers["authorization"] = `Bearer ${key}`;
155
+ this.secrets = key.trim() !== "" ? [key] : [];
156
+ }
157
+
158
+ close(): void {
159
+ // fetch holds no per-adapter resources.
160
+ }
161
+
162
+ async complete(req: Request): Promise<Response> {
163
+ const names = this.toolNameMap([]);
164
+ const c = await this.send(await this.buildBody(req, names, []), req);
165
+ const choice = c.choices?.[0];
166
+ return {
167
+ content: choice?.message?.content ?? "",
168
+ role: choice?.message?.role ?? "assistant",
169
+ finishReason: choice?.finish_reason ?? "",
170
+ usage: usageOf(c.usage),
171
+ };
172
+ }
173
+
174
+ async callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse> {
175
+ const names = this.toolNameMap(tools);
176
+ const body = await this.buildBody(req, names, tools);
177
+ body["tools"] = mapTools(names.defs(tools));
178
+ const c = await this.send(body, req);
179
+ const choice = c.choices?.[0];
180
+ return {
181
+ content: choice?.message?.content ?? "",
182
+ toolCalls: (choice?.message?.tool_calls ?? []).map((tc) => ({
183
+ id: tc.id ?? "",
184
+ name: names.original(tc.function?.name ?? ""),
185
+ arguments: parseArguments(tc.function?.arguments),
186
+ })),
187
+ finishReason: choice?.finish_reason ?? "",
188
+ usage: usageOf(c.usage),
189
+ };
190
+ }
191
+
192
+ stream(req: Request): ToolStream {
193
+ return this.openStream(req, undefined);
194
+ }
195
+
196
+ streamWithTools(req: Request, tools: ToolDef[]): ToolStream {
197
+ return this.openStream(req, tools);
198
+ }
199
+
200
+ // ── private ────────────────────────────────────────────────────
201
+
202
+ private toolNameMap(tools: ReadonlyArray<{ name: string }>): ToolNames {
203
+ return ToolNames.build(OPENAI_TOOL_NAMES, this.toolNames, tools);
204
+ }
205
+
206
+ private url(): string {
207
+ return joinURL(this.baseURL, "chat/completions");
208
+ }
209
+
210
+ private transport(req: Request): TransportOptions {
211
+ const model = req.model || this.model;
212
+ return {
213
+ provider: this.label,
214
+ secrets: this.secrets,
215
+ limits: this.limits,
216
+ mapError: (r) => mapErrorResponse(r, this.label, this.scheme, model),
217
+ };
218
+ }
219
+
220
+ private async send(body: Wire, req: Request): Promise<WireCompletion> {
221
+ const resp = await post(this.transport(req), this.url(), this.headers, body);
222
+ const text = await readBody(resp, this.limits.body, this.label).catch((e) => {
223
+ throw scrubError(e as Error, this.secrets);
224
+ });
225
+ try {
226
+ return JSON.parse(text) as WireCompletion;
227
+ } catch {
228
+ throw new LLMError(`${this.label}: response is not valid JSON`);
229
+ }
230
+ }
231
+
232
+ private openStream(req: Request, tools: ToolDef[] | undefined): ToolStream {
233
+ let outcome: StreamOutcome | undefined;
234
+ const gen = this.run(req, tools, (o) => {
235
+ outcome = o;
236
+ });
237
+ return {
238
+ [Symbol.asyncIterator]: () => gen,
239
+ outcome: () => outcome,
240
+ };
241
+ }
242
+
243
+ private async *run(
244
+ req: Request,
245
+ tools: ToolDef[] | undefined,
246
+ done: (o: StreamOutcome) => void
247
+ ): AsyncGenerator<Token> {
248
+ const names = this.toolNameMap(tools ?? []);
249
+ const body = await this.buildBody(req, names, tools ?? []);
250
+ if (tools) body["tools"] = mapTools(names.defs(tools));
251
+ body["stream"] = true;
252
+ if (req.streamEvents) {
253
+ // Usage streams only when asked for, in a chunk after the last
254
+ // choice; a stream without events does not ask.
255
+ body["stream_options"] = { include_usage: true };
256
+ }
257
+ const resp = await post(this.transport(req), this.url(), {
258
+ ...this.headers,
259
+ accept: "text/event-stream",
260
+ }, body);
261
+ const acc = new Accumulator(names, req.streamEvents === true);
262
+ try {
263
+ for await (const ev of sseEvents(resp, this.limits.event, this.label)) {
264
+ if (ev.data === "[DONE]") {
265
+ done(acc.outcome());
266
+ yield { content: "", done: true };
267
+ return;
268
+ }
269
+ let chunk: WireChunk;
270
+ try {
271
+ chunk = JSON.parse(ev.data) as WireChunk;
272
+ } catch {
273
+ throw new LLMError(`${this.label}: stream event is not valid JSON`);
274
+ }
275
+ if (chunk.error) {
276
+ const e = chunk.error;
277
+ throw new APIError(
278
+ this.label,
279
+ 0,
280
+ e.type ?? "",
281
+ `${this.label}: stream error: ${e.type ?? "error"}: ${e.message ?? ""}`
282
+ );
283
+ }
284
+ yield* acc.add(chunk);
285
+ }
286
+ } catch (err) {
287
+ throw scrubError(err as Error, this.secrets);
288
+ }
289
+ // Some compatible servers end without [DONE] once a choice
290
+ // finished; a stream that ends before any finish is incomplete.
291
+ if (!acc.finished()) throw new StreamTruncatedError(this.label);
292
+ done(acc.outcome());
293
+ yield { content: "", done: true };
294
+ }
295
+
296
+ /**
297
+ * Maps `req`; `tools` are the call's tools, which `req.toolChoice` is
298
+ * checked against (none for a call without tools).
299
+ */
300
+ private async buildBody(
301
+ req: Request,
302
+ names: ToolNames,
303
+ tools: ReadonlyArray<{ name: string }>
304
+ ): Promise<Wire> {
305
+ try {
306
+ checkToolChoice(req.toolChoice, tools);
307
+ } catch (err) {
308
+ throw new LLMError(`${this.label}: ${(err as Error).message}`);
309
+ }
310
+ const messages: Wire[] = [];
311
+ for (const m of req.messages) {
312
+ messages.push(await mapMessage(m, names, this.label));
313
+ }
314
+ const body: Wire = { model: req.model || this.model, messages };
315
+ if (req.temperature !== undefined) body["temperature"] = req.temperature;
316
+ if (req.maxTokens !== undefined && req.maxTokens > 0) {
317
+ body["max_tokens"] = req.maxTokens;
318
+ }
319
+ if (req.stopSequences?.length) body["stop"] = req.stopSequences;
320
+ const c = req.toolChoice;
321
+ if (c) {
322
+ // any is "required"; a named tool goes by the name sent for it.
323
+ body["tool_choice"] =
324
+ c.mode === "tool"
325
+ ? { type: "function", function: { name: names.wire(c.name ?? "") } }
326
+ : c.mode === "any"
327
+ ? "required"
328
+ : c.mode;
329
+ }
330
+ return body;
331
+ }
332
+ }
333
+
334
+ /**
335
+ * Whether cfg's base URL is the one a host-form URI derives
336
+ * (`http://host:port`), rather than one a `base_url` param, the
337
+ * environment or a caller named outright.
338
+ */
339
+ function isHostForm(cfg: ResolvedConfig): boolean {
340
+ if (cfg.uri?.params?.["base_url"] !== undefined) return false;
341
+ return !!cfg.uri?.host && cfg.provider.baseURL === `http://${cfg.uri.host}`;
342
+ }
343
+
344
+ /** `base` ending in `/v1`; one already ending in `/v1` is kept. */
345
+ export function apiRootV1(base: string): string {
346
+ const trimmed = base.replace(/\/+$/, "");
347
+ return trimmed.endsWith("/v1") ? base : `${trimmed}/v1`;
348
+ }
349
+
350
+ // ─── Message mapping ─────────────────────────────────────────────────────────
351
+
352
+ /**
353
+ * Maps one message onto the chat wire: assistant `toolCalls` become
354
+ * `tool_calls`, a role `tool` result carries `tool_call_id`, and
355
+ * `parts` become a user content array. Linkage or parts the wire cannot
356
+ * carry throw instead of being sent as plain text. Tool-call names go
357
+ * out as `names` maps them (llm-v1 tool names).
358
+ */
359
+ async function mapMessage(m: Message, names: ToolNames, label: string): Promise<Wire> {
360
+ if (m.role === "tool" && !m.toolCallId) {
361
+ throw new LLMError(`${label}: tool result needs toolCallId`);
362
+ }
363
+ checkToolLinkage(m);
364
+
365
+ if (m.role === "tool") {
366
+ return { role: "tool", content: m.content, tool_call_id: m.toolCallId };
367
+ }
368
+
369
+ if (m.toolCalls?.length) {
370
+ if (m.parts?.length) {
371
+ throw new LLMError(`${label}: assistant tool calls do not support content parts`);
372
+ }
373
+ const out: Wire = { role: "assistant" };
374
+ if (m.content) out["content"] = m.content;
375
+ out["tool_calls"] = m.toolCalls.map((tc) => {
376
+ if (!tc.id) {
377
+ throw new LLMError(`${label}: tool call ${JSON.stringify(tc.name)} needs an id`);
378
+ }
379
+ return {
380
+ id: tc.id,
381
+ type: "function",
382
+ function: {
383
+ name: names.wire(tc.name),
384
+ arguments: encodeArguments(tc, label),
385
+ },
386
+ };
387
+ });
388
+ return out;
389
+ }
390
+
391
+ if (!m.parts?.length) return { role: m.role, content: m.content };
392
+
393
+ if (m.role !== "" && m.role !== "user") {
394
+ throw new LLMError(
395
+ `${label}: message role ${JSON.stringify(m.role)} does not support content parts`
396
+ );
397
+ }
398
+ const content: Wire[] = [];
399
+ for (const p of m.parts) content.push(await mapPart(p, label));
400
+ return { role: "user", content };
401
+ }
402
+
403
+ /** Tool-call arguments as the JSON string the wire expects. */
404
+ function encodeArguments(tc: ToolCall, label: string): string {
405
+ const args = tc.arguments;
406
+ if (args === undefined || args === null) return "{}";
407
+ if (typeof args !== "string") return JSON.stringify(args);
408
+ try {
409
+ JSON.parse(args);
410
+ } catch {
411
+ throw new LLMError(
412
+ `${label}: tool call ${JSON.stringify(tc.id)} arguments are not valid JSON`
413
+ );
414
+ }
415
+ return args;
416
+ }
417
+
418
+ async function mapPart(p: ContentPart, label: string): Promise<Wire> {
419
+ switch (p.type) {
420
+ case "text":
421
+ return { type: "text", text: p.text ?? "" };
422
+
423
+ case "image": {
424
+ const mime = p.mimeType || p.source?.mimeType() || "";
425
+ if (mime === "application/pdf") {
426
+ return { type: "file", file: { file_data: await readBase64(p, label) } };
427
+ }
428
+ const url = p.source?.url();
429
+ if (url) return { type: "image_url", image_url: { url } };
430
+ if (!mime) {
431
+ throw new LLMError(`${label}: image part needs a MIME type or URL`);
432
+ }
433
+ return {
434
+ type: "image_url",
435
+ image_url: { url: `data:${mime};base64,${await readBase64(p, label)}` },
436
+ };
437
+ }
438
+
439
+ default:
440
+ throw new LLMError(`${label}: unsupported modality ${JSON.stringify(p.type)}`);
441
+ }
442
+ }
443
+
444
+ async function readBase64(p: ContentPart, label: string): Promise<string> {
445
+ if (!p.source) throw new LLMError(`${label}: nil media source`);
446
+ return Buffer.from(await p.source.read()).toString("base64");
447
+ }
448
+
449
+ function mapTools(defs: ToolDef[]): Wire[] {
450
+ return defs.map((d) => {
451
+ const fn: Wire = { name: d.name };
452
+ if (d.description) fn["description"] = d.description;
453
+ const params = parametersOf(d.parameters);
454
+ if (params) fn["parameters"] = params;
455
+ return { type: "function", function: fn };
456
+ });
457
+ }
458
+
459
+ function parametersOf(params: unknown): Wire | undefined {
460
+ let v = params;
461
+ if (typeof v === "string") {
462
+ try {
463
+ v = JSON.parse(v);
464
+ } catch {
465
+ return undefined;
466
+ }
467
+ }
468
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return undefined;
469
+ return v as Wire;
470
+ }
471
+
472
+ // ─── Response mapping ────────────────────────────────────────────────────────
473
+
474
+ interface WireToolCall {
475
+ index?: number;
476
+ id?: string;
477
+ function?: { name?: string; arguments?: string };
478
+ }
479
+
480
+ interface WireUsage {
481
+ prompt_tokens?: number;
482
+ completion_tokens?: number;
483
+ total_tokens?: number;
484
+ }
485
+
486
+ interface WireCompletion {
487
+ choices?: {
488
+ message?: { content?: string | null; role?: string; tool_calls?: WireToolCall[] };
489
+ finish_reason?: string | null;
490
+ }[];
491
+ usage?: WireUsage | null;
492
+ }
493
+
494
+ interface WireChunk {
495
+ choices?: {
496
+ delta?: { content?: string | null; tool_calls?: WireToolCall[] };
497
+ finish_reason?: string | null;
498
+ }[];
499
+ usage?: WireUsage | null;
500
+ error?: { type?: string; message?: string };
501
+ }
502
+
503
+ function usageOf(u: WireUsage | null | undefined): Usage {
504
+ return {
505
+ promptTokens: u?.prompt_tokens ?? 0,
506
+ completionTokens: u?.completion_tokens ?? 0,
507
+ totalTokens: u?.total_tokens ?? 0,
508
+ };
509
+ }
510
+
511
+ /** Returned arguments parsed, or the raw text when they are not JSON. */
512
+ function parseArguments(raw: string | undefined): unknown {
513
+ if (raw === undefined || raw === "") return {};
514
+ try {
515
+ return JSON.parse(raw);
516
+ } catch {
517
+ return raw;
518
+ }
519
+ }
520
+
521
+ /** A tool call as its fragments arrive. */
522
+ interface PartialCall {
523
+ /** The chunk's `tool_calls[].index`. */
524
+ wire: number;
525
+ id: string;
526
+ name: string;
527
+ args: string;
528
+ /** Argument fragments that came before the call started (no id and name yet). */
529
+ pending: string;
530
+ started: boolean;
531
+ }
532
+
533
+ /**
534
+ * Folds stream chunks: text, tool calls (in order of first fragment,
535
+ * arguments concatenated), finish, usage. With `events`
536
+ * ({@link Request.streamEvents}), {@link Accumulator.add} also yields
537
+ * tool-call events and usage snapshots: a call starts on the fragment
538
+ * that completes its id and name (argument fragments before that follow
539
+ * the start as one delta), then a delta per arguments fragment; every
540
+ * open call ends, in index order, when a choice finishes. A finished
541
+ * choice's calls are closed: later fragments are not folded.
542
+ */
543
+ class Accumulator {
544
+ private text = "";
545
+ private finish = "";
546
+ private usage: WireUsage | undefined;
547
+ private calls: PartialCall[] = [];
548
+ private byWire = new Map<number, number>();
549
+
550
+ constructor(
551
+ private readonly names: ToolNames,
552
+ private readonly events: boolean
553
+ ) {}
554
+
555
+ /** Folds `c`; returns the tokens it yields: text, then tool-call events, then usage. */
556
+ add(c: WireChunk): Token[] {
557
+ const out: Token[] = [];
558
+ const choice = c.choices?.[0];
559
+ if (choice) {
560
+ const content = choice.delta?.content ?? "";
561
+ if (content) {
562
+ this.text += content;
563
+ out.push({ content, done: false });
564
+ }
565
+ if (!this.finish) {
566
+ for (const d of choice.delta?.tool_calls ?? []) this.fragment(d, out);
567
+ }
568
+ if (choice.finish_reason && !this.finish) {
569
+ this.finish = choice.finish_reason;
570
+ this.endCalls(out);
571
+ }
572
+ }
573
+ if (c.usage) {
574
+ this.usage = c.usage;
575
+ if (this.events) out.push({ content: "", done: false, usage: usageOf(c.usage) });
576
+ }
577
+ return out;
578
+ }
579
+
580
+ private fragment(d: WireToolCall, out: Token[]): void {
581
+ const wire = d.index ?? this.calls.length;
582
+ let i = this.byWire.get(wire);
583
+ if (i === undefined) {
584
+ i = this.calls.length;
585
+ this.byWire.set(wire, i);
586
+ this.calls.push({ wire, id: "", name: "", args: "", pending: "", started: false });
587
+ }
588
+ const cur = this.calls[i]!;
589
+ if (!cur.id) cur.id = d.id ?? "";
590
+ if (!cur.name) cur.name = d.function?.name ?? "";
591
+ const frag = d.function?.arguments ?? "";
592
+ cur.args += frag;
593
+ if (!this.events) return;
594
+ if (!cur.started) {
595
+ cur.pending += frag;
596
+ if (cur.id && cur.name) this.start(i, cur, out);
597
+ return;
598
+ }
599
+ if (frag) {
600
+ out.push({ content: "", done: false, toolCall: { kind: "delta", index: i, argumentsDelta: frag } });
601
+ }
602
+ }
603
+
604
+ private start(i: number, cur: PartialCall, out: Token[]): void {
605
+ cur.started = true;
606
+ out.push({
607
+ content: "",
608
+ done: false,
609
+ toolCall: { kind: "start", index: i, id: cur.id, name: this.names.original(cur.name) },
610
+ });
611
+ if (cur.pending) {
612
+ out.push({
613
+ content: "",
614
+ done: false,
615
+ toolCall: { kind: "delta", index: i, argumentsDelta: cur.pending },
616
+ });
617
+ cur.pending = "";
618
+ }
619
+ }
620
+
621
+ /** Closes every open call, in index order; a call that never got its id or name starts first. */
622
+ private endCalls(out: Token[]): void {
623
+ if (!this.events) return;
624
+ const order = this.calls.map((_, i) => i).sort((a, b) => this.calls[a]!.wire - this.calls[b]!.wire);
625
+ for (const i of order) {
626
+ const cur = this.calls[i]!;
627
+ if (!cur.started) this.start(i, cur, out);
628
+ const call = this.call(cur);
629
+ out.push({
630
+ content: "",
631
+ done: false,
632
+ toolCall: { kind: "end", index: i, id: call.id, name: call.name, call },
633
+ });
634
+ }
635
+ }
636
+
637
+ private call(c: PartialCall): ToolCall {
638
+ return { id: c.id, name: this.names.original(c.name), arguments: parseArguments(c.args) };
639
+ }
640
+
641
+ finished(): boolean {
642
+ return this.finish !== "";
643
+ }
644
+
645
+ outcome(): StreamOutcome {
646
+ return {
647
+ content: this.text,
648
+ thinking: [],
649
+ toolCalls: this.calls.map((c) => this.call(c)),
650
+ finishReason: this.finish,
651
+ usage: usageOf(this.usage),
652
+ };
653
+ }
654
+ }
655
+
656
+ // ─── Errors ──────────────────────────────────────────────────────────────────
657
+
658
+ function mapErrorResponse(
659
+ r: ErrorResponse,
660
+ label: string,
661
+ scheme: string,
662
+ model: string
663
+ ): Error {
664
+ let e: { type?: string; message?: string } = {};
665
+ try {
666
+ e = (JSON.parse(r.body) as { error?: typeof e }).error ?? {};
667
+ } catch {
668
+ // not a JSON error body
669
+ }
670
+ const detail =
671
+ e.message !== undefined ? `${e.type ?? "error"}: ${e.message}` : r.body.slice(0, 2048);
672
+ const message = `${label}: ${r.status} ${detail}`.trim();
673
+ const api = new APIError(scheme, r.status, e.type ?? "", message);
674
+ switch (r.status) {
675
+ case 401:
676
+ return new AuthError(scheme, api);
677
+ case 403:
678
+ return new PermissionDeniedError(scheme, api);
679
+ case 429:
680
+ return new RateLimitError(scheme);
681
+ case 404:
682
+ return new ModelError(model, scheme);
683
+ }
684
+ if (r.status >= 500) return new HTTPStatusError(r.status, message);
685
+ return api;
686
+ }
687
+
688
+ // ─── Registration ────────────────────────────────────────────────────────────
689
+
690
+ function openaiFactory(cfg: ResolvedConfig): Provider {
691
+ // loadConfig resolved and guarded the key.
692
+ const a = new OpenAIAdapter(cfg);
693
+ return {
694
+ complete: (req) => a.complete(req),
695
+ stream: (req) => a.stream(req),
696
+ callWithTools: (req, tools) => a.callWithTools(req, tools),
697
+ streamWithTools: (req, tools) => a.streamWithTools(req, tools),
698
+ close: () => a.close(),
699
+ };
700
+ }
701
+
702
+ for (const s of OPENAI_SCHEMES) {
703
+ register(s, openaiFactory, {
704
+ endpoints: [OPENAI_BASE_URLS[s] ?? OPENAI_DEFAULT_BASE_URL],
705
+ // LM Studio's local server takes no key: none is resolved for it.
706
+ ...(s === "lmstudio" ? { key: { envVars: [], optional: true } } : {}),
707
+ });
708
+ }