@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,1069 @@
1
+ /**
2
+ * Base error of the llm layer. Lives apart from `llm.ts` so modules
3
+ * that `llm.ts` re-exports can extend it without an import cycle.
4
+ * Import it from `@hop-top/kit/llm`.
5
+ *
6
+ * @internal
7
+ */
8
+ declare class LLMError extends Error {
9
+ statusCode?: number;
10
+ code?: string;
11
+ constructor(message: string);
12
+ }
13
+
14
+ /**
15
+ * Typed errors the HTTP adapters return, re-exported from
16
+ * `@hop-top/kit/llm`. Apart from `llm.ts` so the adapters' transport
17
+ * can raise them without an import cycle.
18
+ *
19
+ * @internal
20
+ */
21
+
22
+ /**
23
+ * An HTTP error response kit classifies by status: a 5xx (fallbackable)
24
+ * or a redirect, which is never followed.
25
+ */
26
+ declare class HTTPStatusError extends LLMError {
27
+ readonly status: string;
28
+ constructor(statusCode: number, status: string);
29
+ }
30
+ /**
31
+ * A provider error response no other class covers (a 4xx such as an
32
+ * invalid request). `type` is the provider's error type, when it gave
33
+ * one. Not fallbackable.
34
+ */
35
+ declare class APIError extends LLMError {
36
+ readonly provider: string;
37
+ readonly type: string;
38
+ constructor(provider: string, statusCode: number, type: string, message: string);
39
+ }
40
+ /**
41
+ * A stream ended before the provider's terminal event: the response is
42
+ * incomplete, never a success. Not fallbackable: tokens may already
43
+ * have been consumed.
44
+ */
45
+ declare class StreamTruncatedError extends LLMError {
46
+ readonly provider: string;
47
+ constructor(provider: string);
48
+ }
49
+ /**
50
+ * A response body, or one streamed event, exceeded its size limit
51
+ * (`max_body_bytes`, `max_event_bytes`). Not fallbackable.
52
+ */
53
+ declare class ResponseTooLargeError extends LLMError {
54
+ readonly provider: string;
55
+ /** The part that overran: `"body"` or `"event"`. */
56
+ readonly what: "body" | "event";
57
+ readonly limit: number;
58
+ constructor(provider: string, what: "body" | "event", limit: number);
59
+ }
60
+ /**
61
+ * A provider key kit will not send to an endpoint. `endpoint` is masked
62
+ * by `redactURI`; the key never appears.
63
+ */
64
+ declare class KeyEndpointError extends LLMError {
65
+ readonly scheme: string;
66
+ readonly endpoint: string;
67
+ /** Set when the refusal is plain http to a remote host. */
68
+ readonly insecure: boolean;
69
+ /**
70
+ * Set when the endpoint carries userinfo, a backslash, a
71
+ * percent-escape, whitespace or a control character, or does not
72
+ * parse: no credential goes to it.
73
+ */
74
+ readonly malformed: boolean;
75
+ constructor(scheme: string, endpoint: string, opts?: {
76
+ insecure?: boolean;
77
+ malformed?: boolean;
78
+ });
79
+ }
80
+ /**
81
+ * No key was found for a scheme whose adapter requires one. Carries
82
+ * names only, never a value: `envVars` lists every variable consulted,
83
+ * highest precedence first, ending with `LLM_API_KEY`.
84
+ */
85
+ declare class MissingKeyError extends LLMError {
86
+ readonly scheme: string;
87
+ readonly model: string;
88
+ readonly envVars: string[];
89
+ constructor(scheme: string, model: string, envVars: string[]);
90
+ }
91
+
92
+ /**
93
+ * The guarded fetch behind `urlSource(url).read()`.
94
+ *
95
+ * A media URL may come from untrusted input, so the fetch refuses what
96
+ * would make it a server-side request forgery or a local file read:
97
+ *
98
+ * - `http` and `https` only (no `file:`, `ftp:`, `data:`), no userinfo;
99
+ * - every address the host resolves to must be public: loopback,
100
+ * private, link-local (cloud metadata `169.254.169.254` among them),
101
+ * shared, documentation, reserved, unspecified and multicast
102
+ * addresses are refused, v4-mapped and NAT64 IPv6 judged by their
103
+ * IPv4;
104
+ * - the socket connects to an address the check passed (the lookup
105
+ * handed to `node:http` is the vetted one), so a second DNS answer
106
+ * cannot rebind it; TLS still verifies the host name;
107
+ * - no proxy, no redirects (a 3xx is an `HTTPStatusError`); a non-2xx
108
+ * status is an error;
109
+ * - the body is capped ({@link DEFAULT_MAX_MEDIA_BYTES}, or `maxBytes`),
110
+ * 30s for the whole download;
111
+ * - the `--offline` policy (`netpolicy`) applies.
112
+ *
113
+ * Errors name the destination without query or userinfo. There is no
114
+ * switch to allow private hosts: media on a local or private host is
115
+ * read by the caller and passed as `inlineSource` or `fileSource`.
116
+ *
117
+ * @internal
118
+ */
119
+
120
+ /** A URL media download is capped at this many bytes unless told otherwise: 32 MiB. */
121
+ declare const DEFAULT_MAX_MEDIA_BYTES: number;
122
+ /**
123
+ * A URL media source refused to fetch its URL: a scheme other than
124
+ * http(s), userinfo, no host, or an address that is not public.
125
+ * `destination` is the URL without query or userinfo.
126
+ */
127
+ declare class MediaURLRefusedError extends LLMError {
128
+ readonly destination: string;
129
+ readonly reason: string;
130
+ constructor(destination: string, reason: string);
131
+ }
132
+ /** Media over its size limit. */
133
+ declare class MediaTooLargeError extends LLMError {
134
+ readonly size: number;
135
+ readonly limit: number;
136
+ readonly provider: string;
137
+ constructor(size: number, limit: number, provider: string);
138
+ }
139
+ /**
140
+ * Whether addr (an IPv4 or IPv6 literal) is a globally routable unicast
141
+ * address. A v4-mapped or NAT64 (64:ff9b::/96) address is judged by the
142
+ * IPv4 address it carries. Mirrors Go's guard.
143
+ */
144
+ declare function isPublicAddress(addr: string): boolean;
145
+
146
+ /**
147
+ * Tool-name rules, the reversible sanitizer and the per-request name
148
+ * table, re-exported from `@hop-top/kit/llm`.
149
+ *
150
+ * Providers restrict tool names; callers use ids such as `pane.open`.
151
+ * A tool-calling adapter builds a {@link ToolNames} per request, sends
152
+ * wire names and returns the caller's names. Normative spec, shared by
153
+ * every kit SDK: `contracts/llm-v1/tool-names.md`.
154
+ */
155
+
156
+ /** Provider param selecting the {@link ToolNameMode}: `?tool_names=strict`. */
157
+ declare const TOOL_NAMES_PARAM = "tool_names";
158
+ /**
159
+ * How an adapter treats a name its provider does not accept.
160
+ * `sanitize` (default) rewrites it and maps it back; `strict` sends
161
+ * names as given and fails an invalid one before sending.
162
+ */
163
+ type ToolNameMode = "sanitize" | "strict";
164
+ /** Why a {@link ToolNameError} fails a request. */
165
+ type ToolNameReason = "empty" | "invalid_utf8" | "invalid" | "duplicate" | "collision";
166
+ /**
167
+ * A provider's tool-name rule: 1 to `maxLen` bytes of ASCII letters,
168
+ * digits, `_`, `-` and the bytes of `extra`; with `leadLetter`, the
169
+ * first byte is a letter or `_`.
170
+ */
171
+ interface ToolNameRule {
172
+ /** Names the rule in errors. */
173
+ readonly provider: string;
174
+ readonly maxLen: number;
175
+ readonly extra: string;
176
+ readonly leadLetter: boolean;
177
+ }
178
+ /** Anthropic Messages API: `^[a-zA-Z0-9_-]{1,128}$`. */
179
+ declare const ANTHROPIC_TOOL_NAMES: ToolNameRule;
180
+ /** OpenAI Chat Completions and compatible servers: `^[a-zA-Z0-9_-]{1,64}$`. */
181
+ declare const OPENAI_TOOL_NAMES: ToolNameRule;
182
+ /** Gemini `FunctionDeclaration.name`: `^[a-zA-Z_][a-zA-Z0-9_.:-]{0,127}$`. */
183
+ declare const GEMINI_TOOL_NAMES: ToolNameRule;
184
+ /**
185
+ * A tool name fails the request before anything is sent. Not
186
+ * fallbackable: the caller's tool set needs fixing. `toolName` is the
187
+ * offending name (`name` is the error class name, as on every Error);
188
+ * `other` is the earlier tool a `collision` maps to the same wire name.
189
+ */
190
+ declare class ToolNameError extends LLMError {
191
+ readonly provider: string;
192
+ readonly reason: ToolNameReason;
193
+ readonly toolName: string;
194
+ readonly other: string;
195
+ constructor(provider: string, reason: ToolNameReason, toolName: string, other?: string);
196
+ }
197
+ /**
198
+ * Reads {@link TOOL_NAMES_PARAM} from provider params; absent means
199
+ * `sanitize`. Any other value throws, failing adapter construction.
200
+ */
201
+ declare function toolNameModeOf(params: Record<string, string> | undefined): ToolNameMode;
202
+ /** Reports whether the provider accepts `name` as is. */
203
+ declare function isValidToolName(rule: ToolNameRule, name: string): boolean;
204
+ /**
205
+ * Returns `name` as the provider accepts it; a valid name comes back
206
+ * unchanged. Otherwise, over the UTF-8 bytes of `name`: each maximal
207
+ * run of disallowed bytes becomes one `_`; with `leadLetter`, a bad
208
+ * first byte gains a leading `_`; a result over `maxLen`, or with no
209
+ * ASCII letter or digit, keeps its first `maxLen - 9` bytes and gains
210
+ * `_` + 8 hex of SHA-256(name). Throws {@link ToolNameError} for an
211
+ * empty name (`empty`) or a lone surrogate (`invalid_utf8`).
212
+ */
213
+ declare function sanitizeToolName(rule: ToolNameRule, name: string): string;
214
+ /**
215
+ * One request's tool names: original -> wire and back. Adapters build
216
+ * one per request with {@link ToolNames.build}, send
217
+ * {@link ToolNames.wire} names (tools and replayed history) and return
218
+ * calls through {@link ToolNames.calls}.
219
+ */
220
+ declare class ToolNames {
221
+ readonly rule: ToolNameRule;
222
+ readonly mode: ToolNameMode;
223
+ private readonly toWire;
224
+ private readonly toOrig;
225
+ private constructor();
226
+ /**
227
+ * Checks `defs` against `rule` and builds their mapping. The first
228
+ * failing def, in order, throws a {@link ToolNameError}: `empty`,
229
+ * `invalid_utf8`, `invalid` (strict only), `duplicate`, `collision`
230
+ * (`other` names the earlier def with the same wire name).
231
+ */
232
+ static build(rule: ToolNameRule, mode: ToolNameMode, defs: ReadonlyArray<{
233
+ readonly name: string;
234
+ }>): ToolNames;
235
+ /**
236
+ * The name to send: a def's wire name; otherwise, as for a call
237
+ * replayed from history, `name` sanitized (`sanitize`) or unchanged
238
+ * (`strict`, or a name the sanitizer refuses).
239
+ */
240
+ wire(name: string): string;
241
+ /** The def name a returned wire name stands for; unknown names pass through. */
242
+ original(wire: string): string;
243
+ /** `defs` with each name replaced by its wire name; input untouched. */
244
+ defs<T extends {
245
+ name: string;
246
+ }>(defs: ReadonlyArray<T>): T[];
247
+ /** `calls` with each name replaced by its original; input untouched. */
248
+ calls<T extends {
249
+ name: string;
250
+ }>(calls: ReadonlyArray<T>): T[];
251
+ }
252
+
253
+ /**
254
+ * Where credentials may go: URI redaction, endpoint parsing, the
255
+ * plain-http and trusted-origin gates, and adapter declarations.
256
+ * Re-exported from `@hop-top/kit/llm`; mirrors Go `llm` (`RedactURI`,
257
+ * `CheckKeyEndpoint`, `CredentialsTrusted`).
258
+ *
259
+ * @internal
260
+ */
261
+ /**
262
+ * Masks the credentials in a provider URI or URL: the value of every
263
+ * credential-named query param (`api_key`, `key`, `*_token`, ...) and
264
+ * userinfo before an `@`. Tolerates malformed input; a `name@version`
265
+ * model id is kept.
266
+ */
267
+ declare function redactURI(raw: string): string;
268
+ /**
269
+ * Throws a {@link KeyEndpointError} for a non-blank `key` bound for a
270
+ * malformed endpoint, or over plain http to a host other than loopback.
271
+ * Adapters call it on the base URL they settle on.
272
+ */
273
+ declare function checkKeyEndpoint(scheme: string, key: string | undefined, baseURL: string): void;
274
+ /**
275
+ * A scheme's credential: the variables holding its key, highest
276
+ * precedence first. `optional` marks a key a provider runs without
277
+ * (a local runtime): `LLM_API_KEY` is then not lent to it. No
278
+ * `envVars` and `optional` is a scheme that takes no key at all.
279
+ */
280
+ interface ProviderKey {
281
+ envVars: string[];
282
+ optional?: boolean;
283
+ }
284
+ /**
285
+ * What an adapter states about its scheme: the endpoints credentials
286
+ * kit resolved itself may go to (see {@link credentialsTrusted}), and
287
+ * its credential when the `<SCHEME>_API_KEY` convention does not fit.
288
+ */
289
+ interface Declaration {
290
+ endpoints?: string[];
291
+ key?: ProviderKey;
292
+ }
293
+ /** The declaration `scheme` registered with, if any. */
294
+ declare function declarationOf(scheme: string): Declaration | undefined;
295
+ /**
296
+ * Reports whether credentials kit resolved itself, not taken from the
297
+ * URI (an env or llm.yaml key, a bearer token, a workspace header), may
298
+ * go to `baseURL` for `scheme`: it is loopback, or shares an origin
299
+ * with the scheme's declared endpoints, its llm.yaml `base_url`,
300
+ * `LLM_BASE_URL` or one of `extra` (the adapter's default endpoint and
301
+ * its own base URL variable). Every credential path decides here.
302
+ */
303
+ declare function credentialsTrusted(scheme: string, baseURL: string, ...extra: string[]): boolean;
304
+
305
+ /**
306
+ * Config loading: llm.yaml, the environment and the URI merged as Go
307
+ * `llm.LoadConfig` merges them. Re-exported from `@hop-top/kit/llm`.
308
+ *
309
+ * @internal
310
+ */
311
+
312
+ /** Options for {@link loadConfig}, `resolve` and `createLLM`. */
313
+ interface LoadOptions {
314
+ /**
315
+ * Reads nothing ambient: the provider comes from the URI alone
316
+ * (`api_key`, `base_url`, host). No llm.yaml, no `LLM_PROVIDER`,
317
+ * `LLM_FALLBACK`, `LLM_API_KEY`, `LLM_BASE_URL` or `<SCHEME>_API_KEY`,
318
+ * and the adapter gets {@link ResolvedConfig.hermetic}, so it reads no
319
+ * environment variable either. For embedding kit in an app that owns
320
+ * its configuration.
321
+ */
322
+ hermetic?: boolean;
323
+ }
324
+ /**
325
+ * Builds the {@link ResolvedConfig} for `uriStr` from llm.yaml
326
+ * (`{configDir("hop")}/llm.yaml`), the environment and the URI, the
327
+ * URI highest. Each field, highest precedence first:
328
+ *
329
+ * - URI: `uriStr`; `LLM_PROVIDER`; llm.yaml `default`. None throws.
330
+ * - apiKey: the URI's `api_key`; llm.yaml `providers.<scheme>.api_key`,
331
+ * then the variable its `api_key_env` names; the scheme's key
332
+ * variables (`<SCHEME>_API_KEY` unless its adapter declares others);
333
+ * `LLM_API_KEY` for a registered scheme that requires a key. Blank is
334
+ * unset everywhere; a blank `api_key` param is dropped. Found
335
+ * nowhere, it is left unset: the adapter reports it.
336
+ * - baseURL: the URI's `base_url`; its host (`http://host:port`);
337
+ * `LLM_BASE_URL`; llm.yaml `base_url`.
338
+ * - model: the URI's; llm.yaml `model`. extras: the block's other keys.
339
+ * - fallbacks: `LLM_FALLBACK` (comma-separated); llm.yaml `fallback`.
340
+ *
341
+ * Throws a {@link KeyEndpointError} when the key may not go where the
342
+ * config points: a key not from the URI to an endpoint only the URI
343
+ * names unless loopback or trusted (declared, llm.yaml `base_url`,
344
+ * `LLM_BASE_URL`); any key over plain http to a remote host.
345
+ *
346
+ * With `opts.hermetic` the config is the URI alone (see
347
+ * {@link LoadOptions}).
348
+ */
349
+ declare function loadConfig(uriStr?: string, opts?: LoadOptions): ResolvedConfig;
350
+
351
+ /**
352
+ * Provider URI parsing, as Go `llm.ParseURI` parses (pinned by
353
+ * contracts/llm-v1 `parse_uri`). Re-exported from `@hop-top/kit/llm`.
354
+ *
355
+ * @internal
356
+ */
357
+
358
+ /**
359
+ * Parses a provider URI: `scheme://[host:port/]model[?params]`.
360
+ *
361
+ * The scheme is required; the model may be empty. The first path
362
+ * segment is a host (`ollama://localhost:11434/llama3`,
363
+ * `ollama://[::1]:11434/llama3`) when it splits as `host:port` with a
364
+ * non-empty port; otherwise the whole path is the model
365
+ * (`openrouter://openai/gpt-4.1-nano`). The query splits on `&`, each
366
+ * pair on its first `=`, and is not percent-decoded; a param without
367
+ * `=` is `""`, one with an empty name is dropped. `params` is absent
368
+ * when none is left.
369
+ *
370
+ * Throws an {@link LLMError} (`empty URI`, `missing scheme in URI
371
+ * "..."`, `empty scheme in URI "..."`) quoting `raw` with its
372
+ * credentials masked by {@link redactURI}.
373
+ */
374
+ declare function parseURI(raw: string): URI;
375
+
376
+ /**
377
+ * Provider key resolution and the gate that keeps a key kit resolved
378
+ * itself off an endpoint only the URI names. Mirrors Go `llm`
379
+ * (`ResolveAPIKey`, `ApplyAPIKey`, the key-endpoint guard) without a
380
+ * secret store.
381
+ *
382
+ * @internal
383
+ */
384
+
385
+ /**
386
+ * Returns `uri` with the provider's key set as its `api_key` param,
387
+ * resolved as {@link loadConfig} resolves it, after the same endpoint
388
+ * guard. `uri` comes back unchanged when it carries a non-blank
389
+ * `api_key` (a blank one is removed first), when its scheme takes no
390
+ * key, and when no adapter serves the scheme and its llm.yaml block
391
+ * names none. A required key found nowhere throws a
392
+ * {@link MissingKeyError}. Go `ApplyAPIKey` without a secret store.
393
+ *
394
+ * The result holds the key: never log it. Errors never carry it.
395
+ */
396
+ declare function applyAPIKey(uri: string): string;
397
+
398
+ /**
399
+ * Metadata-only payloads for the llm lifecycle events
400
+ * `kit.ai.request.started` and `kit.ai.response.received`, as the Go
401
+ * client publishes them. Re-exported from `@hop-top/kit/llm`.
402
+ *
403
+ * The TypeScript client publishes no bus events: its `onRequest` and
404
+ * `onResponse` hooks run in process with the full request and response.
405
+ * A caller that forwards those events (to a bus, a log, a peer) builds
406
+ * the payload here instead of sending the request, so no prompt text,
407
+ * tool name or argument, extension value or media leaves the process.
408
+ */
409
+
410
+ /** The call a payload describes. */
411
+ type CallOp = "complete" | "stream" | "tool_call" | "stream_tools";
412
+ /**
413
+ * `kit.ai.request.started`: a request described without its content.
414
+ * Keys are the wire spelling; optional ones are absent when empty.
415
+ */
416
+ interface RequestStartedPayload {
417
+ op: CallOp;
418
+ /** {@link Request.model}; absent means the adapter's own. */
419
+ model?: string;
420
+ messages: number;
421
+ /** Messages counted by role. */
422
+ roles?: Record<string, number>;
423
+ /** Content parts of multimodal messages counted by type. */
424
+ parts?: Record<string, number>;
425
+ /**
426
+ * UTF-8 length of the messages' text: content, text parts, tool call
427
+ * arguments and thinking text. Media is not counted.
428
+ */
429
+ content_bytes: number;
430
+ /** Tools offered (`tool_call`, `stream_tools`). */
431
+ tools: number;
432
+ max_tokens: number;
433
+ has_temperature: boolean;
434
+ thinking: boolean;
435
+ stop_sequences: number;
436
+ /** {@link Request.extensions} keys, sorted; never their values. */
437
+ extension_keys?: string[];
438
+ }
439
+ /** `kit.ai.response.received`: a finished call without its content. */
440
+ interface ResponseReceivedPayload {
441
+ op: CallOp;
442
+ finish_reason?: string;
443
+ usage: {
444
+ prompt_tokens: number;
445
+ completion_tokens: number;
446
+ cache_read_tokens: number;
447
+ cache_creation_tokens: number;
448
+ total_tokens: number;
449
+ };
450
+ /**
451
+ * UTF-8 length of the response's text: content, tool call arguments
452
+ * and thinking text.
453
+ */
454
+ content_bytes: number;
455
+ /** Calls the model made (`tool_call`). */
456
+ tool_calls: number;
457
+ /** Whole milliseconds the call took. */
458
+ duration_ms: number;
459
+ }
460
+ /**
461
+ * The `kit.ai.request.started` payload for `req` on a call of kind
462
+ * `op` offering `tools` tools.
463
+ */
464
+ declare function requestStartedPayload(op: CallOp, req: Request, tools: number): RequestStartedPayload;
465
+ /**
466
+ * The `kit.ai.response.received` payload for `resp`, with the calls the
467
+ * model made (`tool_call`), after `durationMs`.
468
+ */
469
+ declare function responseReceivedPayload(op: CallOp, resp: Response, toolCalls: readonly ToolCall[], durationMs: number): ResponseReceivedPayload;
470
+
471
+ /**
472
+ * @packageDocumentation
473
+ *
474
+ * LLM client facade — mirrors Go `llm` package interfaces as TS types.
475
+ *
476
+ * Provides URI parsing, config loading, provider registry, Client facade
477
+ * with fallback, and typed errors. Adapters register their URI schemes
478
+ * on import: `@hop-top/kit/anthropic` (`anthropic://`),
479
+ * `@hop-top/kit/openai` (`openai://` and OpenAI-compatible schemes)
480
+ * and `@hop-top/kit/routellm`. Register your own via {@link register}.
481
+ *
482
+ * @example
483
+ * ```ts
484
+ * import { createLLM, register } from '@hop-top/kit/llm';
485
+ *
486
+ * register('mock', (cfg) => ({ complete: async (r) => ({ content: 'hi', role: 'assistant' }), close() {} }));
487
+ * const client = createLLM('mock://model-1');
488
+ * const resp = await client.complete({ messages: [{ role: 'user', content: 'hello' }] });
489
+ * ```
490
+ */
491
+
492
+ /** Classifies a content part in a multimodal message. */
493
+ type PartType = "text" | "image" | "audio" | "video";
494
+ /**
495
+ * Binary media input for a {@link ContentPart}.
496
+ *
497
+ * Built by {@link inlineSource}, {@link urlSource} or {@link fileSource}.
498
+ */
499
+ interface MediaSource {
500
+ /** Non-empty when the source is URL-backed. */
501
+ url(): string;
502
+ /** Inferred MIME type, or `""`. */
503
+ mimeType(): string;
504
+ /** Reads the media bytes. */
505
+ read(): Promise<Uint8Array>;
506
+ }
507
+ /**
508
+ * A single typed element within a multimodal message.
509
+ *
510
+ * Rule: if a {@link Message} has non-empty `parts`, they are used
511
+ * instead of its `content`.
512
+ */
513
+ interface ContentPart {
514
+ type: PartType;
515
+ text?: string;
516
+ source?: MediaSource;
517
+ mimeType?: string;
518
+ metadata?: Record<string, unknown>;
519
+ }
520
+ /**
521
+ * A single role+content pair in a conversation.
522
+ *
523
+ * Multimodal rule: non-empty `parts` take precedence over `content`.
524
+ *
525
+ * Tool-call linkage: an agentic loop replays a tool round as two kinds
526
+ * of message.
527
+ *
528
+ * - Role `"assistant"` with `toolCalls`: the calls the model made,
529
+ * copied from {@link ToolResponse.toolCalls}. `content` carries any
530
+ * text the model produced alongside them and may be `""`.
531
+ * - Role `"tool"` with `toolCallId`: one tool's result, in `content`.
532
+ * `toolCallId` equals the {@link ToolCall.id} it answers. Send one
533
+ * message per call.
534
+ *
535
+ * `toolCalls` is valid only on role `"assistant"` and `toolCallId` only
536
+ * on role `"tool"`; adapters reject either field on any other role, a
537
+ * tool result carrying `parts`, and linkage the provider cannot express,
538
+ * rather than degrading it to plain text ({@link checkToolLinkage}).
539
+ * Messages that set neither field map exactly as before.
540
+ */
541
+ interface Message {
542
+ role: string;
543
+ content: string;
544
+ parts?: ContentPart[];
545
+ /** Tool invocations of an assistant turn. */
546
+ toolCalls?: ToolCall[];
547
+ /** Links a role `"tool"` result to the {@link ToolCall} it answers. */
548
+ toolCallId?: string;
549
+ /**
550
+ * Replays an assistant turn's thinking blocks, exactly as the provider
551
+ * returned them ({@link Response.thinking}, {@link ToolResponse.thinking}
552
+ * or {@link StreamOutcome.thinking}). Required with tool use when
553
+ * thinking is enabled. Assistant only.
554
+ */
555
+ thinking?: ThinkingBlock[];
556
+ /**
557
+ * Marks a prompt-cache breakpoint after this message: on a system
558
+ * message its text, otherwise its last content block.
559
+ */
560
+ cacheControl?: CacheControl;
561
+ }
562
+ /**
563
+ * One block of a model's extended thinking. `signature` verifies
564
+ * `thinking`; a redacted block carries only `redacted`, the provider's
565
+ * opaque data. Pass blocks back exactly as received.
566
+ */
567
+ interface ThinkingBlock {
568
+ thinking: string;
569
+ signature: string;
570
+ redacted: string;
571
+ }
572
+ /**
573
+ * A prompt-cache breakpoint. `ttl` is `""` or absent (the provider
574
+ * default, five minutes on Anthropic), `"5m"` or `"1h"`.
575
+ */
576
+ interface CacheControl {
577
+ ttl?: string;
578
+ }
579
+ /**
580
+ * Enables extended thinking with a token budget, which must be below
581
+ * the request's max tokens.
582
+ */
583
+ interface ThinkingConfig {
584
+ budgetTokens: number;
585
+ }
586
+ interface Request {
587
+ messages: Message[];
588
+ model?: string;
589
+ temperature?: number;
590
+ maxTokens?: number;
591
+ stopSequences?: string[];
592
+ extensions?: Record<string, unknown>;
593
+ /** Enables extended thinking; thinking deltas then stream as {@link Token.thinking}. */
594
+ thinking?: ThinkingConfig;
595
+ /**
596
+ * Makes a stream also yield incremental tool-call events
597
+ * ({@link Token.toolCall}) and usage snapshots ({@link Token.usage}).
598
+ * Unset, a stream yields exactly the tokens it always has. Ignored by
599
+ * `complete` and `callWithTools`.
600
+ */
601
+ streamEvents?: boolean;
602
+ /**
603
+ * Constrains tool use on a tool-calling request (`callWithTools`,
604
+ * `streamWithTools`); unset leaves the provider default. See
605
+ * {@link ToolChoice}.
606
+ */
607
+ toolChoice?: ToolChoice;
608
+ }
609
+ /** Whether the model must call a tool. */
610
+ type ToolChoiceMode = "auto" | "any" | "none" | "tool";
611
+ /**
612
+ * Constrains tool use: `auto` lets the model decide (the providers'
613
+ * default), `any` makes it call at least one tool of its pick, `none`
614
+ * forbids tool calls although tools are defined, `tool` makes it call
615
+ * the tool `name`: its {@link ToolDef.name} as defined, before any
616
+ * provider name mapping. Set `name` with mode `tool` only.
617
+ *
618
+ * Adapters reject an invalid choice ({@link checkToolChoice}) before
619
+ * sending, and so does a call without tools (`complete`, `stream`).
620
+ */
621
+ interface ToolChoice {
622
+ mode: ToolChoiceMode;
623
+ name?: string;
624
+ }
625
+ /**
626
+ * Throws an {@link LLMError} saying why `c` cannot go with `tools`: a
627
+ * mode that is not a {@link ToolChoiceMode}, no tools, a name missing
628
+ * with mode `tool` or set with another mode, or naming no tool in
629
+ * `tools`. Undefined `c` is valid. Adapters prefix the message with
630
+ * their scheme.
631
+ */
632
+ declare function checkToolChoice(c: ToolChoice | undefined, tools: ReadonlyArray<{
633
+ name: string;
634
+ }>): void;
635
+ interface Response {
636
+ content: string;
637
+ role: string;
638
+ usage?: Usage;
639
+ finishReason?: string;
640
+ /** The turn's thinking blocks, to replay unchanged. */
641
+ thinking?: ThinkingBlock[];
642
+ }
643
+ interface Usage {
644
+ promptTokens: number;
645
+ completionTokens: number;
646
+ /**
647
+ * Input tokens read from or written to the prompt cache, apart from
648
+ * `promptTokens`.
649
+ */
650
+ cacheReadTokens?: number;
651
+ cacheCreationTokens?: number;
652
+ /** Every input and output token, cache ones included. */
653
+ totalTokens: number;
654
+ }
655
+ /** A model's rate per million tokens, by kind. */
656
+ interface Price {
657
+ input: number;
658
+ output: number;
659
+ cacheRead: number;
660
+ cacheWrite: number;
661
+ }
662
+ /** Cost of `u` at `p`, cache reads and writes at their own rates. */
663
+ declare function usageCost(u: Usage, p: Price): number;
664
+ /**
665
+ * A single streaming chunk. The final token has `done: true`; nothing
666
+ * follows it. A token carries one thing: a text delta (`content`), a
667
+ * thinking delta (`thinking`), a tool-call event (`toolCall`), a usage
668
+ * snapshot (`usage`), or the end (`done`); `content` is `""` on all but
669
+ * a text delta.
670
+ */
671
+ interface Token {
672
+ content: string;
673
+ /**
674
+ * A thinking delta, sent only when the request enabled
675
+ * {@link Request.thinking}; `content` is then empty.
676
+ */
677
+ thinking?: string;
678
+ /**
679
+ * An incremental tool-call event, sent only when the request set
680
+ * {@link Request.streamEvents}. See {@link ToolCallEvent}.
681
+ */
682
+ toolCall?: ToolCallEvent;
683
+ /**
684
+ * The turn's usage so far, sent only when the request set
685
+ * {@link Request.streamEvents}, each time the provider reports it. A
686
+ * cumulative snapshot, never a delta: counts never go down, and the
687
+ * last one equals the finished turn's usage ({@link StreamOutcome.usage}).
688
+ */
689
+ usage?: Usage;
690
+ done: boolean;
691
+ }
692
+ /**
693
+ * The step of a streamed tool call: `start` opens it (`index`, `id`,
694
+ * `name`), `delta` carries a fragment of its JSON arguments, `end`
695
+ * closes it (`call` holds it complete).
696
+ */
697
+ type ToolCallEventKind = "start" | "delta" | "end";
698
+ /**
699
+ * One step of a tool call as it streams.
700
+ *
701
+ * For each call: one start, then any deltas, then one end, in that
702
+ * order; events of parallel calls may interleave and are told apart by
703
+ * `index`, the call's position in {@link StreamOutcome.toolCalls}. A
704
+ * call that started but never ended (the stream failed, was cancelled
705
+ * or closed) did not complete: no end event is made up for it.
706
+ */
707
+ interface ToolCallEvent {
708
+ kind: ToolCallEventKind;
709
+ index: number;
710
+ /**
711
+ * Set on start and end. `name` is the tool's name as the caller
712
+ * defined it, whatever name went over the wire.
713
+ */
714
+ id?: string;
715
+ name?: string;
716
+ /**
717
+ * A raw fragment of the arguments' JSON, on delta only; fragments
718
+ * concatenate to the complete arguments and are not valid JSON alone.
719
+ */
720
+ argumentsDelta?: string;
721
+ /**
722
+ * The complete call, on end only: exactly the entry at `index` in
723
+ * {@link StreamOutcome.toolCalls}.
724
+ */
725
+ call?: ToolCall;
726
+ }
727
+ interface ToolDef {
728
+ name: string;
729
+ description: string;
730
+ parameters: unknown;
731
+ /** Marks a prompt-cache breakpoint after this tool. */
732
+ cacheControl?: CacheControl;
733
+ }
734
+ /**
735
+ * A single tool invocation returned by the model.
736
+ *
737
+ * `id` is the handle a tool result quotes back in
738
+ * {@link Message.toolCallId}. `arguments` is the parsed JSON value, or a
739
+ * JSON-encoded string (Go's `json.RawMessage`); adapters send a string
740
+ * as is and encode anything else.
741
+ */
742
+ interface ToolCall {
743
+ id: string;
744
+ name: string;
745
+ arguments: unknown;
746
+ }
747
+ interface ToolResponse {
748
+ content: string;
749
+ toolCalls: ToolCall[];
750
+ /** The turn's thinking blocks, to replay unchanged. */
751
+ thinking?: ThinkingBlock[];
752
+ finishReason?: string;
753
+ usage?: Usage;
754
+ }
755
+ /** What a finished stream folded into. */
756
+ interface StreamOutcome {
757
+ content: string;
758
+ /** The turn's thinking blocks in order; replay them unchanged. */
759
+ thinking: ThinkingBlock[];
760
+ toolCalls: ToolCall[];
761
+ finishReason: string;
762
+ usage: Usage;
763
+ }
764
+ /**
765
+ * A token stream whose finished turn can be read back: `outcome()` is
766
+ * defined only once the final token (`done`) was yielded; after an
767
+ * error it stays undefined.
768
+ */
769
+ interface ToolStream extends AsyncIterable<Token> {
770
+ outcome(): StreamOutcome | undefined;
771
+ }
772
+ interface Completer {
773
+ complete(req: Request): Promise<Response>;
774
+ }
775
+ interface Streamer {
776
+ stream(req: Request): AsyncIterable<Token>;
777
+ }
778
+ interface ToolCaller {
779
+ callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse>;
780
+ }
781
+ /**
782
+ * Streams a tool-calling completion: text deltas as tokens, then the
783
+ * whole turn (tool calls, stop reason, usage) from
784
+ * {@link ToolStream.outcome}.
785
+ */
786
+ interface ToolStreamer {
787
+ streamWithTools(req: Request, tools: ToolDef[]): ToolStream;
788
+ }
789
+ interface Provider extends Partial<Completer & Streamer & ToolCaller & ToolStreamer> {
790
+ close(): void;
791
+ }
792
+ interface URI {
793
+ scheme: string;
794
+ model: string;
795
+ host?: string;
796
+ params?: Record<string, string>;
797
+ }
798
+ interface ProviderConfig {
799
+ apiKey?: string;
800
+ baseURL?: string;
801
+ model: string;
802
+ params?: Record<string, string>;
803
+ extras?: Record<string, unknown>;
804
+ }
805
+ interface ResolvedConfig {
806
+ uri: URI;
807
+ provider: ProviderConfig;
808
+ fallbacks: string[];
809
+ /**
810
+ * Set by the `hermetic` option ({@link LoadOptions}): the adapter
811
+ * reads nothing ambient while it builds and runs, no environment
812
+ * variable (`ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`,
813
+ * `ANTHROPIC_WORKSPACE_ID`, `<SCHEME>_API_KEY`, `ROUTELLM_*`,
814
+ * `LLM_BASE_URL`) and no llm.yaml. Only this config counts.
815
+ */
816
+ hermetic?: boolean;
817
+ }
818
+
819
+ declare class ProviderNotFoundError extends LLMError {
820
+ scheme: string;
821
+ constructor(scheme: string);
822
+ }
823
+ declare class CapabilityNotSupportedError extends LLMError {
824
+ capability: string;
825
+ provider: string;
826
+ constructor(capability: string, provider: string);
827
+ }
828
+ /**
829
+ * The provider refused the credential (HTTP 401). A 403 is the narrower
830
+ * {@link PermissionDeniedError}, still an `AuthError`.
831
+ */
832
+ declare class AuthError extends LLMError {
833
+ provider: string;
834
+ /** `cause` is the provider's error response, when there is one. */
835
+ constructor(provider: string, cause?: Error);
836
+ }
837
+ /**
838
+ * The credential was accepted but may not do what was asked (HTTP 403,
839
+ * an Anthropic `permission_error`): a key without access to the model,
840
+ * workspace or feature. Retrying with the same key will not help.
841
+ *
842
+ * It is an auth error too: `err instanceof AuthError` holds, with the
843
+ * same `provider` and `cause`, so code written before the split keeps
844
+ * treating a 403 as an auth failure. Test `PermissionDeniedError` first
845
+ * to tell the two apart.
846
+ */
847
+ declare class PermissionDeniedError extends AuthError {
848
+ constructor(provider: string, cause?: Error);
849
+ }
850
+ declare class RateLimitError extends LLMError {
851
+ provider: string;
852
+ retryAfter?: number;
853
+ constructor(provider: string, retryAfter?: number);
854
+ }
855
+ declare class ModelError extends LLMError {
856
+ model: string;
857
+ provider: string;
858
+ constructor(model: string, provider: string);
859
+ }
860
+ declare class FallbackExhaustedError extends LLMError {
861
+ errors: Error[];
862
+ constructor(errors: Error[]);
863
+ }
864
+ /**
865
+ * Returns true when `err` should trigger a fallback attempt.
866
+ *
867
+ * Fallbackable conditions:
868
+ * - LLMError with statusCode >= 500 (an {@link HTTPStatusError} from a
869
+ * 5xx response or an overloaded stream)
870
+ * - RateLimitError (429)
871
+ * - Connection/timeout errors (ECONNREFUSED, ETIMEDOUT, ECONNRESET)
872
+ *
873
+ * Never fallbackable: a {@link ToolNameError} (the caller's tool set
874
+ * needs fixing), a {@link StreamTruncatedError} (tokens may already be
875
+ * consumed), a {@link ResponseTooLargeError}, a {@link KeyEndpointError}
876
+ * and an {@link APIError} below 500.
877
+ */
878
+ declare function isFallbackable(err: Error): boolean;
879
+ /**
880
+ * Enforces the provider-independent tool-call linkage rules on one
881
+ * message: `toolCalls` only on role `"assistant"`, `toolCallId` only on
882
+ * role `"tool"`, and a tool result carries only `content` (no
883
+ * `toolCalls`, no `parts`). Throws {@link LLMError} otherwise, checking
884
+ * in the Go adapters' order. An empty `toolCalls` array counts as unset.
885
+ *
886
+ * Adapters call it before mapping a message, then add the rules their
887
+ * provider needs (for example a required `toolCallId`).
888
+ */
889
+ declare function checkToolLinkage(m: Message): void;
890
+ /** In-memory media bytes with a caller-supplied MIME type. */
891
+ declare function inlineSource(data: Uint8Array, mimeType: string): MediaSource;
892
+ /** Options for {@link urlSource}. */
893
+ interface URLSourceOptions {
894
+ /** Body cap in bytes (default {@link DEFAULT_MAX_MEDIA_BYTES}). */
895
+ maxBytes?: number;
896
+ }
897
+ /**
898
+ * URL-backed media; `read()` downloads lazily.
899
+ *
900
+ * The download is guarded against server-side request forgery: http or
901
+ * https only, public addresses only (checked on what is dialed, so DNS
902
+ * rebinding cannot redirect it), no redirects, no proxy, at most
903
+ * `maxBytes` (32 MiB by default; {@link MediaTooLargeError} past it),
904
+ * 30s, and `--offline`. Refusals are {@link MediaURLRefusedError}.
905
+ * Adapters whose provider accepts a URL (Anthropic images and PDFs,
906
+ * OpenAI images) send the URL and never read it. Local or private
907
+ * media: read it yourself and pass {@link inlineSource} or
908
+ * {@link fileSource}.
909
+ */
910
+ declare function urlSource(url: string, opts?: URLSourceOptions): MediaSource;
911
+ /**
912
+ * File on disk, read on `read()`. The MIME type comes from the
913
+ * extension (common image, PDF, audio and video types); unknown
914
+ * extensions give `""`, so set {@link ContentPart.mimeType} instead.
915
+ */
916
+ declare function fileSource(path: string): MediaSource;
917
+ type Factory = (cfg: ResolvedConfig) => Provider;
918
+
919
+ /** Register a provider factory for the given URI scheme. */
920
+ declare function register(scheme: string, factory: Factory, decl?: Declaration): void;
921
+
922
+ /**
923
+ * Resolve a URI to a Provider instance via the registry. With
924
+ * `opts.hermetic` neither the config nor the adapter reads anything
925
+ * ambient (see {@link LoadOptions}).
926
+ */
927
+ declare function resolve(uriStr: string, opts?: LoadOptions): Provider;
928
+ /** Clear the registry (for tests). */
929
+ declare function clearRegistry(): void;
930
+ interface ClientOptions extends LoadOptions {
931
+ fallback?: string[];
932
+ onRequest?: (req: Request) => void;
933
+ onResponse?: (resp: Response, durationMs: number) => void;
934
+ onError?: (err: Error) => void;
935
+ onFallback?: (from: number, to: number, err: Error) => void;
936
+ }
937
+ interface Client {
938
+ complete(req: Request): Promise<Response>;
939
+ stream(req: Request): AsyncIterable<Token>;
940
+ callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse>;
941
+ /**
942
+ * Streams a tool-calling completion; falls back like {@link stream},
943
+ * before the first token only.
944
+ */
945
+ streamWithTools(req: Request, tools: ToolDef[]): ToolStream;
946
+ capabilities(): string[];
947
+ provider(): Provider;
948
+ close(): void;
949
+ }
950
+ /**
951
+ * Create an LLM client with fallback support and event hooks.
952
+ *
953
+ * The returned Client delegates to the provider resolved from `uri`.
954
+ * On fallbackable errors, it tries each fallback URI in order.
955
+ */
956
+ declare function createLLM(uri: string, opts?: ClientOptions): Client;
957
+
958
+ declare const llm_ANTHROPIC_TOOL_NAMES: typeof ANTHROPIC_TOOL_NAMES;
959
+ type llm_APIError = APIError;
960
+ declare const llm_APIError: typeof APIError;
961
+ type llm_AuthError = AuthError;
962
+ declare const llm_AuthError: typeof AuthError;
963
+ type llm_CacheControl = CacheControl;
964
+ type llm_CallOp = CallOp;
965
+ type llm_CapabilityNotSupportedError = CapabilityNotSupportedError;
966
+ declare const llm_CapabilityNotSupportedError: typeof CapabilityNotSupportedError;
967
+ type llm_Client = Client;
968
+ type llm_ClientOptions = ClientOptions;
969
+ type llm_Completer = Completer;
970
+ type llm_ContentPart = ContentPart;
971
+ declare const llm_DEFAULT_MAX_MEDIA_BYTES: typeof DEFAULT_MAX_MEDIA_BYTES;
972
+ type llm_Declaration = Declaration;
973
+ type llm_Factory = Factory;
974
+ type llm_FallbackExhaustedError = FallbackExhaustedError;
975
+ declare const llm_FallbackExhaustedError: typeof FallbackExhaustedError;
976
+ declare const llm_GEMINI_TOOL_NAMES: typeof GEMINI_TOOL_NAMES;
977
+ type llm_HTTPStatusError = HTTPStatusError;
978
+ declare const llm_HTTPStatusError: typeof HTTPStatusError;
979
+ type llm_KeyEndpointError = KeyEndpointError;
980
+ declare const llm_KeyEndpointError: typeof KeyEndpointError;
981
+ type llm_LLMError = LLMError;
982
+ declare const llm_LLMError: typeof LLMError;
983
+ type llm_LoadOptions = LoadOptions;
984
+ type llm_MediaSource = MediaSource;
985
+ type llm_MediaTooLargeError = MediaTooLargeError;
986
+ declare const llm_MediaTooLargeError: typeof MediaTooLargeError;
987
+ type llm_MediaURLRefusedError = MediaURLRefusedError;
988
+ declare const llm_MediaURLRefusedError: typeof MediaURLRefusedError;
989
+ type llm_Message = Message;
990
+ type llm_MissingKeyError = MissingKeyError;
991
+ declare const llm_MissingKeyError: typeof MissingKeyError;
992
+ type llm_ModelError = ModelError;
993
+ declare const llm_ModelError: typeof ModelError;
994
+ declare const llm_OPENAI_TOOL_NAMES: typeof OPENAI_TOOL_NAMES;
995
+ type llm_PartType = PartType;
996
+ type llm_PermissionDeniedError = PermissionDeniedError;
997
+ declare const llm_PermissionDeniedError: typeof PermissionDeniedError;
998
+ type llm_Price = Price;
999
+ type llm_Provider = Provider;
1000
+ type llm_ProviderConfig = ProviderConfig;
1001
+ type llm_ProviderKey = ProviderKey;
1002
+ type llm_ProviderNotFoundError = ProviderNotFoundError;
1003
+ declare const llm_ProviderNotFoundError: typeof ProviderNotFoundError;
1004
+ type llm_RateLimitError = RateLimitError;
1005
+ declare const llm_RateLimitError: typeof RateLimitError;
1006
+ type llm_Request = Request;
1007
+ type llm_RequestStartedPayload = RequestStartedPayload;
1008
+ type llm_ResolvedConfig = ResolvedConfig;
1009
+ type llm_Response = Response;
1010
+ type llm_ResponseReceivedPayload = ResponseReceivedPayload;
1011
+ type llm_ResponseTooLargeError = ResponseTooLargeError;
1012
+ declare const llm_ResponseTooLargeError: typeof ResponseTooLargeError;
1013
+ type llm_StreamOutcome = StreamOutcome;
1014
+ type llm_StreamTruncatedError = StreamTruncatedError;
1015
+ declare const llm_StreamTruncatedError: typeof StreamTruncatedError;
1016
+ type llm_Streamer = Streamer;
1017
+ declare const llm_TOOL_NAMES_PARAM: typeof TOOL_NAMES_PARAM;
1018
+ type llm_ThinkingBlock = ThinkingBlock;
1019
+ type llm_ThinkingConfig = ThinkingConfig;
1020
+ type llm_Token = Token;
1021
+ type llm_ToolCall = ToolCall;
1022
+ type llm_ToolCallEvent = ToolCallEvent;
1023
+ type llm_ToolCallEventKind = ToolCallEventKind;
1024
+ type llm_ToolCaller = ToolCaller;
1025
+ type llm_ToolChoice = ToolChoice;
1026
+ type llm_ToolChoiceMode = ToolChoiceMode;
1027
+ type llm_ToolDef = ToolDef;
1028
+ type llm_ToolNameError = ToolNameError;
1029
+ declare const llm_ToolNameError: typeof ToolNameError;
1030
+ type llm_ToolNameMode = ToolNameMode;
1031
+ type llm_ToolNameReason = ToolNameReason;
1032
+ type llm_ToolNameRule = ToolNameRule;
1033
+ type llm_ToolNames = ToolNames;
1034
+ declare const llm_ToolNames: typeof ToolNames;
1035
+ type llm_ToolResponse = ToolResponse;
1036
+ type llm_ToolStream = ToolStream;
1037
+ type llm_ToolStreamer = ToolStreamer;
1038
+ type llm_URI = URI;
1039
+ type llm_URLSourceOptions = URLSourceOptions;
1040
+ type llm_Usage = Usage;
1041
+ declare const llm_applyAPIKey: typeof applyAPIKey;
1042
+ declare const llm_checkKeyEndpoint: typeof checkKeyEndpoint;
1043
+ declare const llm_checkToolChoice: typeof checkToolChoice;
1044
+ declare const llm_checkToolLinkage: typeof checkToolLinkage;
1045
+ declare const llm_clearRegistry: typeof clearRegistry;
1046
+ declare const llm_createLLM: typeof createLLM;
1047
+ declare const llm_credentialsTrusted: typeof credentialsTrusted;
1048
+ declare const llm_declarationOf: typeof declarationOf;
1049
+ declare const llm_fileSource: typeof fileSource;
1050
+ declare const llm_inlineSource: typeof inlineSource;
1051
+ declare const llm_isFallbackable: typeof isFallbackable;
1052
+ declare const llm_isPublicAddress: typeof isPublicAddress;
1053
+ declare const llm_isValidToolName: typeof isValidToolName;
1054
+ declare const llm_loadConfig: typeof loadConfig;
1055
+ declare const llm_parseURI: typeof parseURI;
1056
+ declare const llm_redactURI: typeof redactURI;
1057
+ declare const llm_register: typeof register;
1058
+ declare const llm_requestStartedPayload: typeof requestStartedPayload;
1059
+ declare const llm_resolve: typeof resolve;
1060
+ declare const llm_responseReceivedPayload: typeof responseReceivedPayload;
1061
+ declare const llm_sanitizeToolName: typeof sanitizeToolName;
1062
+ declare const llm_toolNameModeOf: typeof toolNameModeOf;
1063
+ declare const llm_urlSource: typeof urlSource;
1064
+ declare const llm_usageCost: typeof usageCost;
1065
+ declare namespace llm {
1066
+ export { llm_ANTHROPIC_TOOL_NAMES as ANTHROPIC_TOOL_NAMES, llm_APIError as APIError, llm_AuthError as AuthError, type llm_CacheControl as CacheControl, type llm_CallOp as CallOp, llm_CapabilityNotSupportedError as CapabilityNotSupportedError, type llm_Client as Client, type llm_ClientOptions as ClientOptions, type llm_Completer as Completer, type llm_ContentPart as ContentPart, llm_DEFAULT_MAX_MEDIA_BYTES as DEFAULT_MAX_MEDIA_BYTES, type llm_Declaration as Declaration, type llm_Factory as Factory, llm_FallbackExhaustedError as FallbackExhaustedError, llm_GEMINI_TOOL_NAMES as GEMINI_TOOL_NAMES, llm_HTTPStatusError as HTTPStatusError, llm_KeyEndpointError as KeyEndpointError, llm_LLMError as LLMError, type llm_LoadOptions as LoadOptions, type llm_MediaSource as MediaSource, llm_MediaTooLargeError as MediaTooLargeError, llm_MediaURLRefusedError as MediaURLRefusedError, type llm_Message as Message, llm_MissingKeyError as MissingKeyError, llm_ModelError as ModelError, llm_OPENAI_TOOL_NAMES as OPENAI_TOOL_NAMES, type llm_PartType as PartType, llm_PermissionDeniedError as PermissionDeniedError, type llm_Price as Price, type llm_Provider as Provider, type llm_ProviderConfig as ProviderConfig, type llm_ProviderKey as ProviderKey, llm_ProviderNotFoundError as ProviderNotFoundError, llm_RateLimitError as RateLimitError, type llm_Request as Request, type llm_RequestStartedPayload as RequestStartedPayload, type llm_ResolvedConfig as ResolvedConfig, type llm_Response as Response, type llm_ResponseReceivedPayload as ResponseReceivedPayload, llm_ResponseTooLargeError as ResponseTooLargeError, type llm_StreamOutcome as StreamOutcome, llm_StreamTruncatedError as StreamTruncatedError, type llm_Streamer as Streamer, llm_TOOL_NAMES_PARAM as TOOL_NAMES_PARAM, type llm_ThinkingBlock as ThinkingBlock, type llm_ThinkingConfig as ThinkingConfig, type llm_Token as Token, type llm_ToolCall as ToolCall, type llm_ToolCallEvent as ToolCallEvent, type llm_ToolCallEventKind as ToolCallEventKind, type llm_ToolCaller as ToolCaller, type llm_ToolChoice as ToolChoice, type llm_ToolChoiceMode as ToolChoiceMode, type llm_ToolDef as ToolDef, llm_ToolNameError as ToolNameError, type llm_ToolNameMode as ToolNameMode, type llm_ToolNameReason as ToolNameReason, type llm_ToolNameRule as ToolNameRule, llm_ToolNames as ToolNames, type llm_ToolResponse as ToolResponse, type llm_ToolStream as ToolStream, type llm_ToolStreamer as ToolStreamer, type llm_URI as URI, type llm_URLSourceOptions as URLSourceOptions, type llm_Usage as Usage, llm_applyAPIKey as applyAPIKey, llm_checkKeyEndpoint as checkKeyEndpoint, llm_checkToolChoice as checkToolChoice, llm_checkToolLinkage as checkToolLinkage, llm_clearRegistry as clearRegistry, llm_createLLM as createLLM, llm_credentialsTrusted as credentialsTrusted, llm_declarationOf as declarationOf, llm_fileSource as fileSource, llm_inlineSource as inlineSource, llm_isFallbackable as isFallbackable, llm_isPublicAddress as isPublicAddress, llm_isValidToolName as isValidToolName, llm_loadConfig as loadConfig, llm_parseURI as parseURI, llm_redactURI as redactURI, llm_register as register, llm_requestStartedPayload as requestStartedPayload, llm_resolve as resolve, llm_responseReceivedPayload as responseReceivedPayload, llm_sanitizeToolName as sanitizeToolName, llm_toolNameModeOf as toolNameModeOf, llm_urlSource as urlSource, llm_usageCost as usageCost };
1067
+ }
1068
+
1069
+ export { type ToolCall as $, ANTHROPIC_TOOL_NAMES as A, type ProviderConfig as B, type Completer as C, DEFAULT_MAX_MEDIA_BYTES as D, type ProviderKey as E, type Factory as F, GEMINI_TOOL_NAMES as G, HTTPStatusError as H, ProviderNotFoundError as I, RateLimitError as J, KeyEndpointError as K, LLMError as L, type MediaSource as M, type RequestStartedPayload as N, OPENAI_TOOL_NAMES as O, type PartType as P, type ResponseReceivedPayload as Q, type ResolvedConfig as R, type Streamer as S, type ToolCaller as T, ResponseTooLargeError as U, type StreamOutcome as V, StreamTruncatedError as W, TOOL_NAMES_PARAM as X, type ThinkingBlock as Y, type ThinkingConfig as Z, type Token as _, type ToolStreamer as a, type ToolCallEvent as a0, type ToolCallEventKind as a1, type ToolChoice as a2, type ToolChoiceMode as a3, ToolNameError as a4, type ToolNameMode as a5, type ToolNameReason as a6, type ToolNameRule as a7, ToolNames as a8, type URI as a9, type URLSourceOptions as aa, type Usage as ab, applyAPIKey as ac, checkKeyEndpoint as ad, checkToolChoice as ae, checkToolLinkage as af, clearRegistry as ag, createLLM as ah, credentialsTrusted as ai, declarationOf as aj, fileSource as ak, inlineSource as al, isFallbackable as am, isPublicAddress as an, isValidToolName as ao, loadConfig as ap, parseURI as aq, redactURI as ar, register as as, requestStartedPayload as at, resolve as au, responseReceivedPayload as av, sanitizeToolName as aw, toolNameModeOf as ax, urlSource as ay, usageCost as az, type Request as b, type Response as c, type ToolDef as d, type ToolResponse as e, type ToolStream as f, APIError as g, AuthError as h, type CacheControl as i, type CallOp as j, CapabilityNotSupportedError as k, llm as l, type Client as m, type ClientOptions as n, type ContentPart as o, type Declaration as p, FallbackExhaustedError as q, type LoadOptions as r, MediaTooLargeError as s, MediaURLRefusedError as t, type Message as u, MissingKeyError as v, ModelError as w, PermissionDeniedError as x, type Price as y, type Provider as z };