@trazum/core 1.8.0

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 (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +163 -0
  3. package/dist/advisories.d.ts +23 -0
  4. package/dist/advisories.d.ts.map +1 -0
  5. package/dist/advisories.js +376 -0
  6. package/dist/advisories.js.map +1 -0
  7. package/dist/aws-sigv4.d.ts +88 -0
  8. package/dist/aws-sigv4.d.ts.map +1 -0
  9. package/dist/aws-sigv4.js +117 -0
  10. package/dist/aws-sigv4.js.map +1 -0
  11. package/dist/baseline.d.ts +171 -0
  12. package/dist/baseline.d.ts.map +1 -0
  13. package/dist/baseline.js +273 -0
  14. package/dist/baseline.js.map +1 -0
  15. package/dist/cache.d.ts +26 -0
  16. package/dist/cache.d.ts.map +1 -0
  17. package/dist/cache.js +28 -0
  18. package/dist/cache.js.map +1 -0
  19. package/dist/changes.d.ts +29 -0
  20. package/dist/changes.d.ts.map +1 -0
  21. package/dist/changes.js +142 -0
  22. package/dist/changes.js.map +1 -0
  23. package/dist/compare.d.ts +65 -0
  24. package/dist/compare.d.ts.map +1 -0
  25. package/dist/compare.js +58 -0
  26. package/dist/compare.js.map +1 -0
  27. package/dist/config-schema.d.ts +118 -0
  28. package/dist/config-schema.d.ts.map +1 -0
  29. package/dist/config-schema.js +315 -0
  30. package/dist/config-schema.js.map +1 -0
  31. package/dist/config.d.ts +47 -0
  32. package/dist/config.d.ts.map +1 -0
  33. package/dist/config.js +112 -0
  34. package/dist/config.js.map +1 -0
  35. package/dist/detect.d.ts +70 -0
  36. package/dist/detect.d.ts.map +1 -0
  37. package/dist/detect.js +228 -0
  38. package/dist/detect.js.map +1 -0
  39. package/dist/evaluate.d.ts +98 -0
  40. package/dist/evaluate.d.ts.map +1 -0
  41. package/dist/evaluate.js +110 -0
  42. package/dist/evaluate.js.map +1 -0
  43. package/dist/extract.d.ts +81 -0
  44. package/dist/extract.d.ts.map +1 -0
  45. package/dist/extract.js +280 -0
  46. package/dist/extract.js.map +1 -0
  47. package/dist/gcp-auth.d.ts +58 -0
  48. package/dist/gcp-auth.d.ts.map +1 -0
  49. package/dist/gcp-auth.js +113 -0
  50. package/dist/gcp-auth.js.map +1 -0
  51. package/dist/glob.d.ts +49 -0
  52. package/dist/glob.d.ts.map +1 -0
  53. package/dist/glob.js +154 -0
  54. package/dist/glob.js.map +1 -0
  55. package/dist/host.d.ts +30 -0
  56. package/dist/host.d.ts.map +1 -0
  57. package/dist/host.js +69 -0
  58. package/dist/host.js.map +1 -0
  59. package/dist/i18n/en.d.ts +4 -0
  60. package/dist/i18n/en.d.ts.map +1 -0
  61. package/dist/i18n/en.js +168 -0
  62. package/dist/i18n/en.js.map +1 -0
  63. package/dist/i18n/es.d.ts +4 -0
  64. package/dist/i18n/es.d.ts.map +1 -0
  65. package/dist/i18n/es.js +168 -0
  66. package/dist/i18n/es.js.map +1 -0
  67. package/dist/i18n/index.d.ts +36 -0
  68. package/dist/i18n/index.d.ts.map +1 -0
  69. package/dist/i18n/index.js +50 -0
  70. package/dist/i18n/index.js.map +1 -0
  71. package/dist/i18n/types.d.ts +180 -0
  72. package/dist/i18n/types.d.ts.map +1 -0
  73. package/dist/i18n/types.js +11 -0
  74. package/dist/i18n/types.js.map +1 -0
  75. package/dist/index.d.ts +66 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +69 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/llm.d.ts +226 -0
  80. package/dist/llm.d.ts.map +1 -0
  81. package/dist/llm.js +485 -0
  82. package/dist/llm.js.map +1 -0
  83. package/dist/nearest.d.ts +20 -0
  84. package/dist/nearest.d.ts.map +1 -0
  85. package/dist/nearest.js +54 -0
  86. package/dist/nearest.js.map +1 -0
  87. package/dist/net.d.ts +90 -0
  88. package/dist/net.d.ts.map +1 -0
  89. package/dist/net.js +203 -0
  90. package/dist/net.js.map +1 -0
  91. package/dist/node.d.ts +32 -0
  92. package/dist/node.d.ts.map +1 -0
  93. package/dist/node.js +33 -0
  94. package/dist/node.js.map +1 -0
  95. package/dist/openrouter.d.ts +25 -0
  96. package/dist/openrouter.d.ts.map +1 -0
  97. package/dist/openrouter.js +72 -0
  98. package/dist/openrouter.js.map +1 -0
  99. package/dist/optimize.d.ts +38 -0
  100. package/dist/optimize.d.ts.map +1 -0
  101. package/dist/optimize.js +183 -0
  102. package/dist/optimize.js.map +1 -0
  103. package/dist/otlp.d.ts +91 -0
  104. package/dist/otlp.d.ts.map +1 -0
  105. package/dist/otlp.js +102 -0
  106. package/dist/otlp.js.map +1 -0
  107. package/dist/phrases.d.ts +169 -0
  108. package/dist/phrases.d.ts.map +1 -0
  109. package/dist/phrases.js +939 -0
  110. package/dist/phrases.js.map +1 -0
  111. package/dist/pricing-overlay.d.ts +55 -0
  112. package/dist/pricing-overlay.d.ts.map +1 -0
  113. package/dist/pricing-overlay.js +241 -0
  114. package/dist/pricing-overlay.js.map +1 -0
  115. package/dist/pricing.d.ts +115 -0
  116. package/dist/pricing.d.ts.map +1 -0
  117. package/dist/pricing.js +400 -0
  118. package/dist/pricing.js.map +1 -0
  119. package/dist/profile.d.ts +71 -0
  120. package/dist/profile.d.ts.map +1 -0
  121. package/dist/profile.js +55 -0
  122. package/dist/profile.js.map +1 -0
  123. package/dist/promptfoo.d.ts +58 -0
  124. package/dist/promptfoo.d.ts.map +1 -0
  125. package/dist/promptfoo.js +149 -0
  126. package/dist/promptfoo.js.map +1 -0
  127. package/dist/prune.d.ts +91 -0
  128. package/dist/prune.d.ts.map +1 -0
  129. package/dist/prune.js +110 -0
  130. package/dist/prune.js.map +1 -0
  131. package/dist/reorder.d.ts +82 -0
  132. package/dist/reorder.d.ts.map +1 -0
  133. package/dist/reorder.js +215 -0
  134. package/dist/reorder.js.map +1 -0
  135. package/dist/review.d.ts +54 -0
  136. package/dist/review.d.ts.map +1 -0
  137. package/dist/review.js +131 -0
  138. package/dist/review.js.map +1 -0
  139. package/dist/rules.d.ts +5 -0
  140. package/dist/rules.d.ts.map +1 -0
  141. package/dist/rules.js +279 -0
  142. package/dist/rules.js.map +1 -0
  143. package/dist/savings.d.ts +36 -0
  144. package/dist/savings.d.ts.map +1 -0
  145. package/dist/savings.js +83 -0
  146. package/dist/savings.js.map +1 -0
  147. package/dist/segment.d.ts +8 -0
  148. package/dist/segment.d.ts.map +1 -0
  149. package/dist/segment.js +74 -0
  150. package/dist/segment.js.map +1 -0
  151. package/dist/shared-prefix.d.ts +63 -0
  152. package/dist/shared-prefix.d.ts.map +1 -0
  153. package/dist/shared-prefix.js +151 -0
  154. package/dist/shared-prefix.js.map +1 -0
  155. package/dist/similarity.d.ts +13 -0
  156. package/dist/similarity.d.ts.map +1 -0
  157. package/dist/similarity.js +30 -0
  158. package/dist/similarity.js.map +1 -0
  159. package/dist/structure.d.ts +144 -0
  160. package/dist/structure.d.ts.map +1 -0
  161. package/dist/structure.js +455 -0
  162. package/dist/structure.js.map +1 -0
  163. package/dist/suggest.d.ts +100 -0
  164. package/dist/suggest.d.ts.map +1 -0
  165. package/dist/suggest.js +151 -0
  166. package/dist/suggest.js.map +1 -0
  167. package/dist/tokenizer.d.ts +57 -0
  168. package/dist/tokenizer.d.ts.map +1 -0
  169. package/dist/tokenizer.js +157 -0
  170. package/dist/tokenizer.js.map +1 -0
  171. package/dist/types.d.ts +296 -0
  172. package/dist/types.d.ts.map +1 -0
  173. package/dist/types.js +3 -0
  174. package/dist/types.js.map +1 -0
  175. package/dist/walk.d.ts +40 -0
  176. package/dist/walk.d.ts.map +1 -0
  177. package/dist/walk.js +95 -0
  178. package/dist/walk.js.map +1 -0
  179. package/package.json +56 -0
  180. package/src/advisories.ts +431 -0
  181. package/src/aws-sigv4.ts +174 -0
  182. package/src/baseline.ts +390 -0
  183. package/src/cache.ts +54 -0
  184. package/src/changes.ts +158 -0
  185. package/src/compare.ts +131 -0
  186. package/src/config-schema.ts +451 -0
  187. package/src/config.ts +161 -0
  188. package/src/detect.ts +312 -0
  189. package/src/evaluate.ts +188 -0
  190. package/src/extract.ts +336 -0
  191. package/src/gcp-auth.ts +166 -0
  192. package/src/glob.ts +160 -0
  193. package/src/host.ts +90 -0
  194. package/src/i18n/en.ts +236 -0
  195. package/src/i18n/es.ts +236 -0
  196. package/src/i18n/index.ts +68 -0
  197. package/src/i18n/types.ts +230 -0
  198. package/src/index.ts +228 -0
  199. package/src/llm.ts +708 -0
  200. package/src/nearest.ts +61 -0
  201. package/src/net.ts +233 -0
  202. package/src/node.ts +63 -0
  203. package/src/openrouter.ts +125 -0
  204. package/src/optimize.ts +228 -0
  205. package/src/otlp.ts +179 -0
  206. package/src/phrases.ts +1047 -0
  207. package/src/pricing-overlay.ts +319 -0
  208. package/src/pricing.ts +468 -0
  209. package/src/profile.ts +124 -0
  210. package/src/promptfoo.ts +213 -0
  211. package/src/prune.ts +211 -0
  212. package/src/reorder.ts +307 -0
  213. package/src/review.ts +180 -0
  214. package/src/rules.ts +324 -0
  215. package/src/savings.ts +121 -0
  216. package/src/segment.ts +106 -0
  217. package/src/shared-prefix.ts +198 -0
  218. package/src/similarity.ts +28 -0
  219. package/src/structure.ts +652 -0
  220. package/src/suggest.ts +254 -0
  221. package/src/tokenizer.ts +190 -0
  222. package/src/types.ts +323 -0
  223. package/src/walk.ts +117 -0
package/src/llm.ts ADDED
@@ -0,0 +1,708 @@
1
+ import { buildAdvisories } from './advisories.js';
2
+ import { getMessages } from './i18n/index.js';
3
+ import { signRequest } from './aws-sigv4.js';
4
+ import { accessToken } from './gcp-auth.js';
5
+ import type { CachedToken, ServiceAccount } from './gcp-auth.js';
6
+ import { SAFE_FETCH_INIT, checkedEndpoint } from './net.js';
7
+ import type { Locale } from './i18n/types.js';
8
+ import { computeSavings } from './savings.js';
9
+ import { segment } from './segment.js';
10
+ import { estimateTokens } from './tokenizer.js';
11
+ import type { LlmProvider, OptimizationResult, TokenCounter } from './types.js';
12
+
13
+ /**
14
+ * Optional LLM layer.
15
+ *
16
+ * The deterministic core already does the work at zero cost. This pass adds
17
+ * the semantic compression rules cannot do — rewriting a whole sentence,
18
+ * merging two instructions that say the same thing in different words — and
19
+ * that is why it costs one call.
20
+ *
21
+ * The provider is pluggable on purpose: your own hosted model, an
22
+ * OpenAI-compatible endpoint, the Claude API or anything else behind
23
+ * `customProvider`.
24
+ */
25
+
26
+ export const REFINER_SYSTEM_PROMPT = `You rewrite prompts so they cost fewer tokens without changing what they ask for.
27
+
28
+ Rules:
29
+ - Preserve exactly the same task, constraints, output format and success criteria.
30
+ - Copy verbatim, without changing a single character: code blocks, URLs, template placeholders ({{x}}, \${x}, {x}) and XML/HTML tags.
31
+ - Do not summarise and do not drop requirements. When in doubt about whether something is a requirement, keep it.
32
+ - Remove redundancy, padding and repetition. Merge duplicated instructions.
33
+ - Keep the original language of the prompt.
34
+ - Return ONLY the rewritten prompt. No explanations, no commentary, no code fences wrapping the answer.`;
35
+
36
+ export interface RefineOptions {
37
+ /**
38
+ * Minimum fraction of tokens the result must keep (0-1). Below this
39
+ * threshold the model is assumed to have summarised rather than compressed,
40
+ * and the candidate is rejected. Defaults to 0.25.
41
+ */
42
+ minRetainRatio?: number;
43
+ tokenCounter?: TokenCounter;
44
+ /** Language of the rejection reason. Defaults to the result's locale. */
45
+ locale?: Locale;
46
+ }
47
+
48
+ /** Strips code fences if the model wrapped its answer despite being asked not to. */
49
+ function stripCodeFence(text: string): string {
50
+ const trimmed = text.trim();
51
+ const match = /^(?:```|~~~)[a-zA-Z]*\n([\s\S]*?)\n?(?:```|~~~)$/.exec(trimmed);
52
+ return match?.[1] ?? trimmed;
53
+ }
54
+
55
+ /**
56
+ * Runs the already-optimised prompt through the LLM and accepts the result
57
+ * only if it passes the safety checks.
58
+ *
59
+ * It never returns a prompt worse than the deterministic one: if the candidate
60
+ * loses protected content, grows in tokens or shrinks suspiciously, it is
61
+ * discarded and the previous result stands.
62
+ */
63
+ export async function refineWithLlm(
64
+ result: OptimizationResult,
65
+ provider: LlmProvider,
66
+ options: RefineOptions = {},
67
+ ): Promise<OptimizationResult> {
68
+ const count = options.tokenCounter ?? estimateTokens;
69
+ const minRetainRatio = options.minRetainRatio ?? 0.25;
70
+ const locale = options.locale ?? result.locale;
71
+ const t = getMessages(locale);
72
+
73
+ const raw = await provider.complete({
74
+ system: REFINER_SYSTEM_PROMPT,
75
+ user: result.optimized,
76
+ });
77
+ const candidate = stripCodeFence(raw);
78
+ const tokensBefore = result.tokensAfter;
79
+ const tokensAfter = count(candidate);
80
+
81
+ const base = {
82
+ provider: provider.name,
83
+ model: provider.model,
84
+ candidate,
85
+ tokensBefore,
86
+ tokensAfter,
87
+ };
88
+
89
+ const reject = (rejectedReason: string): OptimizationResult => ({
90
+ ...result,
91
+ llm: { ...base, applied: false, rejectedReason },
92
+ });
93
+
94
+ if (!candidate.trim()) {
95
+ return reject(t.llm.emptyResponse());
96
+ }
97
+
98
+ // Protected content has to still be there, character for character.
99
+ const mustSurvive = [
100
+ ...new Set(
101
+ segment(result.optimized)
102
+ .filter((s) => s.kind === 'protected')
103
+ .map((s) => s.text),
104
+ ),
105
+ ];
106
+ const lost = mustSurvive.filter((text) => !candidate.includes(text));
107
+ if (lost.length > 0) {
108
+ return reject(t.llm.protectedContentAltered(lost.length));
109
+ }
110
+
111
+ if (tokensAfter >= tokensBefore) {
112
+ return reject(t.llm.notShorter(tokensAfter, tokensBefore));
113
+ }
114
+
115
+ if (tokensAfter < tokensBefore * minRetainRatio) {
116
+ return reject(t.llm.suspiciousShrink(Math.round((tokensAfter / tokensBefore) * 100)));
117
+ }
118
+
119
+ const finalTokensBefore = result.tokensBefore;
120
+ const savings = computeSavings(finalTokensBefore, tokensAfter, result.usage);
121
+ const advisories = buildAdvisories(candidate, tokensAfter, result.usage, { count, locale });
122
+
123
+ return {
124
+ ...result,
125
+ optimized: candidate,
126
+ tokensAfter,
127
+ tokensSaved: finalTokensBefore - tokensAfter,
128
+ reductionPct:
129
+ finalTokensBefore > 0 ? ((finalTokensBefore - tokensAfter) / finalTokensBefore) * 100 : 0,
130
+ savings,
131
+ advisories,
132
+ llm: { ...base, applied: true },
133
+ };
134
+ }
135
+
136
+ // --------------------------------------------------------------------------
137
+ // Bundled providers
138
+ // --------------------------------------------------------------------------
139
+
140
+ export interface OpenAiCompatibleOptions {
141
+ /** Base URL, without `/chat/completions`. E.g. `https://llm.example.com/v1` */
142
+ baseUrl: string;
143
+ apiKey?: string;
144
+ model: string;
145
+ /** Extra headers, in case your gateway requires its own. */
146
+ headers?: Record<string, string>;
147
+ /** Name shown in the report. */
148
+ name?: string;
149
+ maxTokens?: number;
150
+ fetchImpl?: typeof fetch;
151
+ /**
152
+ * Allow http and private hosts — localhost, the RFC1918 ranges, the cloud
153
+ * metadata address.
154
+ *
155
+ * **Only when the operator chose the URL.** That is the whole distinction. An
156
+ * endpoint from `TRAZUM_LLM_BASE_URL` is somebody configuring their own
157
+ * machine, and pointing it at `http://localhost:11434` for Ollama is the
158
+ * documented normal case. An endpoint arriving in an HTTP request body is a
159
+ * stranger naming a host for this server to fetch, which is server-side
160
+ * request forgery whatever else it is called.
161
+ */
162
+ allowInsecure?: boolean;
163
+ }
164
+
165
+ /**
166
+ * The endpoint check lives in `net.ts`, beside the validator and beside the
167
+ * `fetch` options every server-side call here carries.
168
+ *
169
+ * At construction rather than at call time, so a provider that can never work
170
+ * does not exist to be handed around.
171
+ *
172
+ * The web route already validates a body-supplied URL before it gets here, and
173
+ * that stays — it turns the reason code into a sentence in the reader's
174
+ * language. This is the second lock, at the boundary. `openAiCompatible` is an
175
+ * exported library function, so "the caller checks" is a promise about every
176
+ * future caller, including ones outside this repository.
177
+ */
178
+
179
+ /**
180
+ * Any endpoint speaking OpenAI's `/chat/completions` format. Covers vLLM,
181
+ * Ollama, OpenRouter, LM Studio, Together and most internal gateways.
182
+ */
183
+ export function openAiCompatible(options: OpenAiCompatibleOptions): LlmProvider {
184
+ const {
185
+ baseUrl,
186
+ apiKey,
187
+ model,
188
+ headers = {},
189
+ name = 'openai-compatible',
190
+ maxTokens = 8192,
191
+ fetchImpl = fetch,
192
+ allowInsecure = false,
193
+ } = options;
194
+
195
+ const endpoint = checkedEndpoint(baseUrl, { allowInsecure, name });
196
+
197
+ return {
198
+ name,
199
+ model,
200
+ async complete({ system, user }) {
201
+ const res = await fetchImpl(`${endpoint}/chat/completions`, {
202
+ ...SAFE_FETCH_INIT,
203
+ method: 'POST',
204
+ headers: {
205
+ 'content-type': 'application/json',
206
+ ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
207
+ ...headers,
208
+ },
209
+ body: JSON.stringify({
210
+ model,
211
+ max_tokens: maxTokens,
212
+ messages: [
213
+ { role: 'system', content: system },
214
+ { role: 'user', content: user },
215
+ ],
216
+ }),
217
+ });
218
+ if (!res.ok) {
219
+ throw new Error(`Provider "${name}" responded ${res.status}: ${await res.text()}`);
220
+ }
221
+ const data = (await res.json()) as {
222
+ choices?: Array<{ message?: { content?: string } }>;
223
+ };
224
+ const content = data.choices?.[0]?.message?.content;
225
+ if (typeof content !== 'string') {
226
+ throw new Error(`Unexpected response from "${name}": choices[0].message.content not found`);
227
+ }
228
+ return content;
229
+ },
230
+ };
231
+ }
232
+
233
+ export interface AnthropicProviderOptions {
234
+ apiKey: string;
235
+ model?: string;
236
+ baseUrl?: string;
237
+ maxTokens?: number;
238
+ fetchImpl?: typeof fetch;
239
+ /** See `OpenAiCompatibleOptions.allowInsecure`: only when you chose the URL. */
240
+ allowInsecure?: boolean;
241
+ }
242
+
243
+ /** The Claude API directly, via `/v1/messages`. */
244
+ export function anthropicProvider(options: AnthropicProviderOptions): LlmProvider {
245
+ const {
246
+ apiKey,
247
+ model = 'claude-opus-5',
248
+ baseUrl = 'https://api.anthropic.com',
249
+ maxTokens = 8192,
250
+ fetchImpl = fetch,
251
+ allowInsecure = false,
252
+ } = options;
253
+
254
+ // The same door, one along. This one has a safe default, which is exactly why
255
+ // it is easy to forget that the option overriding it is a network target.
256
+ const endpoint = checkedEndpoint(baseUrl, { allowInsecure, name: 'anthropic' });
257
+
258
+ return {
259
+ name: 'anthropic',
260
+ model,
261
+ async complete({ system, user }) {
262
+ const res = await fetchImpl(`${endpoint}/v1/messages`, {
263
+ ...SAFE_FETCH_INIT,
264
+ method: 'POST',
265
+ headers: {
266
+ 'content-type': 'application/json',
267
+ 'x-api-key': apiKey,
268
+ 'anthropic-version': '2023-06-01',
269
+ },
270
+ body: JSON.stringify({
271
+ model,
272
+ max_tokens: maxTokens,
273
+ system,
274
+ messages: [{ role: 'user', content: user }],
275
+ }),
276
+ });
277
+ if (!res.ok) {
278
+ throw new Error(`The Claude API responded ${res.status}: ${await res.text()}`);
279
+ }
280
+ const data = (await res.json()) as {
281
+ content?: Array<{ type: string; text?: string }>;
282
+ stop_reason?: string;
283
+ };
284
+ if (data.stop_reason === 'refusal') {
285
+ throw new Error('The Claude API declined the request (stop_reason: refusal).');
286
+ }
287
+ const text = data.content?.find((b) => b.type === 'text')?.text;
288
+ if (typeof text !== 'string') {
289
+ throw new Error('Unexpected response from the Claude API: no text block.');
290
+ }
291
+ return text;
292
+ },
293
+ };
294
+ }
295
+
296
+ /**
297
+ * Reads an answer out of Google's `generateContent` response, or refuses.
298
+ *
299
+ * Shared by `geminiProvider` and `vertexProvider`, which speak to the same API
300
+ * behind different credentials. Two copies of "is this answer complete" is one
301
+ * copy too many: the whole point of these checks is that three of Google's
302
+ * failure modes arrive as HTTP 200, and a second copy is a second place for one
303
+ * of them to be forgotten.
304
+ *
305
+ * `label` names the surface in the error, because "Gemini refused" and "Vertex
306
+ * refused" send somebody to different consoles.
307
+ */
308
+ function readGeminiAnswer(payload: unknown, label: string): string {
309
+ const data = payload as {
310
+ candidates?: Array<{ content?: { parts?: Array<{ text?: string }> }; finishReason?: string }>;
311
+ promptFeedback?: { blockReason?: string };
312
+ };
313
+
314
+ const blocked = data.promptFeedback?.blockReason;
315
+ if (blocked) {
316
+ throw new Error(`${label} blocked the prompt (${blocked}).`);
317
+ }
318
+
319
+ const candidate = data.candidates?.[0];
320
+ if (!candidate) {
321
+ throw new Error(`Unexpected response from ${label}: no candidates.`);
322
+ }
323
+ if (candidate.finishReason === 'MAX_TOKENS') {
324
+ // Refused rather than returned. A truncated rewrite is the failure this
325
+ // whole package is built to avoid: it reads as an answer.
326
+ throw new Error(`${label} stopped at the token limit — the answer is incomplete.`);
327
+ }
328
+ if (candidate.finishReason === 'SAFETY' || candidate.finishReason === 'PROHIBITED_CONTENT') {
329
+ throw new Error(`${label} declined the request (${candidate.finishReason}).`);
330
+ }
331
+
332
+ const text = candidate.content?.parts?.map((part) => part.text ?? '').join('');
333
+ if (!text) {
334
+ throw new Error(`Unexpected response from ${label}: no text in the candidate.`);
335
+ }
336
+ return text;
337
+ }
338
+
339
+ export interface GeminiProviderOptions {
340
+ apiKey: string;
341
+ /** Default: `gemini-2.5-pro`. */
342
+ model?: string;
343
+ /** Default: Google's public endpoint. */
344
+ baseUrl?: string;
345
+ maxTokens?: number;
346
+ fetchImpl?: typeof fetch;
347
+ /** See `OpenAiCompatibleOptions.allowInsecure`: only when you chose the URL. */
348
+ allowInsecure?: boolean;
349
+ }
350
+
351
+ /**
352
+ * Gemini directly, via `generateContent`.
353
+ *
354
+ * The one provider on the list that needs its own function rather than the
355
+ * OpenAI-compatible path. Everything else — Groq, Together, Fireworks,
356
+ * DeepInfra, Cerebras, SiliconFlow, OpenRouter, LiteLLM — speaks the OpenAI
357
+ * shape, so `openAiCompatibleProvider` with a base URL is the whole
358
+ * integration. Google's is a different document: the system prompt is
359
+ * `systemInstruction` rather than a message, turns are `contents` with `parts`,
360
+ * and the answer is the first candidate's parts joined.
361
+ *
362
+ * Three failure modes that are not HTTP errors, and each has bitten somebody:
363
+ *
364
+ * - **A safety block returns 200.** `promptFeedback.blockReason` arrives with no
365
+ * candidates at all, so reading `candidates[0]` gives `undefined` and the
366
+ * caller sees "no text" for what is actually a refusal.
367
+ * - **`finishReason: MAX_TOKENS` also returns 200**, with a truncated answer.
368
+ * For a rewrite pass that is worse than an error: the text looks like a
369
+ * result and is half a result.
370
+ * - **Parts can be empty.** A candidate with no text part is a valid document
371
+ * and not a valid answer.
372
+ *
373
+ * The key goes in a header, not the query string. Google's own examples put it
374
+ * in `?key=`, which puts a credential in every proxy log and referrer between
375
+ * here and there.
376
+ */
377
+ export function geminiProvider(options: GeminiProviderOptions): LlmProvider {
378
+ const {
379
+ apiKey,
380
+ model = 'gemini-2.5-pro',
381
+ baseUrl = 'https://generativelanguage.googleapis.com',
382
+ maxTokens = 8192,
383
+ fetchImpl = fetch,
384
+ allowInsecure = false,
385
+ } = options;
386
+
387
+ const endpoint = checkedEndpoint(baseUrl, { allowInsecure, name: 'gemini' });
388
+
389
+ return {
390
+ name: 'gemini',
391
+ model,
392
+ async complete({ system, user }) {
393
+ const res = await fetchImpl(
394
+ `${endpoint}/v1beta/models/${encodeURIComponent(model)}:generateContent`,
395
+ {
396
+ ...SAFE_FETCH_INIT,
397
+ method: 'POST',
398
+ headers: { 'content-type': 'application/json', 'x-goog-api-key': apiKey },
399
+ body: JSON.stringify({
400
+ systemInstruction: { parts: [{ text: system }] },
401
+ contents: [{ role: 'user', parts: [{ text: user }] }],
402
+ generationConfig: { maxOutputTokens: maxTokens, temperature: 0 },
403
+ }),
404
+ },
405
+ );
406
+
407
+ if (!res.ok) {
408
+ throw new Error(`The Gemini API responded ${res.status}: ${await res.text()}`);
409
+ }
410
+ return readGeminiAnswer(await res.json(), 'The Gemini API');
411
+ },
412
+ };
413
+ }
414
+
415
+ export interface BedrockProviderOptions {
416
+ /** e.g. `anthropic.claude-sonnet-4-5-20250929-v1:0`. */
417
+ model: string;
418
+ region: string;
419
+ accessKeyId: string;
420
+ secretAccessKey: string;
421
+ /** For temporary credentials from STS or an instance role. */
422
+ sessionToken?: string;
423
+ maxTokens?: number;
424
+ /** Override the host. Defaults to the regional Bedrock runtime endpoint. */
425
+ baseUrl?: string;
426
+ fetchImpl?: typeof fetch;
427
+ allowInsecure?: boolean;
428
+ /** Injectable for tests; the signature is a function of the clock. */
429
+ now?: () => Date;
430
+ }
431
+
432
+ /**
433
+ * Amazon Bedrock, through **Converse** rather than `InvokeModel`.
434
+ *
435
+ * That choice is the whole reason this is one provider instead of six.
436
+ * `InvokeModel` takes a body in each model family's own shape — Anthropic's
437
+ * `messages` with `anthropic_version`, Meta's `prompt`, Amazon's
438
+ * `inputText` — so supporting "Bedrock" through it means supporting each vendor
439
+ * separately and getting a 400 for every model nobody thought about. `Converse`
440
+ * is Bedrock's unified surface: one request shape, one response shape, every
441
+ * model that supports it.
442
+ *
443
+ * Signed with SigV4 by hand — see `aws-sigv4.ts` for why there is no SDK here
444
+ * and what the tests do and do not prove.
445
+ *
446
+ * `stopReason: 'max_tokens'` throws, for the same reason it does on Gemini: a
447
+ * truncated rewrite reads exactly like a finished one, and that is the failure
448
+ * this package exists to refuse.
449
+ */
450
+ export function bedrockProvider(options: BedrockProviderOptions): LlmProvider {
451
+ const {
452
+ model,
453
+ region,
454
+ accessKeyId,
455
+ secretAccessKey,
456
+ sessionToken,
457
+ maxTokens = 8192,
458
+ baseUrl = `https://bedrock-runtime.${region}.amazonaws.com`,
459
+ fetchImpl = fetch,
460
+ allowInsecure = false,
461
+ now = () => new Date(),
462
+ } = options;
463
+
464
+ const endpoint = checkedEndpoint(baseUrl, { allowInsecure, name: 'bedrock' });
465
+ const host = new URL(endpoint).host;
466
+
467
+ return {
468
+ name: 'bedrock',
469
+ model,
470
+ async complete({ system, user }) {
471
+ /**
472
+ * Bedrock model ids contain a colon — `anthropic.claude-v2:1` — and AWS's
473
+ * own URLs carry it unencoded, which RFC 3986 permits in a path segment.
474
+ *
475
+ * The comment that used to sit here claimed `encodeURIComponent` leaves it
476
+ * alone. It does not: it produces `%3A`. The signature would still have
477
+ * matched, because the same string is signed and sent — but the request
478
+ * would have gone to a path AWS does not document, and whether its router
479
+ * normalises `%3A` back to `:` is not something this repository can find
480
+ * out from here. A test asserting the path exactly is what surfaced it.
481
+ *
482
+ * So: encode, then put the colon back. `/` stays encoded, which is the one
483
+ * character that would change the shape of the path rather than a
484
+ * character in it.
485
+ */
486
+ const path = `/model/${encodeURIComponent(model).replace(/%3A/g, ':')}/converse`;
487
+ const body = JSON.stringify({
488
+ system: [{ text: system }],
489
+ messages: [{ role: 'user', content: [{ text: user }] }],
490
+ inferenceConfig: { maxTokens, temperature: 0 },
491
+ });
492
+
493
+ const signed = await signRequest({
494
+ method: 'POST',
495
+ path,
496
+ host,
497
+ region,
498
+ service: 'bedrock',
499
+ body,
500
+ accessKeyId,
501
+ secretAccessKey,
502
+ ...(sessionToken ? { sessionToken } : {}),
503
+ now: now(),
504
+ });
505
+
506
+ const res = await fetchImpl(`${endpoint}${path}`, {
507
+ ...SAFE_FETCH_INIT,
508
+ method: 'POST',
509
+ headers: { ...signed, 'content-type': 'application/json' },
510
+ body,
511
+ });
512
+
513
+ if (!res.ok) {
514
+ throw new Error(`Bedrock responded ${res.status}: ${await res.text()}`);
515
+ }
516
+
517
+ const data = (await res.json()) as {
518
+ output?: { message?: { content?: Array<{ text?: string }> } };
519
+ stopReason?: string;
520
+ };
521
+
522
+ if (data.stopReason === 'max_tokens') {
523
+ throw new Error('Bedrock stopped at the token limit — the answer is incomplete.');
524
+ }
525
+ if (data.stopReason === 'content_filtered') {
526
+ throw new Error('Bedrock filtered the response (stopReason: content_filtered).');
527
+ }
528
+
529
+ const text = data.output?.message?.content?.map((part) => part.text ?? '').join('');
530
+ if (!text) {
531
+ throw new Error('Unexpected response from Bedrock: no text in the message.');
532
+ }
533
+ return text;
534
+ },
535
+ };
536
+ }
537
+
538
+ export interface VertexProviderOptions {
539
+ /** The parsed contents of a service-account JSON key. */
540
+ serviceAccount: ServiceAccount;
541
+ project: string;
542
+ /** e.g. `us-central1`. `global` is also valid for some models. */
543
+ location: string;
544
+ /** Default: `gemini-2.5-pro`. */
545
+ model?: string;
546
+ /** Default: `google`. `anthropic` for Claude on Vertex. */
547
+ publisher?: string;
548
+ maxTokens?: number;
549
+ baseUrl?: string;
550
+ fetchImpl?: typeof fetch;
551
+ allowInsecure?: boolean;
552
+ now?: () => Date;
553
+ }
554
+
555
+ /**
556
+ * Gemini through Vertex AI, with a service account instead of an API key.
557
+ *
558
+ * Vertex will not take an API key, which is the whole difference from
559
+ * `geminiProvider`: the credential is a signed assertion traded for an access
560
+ * token that lasts an hour. `gcp-auth.ts` does that, caches the token, and
561
+ * explains why there is no SDK.
562
+ *
563
+ * The response shape is Gemini's, so the same three HTTP-200 failures apply and
564
+ * are refused the same way — a blocked prompt, a truncated answer, an empty
565
+ * candidate. The parsing is shared with `geminiProvider` rather than copied,
566
+ * because two copies of "is this answer complete" is one copy too many.
567
+ */
568
+ export function vertexProvider(options: VertexProviderOptions): LlmProvider {
569
+ const {
570
+ serviceAccount,
571
+ project,
572
+ location,
573
+ model = 'gemini-2.5-pro',
574
+ publisher = 'google',
575
+ maxTokens = 8192,
576
+ baseUrl = location === 'global'
577
+ ? 'https://aiplatform.googleapis.com'
578
+ : `https://${location}-aiplatform.googleapis.com`,
579
+ fetchImpl = fetch,
580
+ allowInsecure = false,
581
+ now = () => new Date(),
582
+ } = options;
583
+
584
+ const endpoint = checkedEndpoint(baseUrl, { allowInsecure, name: 'vertex' });
585
+ // One cache per provider instance, so two providers in one process do not
586
+ // share a token — and neither leaks into the other's requests.
587
+ const cache: { current: CachedToken | null } = { current: null };
588
+
589
+ return {
590
+ name: 'vertex',
591
+ model,
592
+ async complete({ system, user }) {
593
+ const token = await accessToken(serviceAccount, { fetchImpl, now, cache });
594
+
595
+ const path =
596
+ `/v1/projects/${encodeURIComponent(project)}` +
597
+ `/locations/${encodeURIComponent(location)}` +
598
+ `/publishers/${encodeURIComponent(publisher)}` +
599
+ `/models/${encodeURIComponent(model)}:generateContent`;
600
+
601
+ const res = await fetchImpl(`${endpoint}${path}`, {
602
+ ...SAFE_FETCH_INIT,
603
+ method: 'POST',
604
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
605
+ body: JSON.stringify({
606
+ systemInstruction: { parts: [{ text: system }] },
607
+ contents: [{ role: 'user', parts: [{ text: user }] }],
608
+ generationConfig: { maxOutputTokens: maxTokens, temperature: 0 },
609
+ }),
610
+ });
611
+
612
+ if (!res.ok) {
613
+ throw new Error(`Vertex responded ${res.status}: ${await res.text()}`);
614
+ }
615
+ return readGeminiAnswer(await res.json(), 'Vertex');
616
+ },
617
+ };
618
+ }
619
+
620
+ export interface CustomProviderOptions {
621
+ name: string;
622
+ model: string;
623
+ /** Builds the HTTP request from the system and user prompts. */
624
+ request(input: { system: string; user: string }): { url: string; init: RequestInit };
625
+ /** Extracts the text from the already-parsed response body. */
626
+ extract(body: unknown): string;
627
+ fetchImpl?: typeof fetch;
628
+ }
629
+
630
+ /**
631
+ * Escape hatch: if your endpoint speaks none of the formats above, you define
632
+ * how the request is built and how the response is read, and everything else
633
+ * keeps working the same.
634
+ */
635
+ export function customProvider(options: CustomProviderOptions): LlmProvider {
636
+ const { name, model, request, extract, fetchImpl = fetch } = options;
637
+ return {
638
+ name,
639
+ model,
640
+ async complete(input) {
641
+ const { url, init } = request(input);
642
+ // The caller built this request themselves, so the URL is theirs to choose
643
+ // — but the redirect default is not something they opted into, and it is
644
+ // the one that turns any endpoint into a hop. Overridable, since a custom
645
+ // provider may genuinely need to follow one.
646
+ const res = await fetchImpl(url, { ...SAFE_FETCH_INIT, ...init });
647
+ if (!res.ok) {
648
+ throw new Error(`Provider "${name}" responded ${res.status}: ${await res.text()}`);
649
+ }
650
+ return extract(await res.json());
651
+ },
652
+ };
653
+ }
654
+
655
+ /**
656
+ * Builds a provider from environment variables.
657
+ *
658
+ * TRAZUM_LLM_PROVIDER openai | anthropic (default: openai)
659
+ * TRAZUM_LLM_BASE_URL base URL of the endpoint
660
+ * TRAZUM_LLM_API_KEY key, when one is needed
661
+ * TRAZUM_LLM_MODEL model identifier
662
+ *
663
+ * Returns `null` when the configuration is incomplete, so the tool keeps
664
+ * working in deterministic mode instead of failing.
665
+ */
666
+ export function providerFromEnv(
667
+ env: Record<string, string | undefined> = process.env,
668
+ ): LlmProvider | null {
669
+ const kind = (env.TRAZUM_LLM_PROVIDER ?? 'openai').toLowerCase();
670
+ const apiKey = env.TRAZUM_LLM_API_KEY;
671
+ const model = env.TRAZUM_LLM_MODEL;
672
+ const baseUrl = env.TRAZUM_LLM_BASE_URL;
673
+
674
+ // Trusted because it came from the environment: the operator configuring
675
+ // their own machine, not a stranger naming a host for this server to fetch.
676
+ // `http://localhost:11434` for Ollama is the normal case here, and the
677
+ // documentation promises it works.
678
+ if (kind === 'anthropic') {
679
+ if (!apiKey) return null;
680
+ return anthropicProvider({
681
+ apiKey,
682
+ allowInsecure: true,
683
+ ...(model ? { model } : {}),
684
+ ...(baseUrl ? { baseUrl } : {}),
685
+ });
686
+ }
687
+
688
+ if (kind === 'gemini' || kind === 'google') {
689
+ // Same shape as the Anthropic branch: a key is enough, because the endpoint
690
+ // has a working default and the model does too.
691
+ if (!apiKey) return null;
692
+ return geminiProvider({
693
+ apiKey,
694
+ allowInsecure: true,
695
+ ...(model ? { model } : {}),
696
+ ...(baseUrl ? { baseUrl } : {}),
697
+ });
698
+ }
699
+
700
+ if (!baseUrl || !model) return null;
701
+ return openAiCompatible({
702
+ baseUrl,
703
+ allowInsecure: true,
704
+ model,
705
+ ...(apiKey ? { apiKey } : {}),
706
+ name: env.TRAZUM_LLM_NAME ?? 'llm',
707
+ });
708
+ }