@jambonz/llm 0.1.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.
@@ -0,0 +1,2645 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/test-kit/index.ts
31
+ var test_kit_exports = {};
32
+ __export(test_kit_exports, {
33
+ FakeAdapter: () => FakeAdapter,
34
+ createFakeHarness: () => createFakeHarness,
35
+ fakeManifest: () => fakeManifest,
36
+ runContractTests: () => runContractTests
37
+ });
38
+ module.exports = __toCommonJS(test_kit_exports);
39
+
40
+ // src/test-kit/runner.ts
41
+ var import_vitest = require("vitest");
42
+
43
+ // src/registry.ts
44
+ var registry = /* @__PURE__ */ new Map();
45
+ function registerAdapter(factory) {
46
+ if (registry.has(factory.vendor)) {
47
+ throw new Error(
48
+ `Adapter already registered for vendor '${factory.vendor}'. Use replaceAdapter() if you intended to override.`
49
+ );
50
+ }
51
+ if (factory.vendor !== factory.manifest.vendor) {
52
+ throw new Error(
53
+ `Adapter factory vendor '${factory.vendor}' does not match manifest.vendor '${factory.manifest.vendor}'.`
54
+ );
55
+ }
56
+ registry.set(factory.vendor, factory);
57
+ }
58
+ function getAdapterFactory(vendor) {
59
+ const factory = registry.get(vendor);
60
+ if (!factory) {
61
+ const known = Array.from(registry.keys()).sort().join(", ") || "(none)";
62
+ throw new Error(
63
+ `Unknown vendor '${vendor}'. Registered vendors: ${known}`
64
+ );
65
+ }
66
+ return factory;
67
+ }
68
+ function _resetRegistryForTests() {
69
+ registry.clear();
70
+ }
71
+
72
+ // src/adapters/openai/adapter.ts
73
+ var import_openai = __toESM(require("openai"), 1);
74
+
75
+ // src/validate.ts
76
+ function assertValidRequest(req) {
77
+ if (!req || typeof req !== "object") {
78
+ throw new Error("PromptRequest must be an object");
79
+ }
80
+ if (typeof req.model !== "string" || req.model.length === 0) {
81
+ throw new Error("PromptRequest.model must be a non-empty string");
82
+ }
83
+ if (!Array.isArray(req.messages) || req.messages.length === 0) {
84
+ throw new Error("PromptRequest.messages must be a non-empty array");
85
+ }
86
+ if (req.messages.some((m) => m.role === "system")) {
87
+ throw new Error(
88
+ "PromptRequest.messages must not contain role: 'system'. Pass the system prompt via PromptRequest.system instead."
89
+ );
90
+ }
91
+ }
92
+
93
+ // src/adapters/openai/_streaming.ts
94
+ async function* streamFromOpenAI(client, req, options) {
95
+ assertValidRequest(req);
96
+ if (req.signal?.aborted) {
97
+ yield { type: "end", finishReason: "aborted" };
98
+ return;
99
+ }
100
+ const capabilities = capabilitiesFor(req.model, options.knownModels);
101
+ const useTools = req.tools && req.tools.length > 0 && capabilities.tools;
102
+ const messages = buildWireMessages(req);
103
+ const tools = useTools ? formatTools(req.tools) : void 0;
104
+ const body = {
105
+ model: req.model,
106
+ messages,
107
+ stream: true,
108
+ stream_options: { include_usage: true }
109
+ };
110
+ if (tools) {
111
+ body.tools = tools;
112
+ body.tool_choice = "auto";
113
+ }
114
+ if (req.temperature !== void 0) body.temperature = req.temperature;
115
+ if (req.maxTokens !== void 0) body.max_tokens = req.maxTokens;
116
+ let stream;
117
+ try {
118
+ stream = await client.chat.completions.create(body, { signal: req.signal });
119
+ } catch (err) {
120
+ if (isAbortError(err)) {
121
+ yield { type: "end", finishReason: "aborted" };
122
+ return;
123
+ }
124
+ throw err;
125
+ }
126
+ const pending = {};
127
+ const startedIds = /* @__PURE__ */ new Set();
128
+ const toolCallsEmitted = /* @__PURE__ */ new Set();
129
+ let usage;
130
+ let finalFinishReason = null;
131
+ let finalRawReason;
132
+ try {
133
+ for await (const chunk of stream) {
134
+ if (req.signal?.aborted) {
135
+ yield { type: "end", finishReason: "aborted" };
136
+ return;
137
+ }
138
+ if (chunk.usage) {
139
+ usage = {
140
+ ...chunk.usage.prompt_tokens !== void 0 ? { inputTokens: chunk.usage.prompt_tokens } : {},
141
+ ...chunk.usage.completion_tokens !== void 0 ? { outputTokens: chunk.usage.completion_tokens } : {},
142
+ ...chunk.usage.total_tokens !== void 0 ? { totalTokens: chunk.usage.total_tokens } : {}
143
+ };
144
+ }
145
+ const choice = chunk.choices?.[0];
146
+ if (!choice) continue;
147
+ const delta = choice.delta;
148
+ const finishReason = choice.finish_reason;
149
+ if (delta?.content) {
150
+ yield { type: "token", text: delta.content };
151
+ }
152
+ if (delta?.tool_calls) {
153
+ for (const tc of delta.tool_calls) {
154
+ const idx = tc.index;
155
+ if (!pending[idx]) {
156
+ pending[idx] = { id: "", name: "", arguments: "" };
157
+ }
158
+ if (tc.id) pending[idx].id += tc.id;
159
+ if (tc.function?.name) pending[idx].name += tc.function.name;
160
+ if (tc.function?.arguments) pending[idx].arguments += tc.function.arguments;
161
+ if (pending[idx].id && pending[idx].name && !startedIds.has(pending[idx].id)) {
162
+ startedIds.add(pending[idx].id);
163
+ yield {
164
+ type: "toolCallStart",
165
+ id: pending[idx].id,
166
+ name: pending[idx].name
167
+ };
168
+ }
169
+ }
170
+ }
171
+ if (finishReason === "tool_calls") {
172
+ if (req.signal?.aborted) {
173
+ yield { type: "end", finishReason: "aborted" };
174
+ return;
175
+ }
176
+ for (const tc of Object.values(pending)) {
177
+ if (!tc.id || !tc.name) continue;
178
+ if (toolCallsEmitted.has(tc.id)) continue;
179
+ toolCallsEmitted.add(tc.id);
180
+ let args = {};
181
+ try {
182
+ args = tc.arguments ? JSON.parse(tc.arguments) : {};
183
+ } catch {
184
+ args = {};
185
+ }
186
+ yield {
187
+ type: "toolCall",
188
+ id: tc.id,
189
+ name: tc.name,
190
+ arguments: args
191
+ };
192
+ }
193
+ finalFinishReason = "tool";
194
+ finalRawReason = finishReason;
195
+ } else if (finishReason) {
196
+ finalFinishReason = mapFinishReason(finishReason);
197
+ finalRawReason = finishReason;
198
+ }
199
+ }
200
+ } catch (err) {
201
+ if (isAbortError(err)) {
202
+ yield { type: "end", finishReason: "aborted" };
203
+ return;
204
+ }
205
+ throw err;
206
+ }
207
+ const endEvent = {
208
+ type: "end",
209
+ finishReason: finalFinishReason ?? "stop",
210
+ ...usage ? { usage } : {},
211
+ ...finalRawReason ? { rawReason: finalRawReason } : {}
212
+ };
213
+ yield endEvent;
214
+ }
215
+ function appendOpenAIToolResult(history, toolCallId, result) {
216
+ const content = typeof result === "string" ? result : JSON.stringify(result);
217
+ const wireMessage = {
218
+ role: "tool",
219
+ tool_call_id: toolCallId,
220
+ content
221
+ };
222
+ return [
223
+ ...history,
224
+ {
225
+ role: "tool",
226
+ content,
227
+ vendorRaw: wireMessage
228
+ }
229
+ ];
230
+ }
231
+ async function listOpenAICompatibleModels(client, knownModels) {
232
+ const result = await client.models.list();
233
+ const out = [];
234
+ for (const m of result.data) {
235
+ const known = knownModels.find((k) => k.id === m.id);
236
+ if (known) {
237
+ out.push(known);
238
+ } else {
239
+ out.push({
240
+ id: m.id,
241
+ capabilities: defaultCapabilitiesForUnknown(m.id)
242
+ });
243
+ }
244
+ }
245
+ return out;
246
+ }
247
+ function buildWireMessages(req) {
248
+ const out = [];
249
+ if (req.system) {
250
+ out.push({ role: "system", content: req.system });
251
+ }
252
+ for (const msg of req.messages) {
253
+ if (msg.vendorRaw && typeof msg.vendorRaw === "object") {
254
+ out.push(msg.vendorRaw);
255
+ } else {
256
+ out.push({ role: msg.role, content: msg.content });
257
+ }
258
+ }
259
+ return out;
260
+ }
261
+ function formatTools(tools) {
262
+ return tools.map((t) => ({
263
+ type: "function",
264
+ function: {
265
+ name: t.name,
266
+ description: t.description ?? "",
267
+ parameters: t.parameters ?? { type: "object", properties: {} }
268
+ }
269
+ }));
270
+ }
271
+ function capabilitiesFor(modelId, knownModels) {
272
+ const known = knownModels.find((k) => k.id === modelId);
273
+ if (known) return known.capabilities;
274
+ return defaultCapabilitiesForUnknown(modelId);
275
+ }
276
+ function defaultCapabilitiesForUnknown(modelId) {
277
+ const isReasoning = /^o[13]([-/]|$)/i.test(modelId);
278
+ if (isReasoning) {
279
+ return {
280
+ streaming: false,
281
+ tools: false,
282
+ vision: false,
283
+ systemPrompt: false
284
+ };
285
+ }
286
+ return {
287
+ streaming: true,
288
+ tools: true,
289
+ vision: false,
290
+ systemPrompt: true
291
+ };
292
+ }
293
+ function mapFinishReason(r) {
294
+ switch (r) {
295
+ case "stop":
296
+ return "stop";
297
+ case "tool_calls":
298
+ return "tool";
299
+ case "function_call":
300
+ return "tool";
301
+ case "length":
302
+ return "length";
303
+ case "content_filter":
304
+ return "filtered";
305
+ default:
306
+ return "stop";
307
+ }
308
+ }
309
+ function isAbortError(err) {
310
+ if (!err || typeof err !== "object") return false;
311
+ const e = err;
312
+ return e.name === "APIUserAbortError" || e.name === "AbortError" || e.code === "ABORT_ERR" || typeof e.message === "string" && /aborted/i.test(e.message);
313
+ }
314
+
315
+ // src/adapters/openai/manifest.ts
316
+ var OPENAI_KNOWN_MODELS = [
317
+ {
318
+ id: "gpt-4o",
319
+ displayName: "GPT-4o",
320
+ capabilities: {
321
+ streaming: true,
322
+ tools: true,
323
+ vision: true,
324
+ systemPrompt: true,
325
+ maxContextTokens: 128e3
326
+ }
327
+ },
328
+ {
329
+ id: "gpt-4o-mini",
330
+ displayName: "GPT-4o mini",
331
+ capabilities: {
332
+ streaming: true,
333
+ tools: true,
334
+ vision: true,
335
+ systemPrompt: true,
336
+ maxContextTokens: 128e3
337
+ }
338
+ },
339
+ {
340
+ id: "gpt-4-turbo",
341
+ displayName: "GPT-4 Turbo",
342
+ capabilities: {
343
+ streaming: true,
344
+ tools: true,
345
+ vision: true,
346
+ systemPrompt: true,
347
+ maxContextTokens: 128e3
348
+ }
349
+ },
350
+ {
351
+ id: "gpt-3.5-turbo",
352
+ displayName: "GPT-3.5 Turbo",
353
+ capabilities: {
354
+ streaming: true,
355
+ tools: true,
356
+ vision: false,
357
+ systemPrompt: true,
358
+ maxContextTokens: 16385
359
+ }
360
+ },
361
+ {
362
+ id: "o1-preview",
363
+ displayName: "o1 preview (reasoning)",
364
+ capabilities: {
365
+ streaming: false,
366
+ tools: false,
367
+ vision: false,
368
+ systemPrompt: false,
369
+ maxContextTokens: 128e3
370
+ }
371
+ },
372
+ {
373
+ id: "o1-mini",
374
+ displayName: "o1 mini (reasoning)",
375
+ capabilities: {
376
+ streaming: false,
377
+ tools: false,
378
+ vision: false,
379
+ systemPrompt: false,
380
+ maxContextTokens: 128e3
381
+ }
382
+ }
383
+ ];
384
+ var openAIManifest = {
385
+ vendor: "openai",
386
+ displayName: "OpenAI",
387
+ authKinds: [
388
+ {
389
+ kind: "apiKey",
390
+ displayName: "API Key",
391
+ fields: [
392
+ {
393
+ name: "apiKey",
394
+ label: "API Key",
395
+ type: "password",
396
+ required: true,
397
+ help: "Get an API key from https://platform.openai.com/api-keys"
398
+ },
399
+ {
400
+ name: "baseURL",
401
+ label: "Base URL",
402
+ type: "url",
403
+ required: false,
404
+ default: "https://api.openai.com/v1",
405
+ help: "Override for OpenAI-compatible endpoints (LM Studio, Ollama, vLLM, proxies)."
406
+ }
407
+ ]
408
+ }
409
+ ],
410
+ knownModels: OPENAI_KNOWN_MODELS,
411
+ supportsModelListing: true,
412
+ docsUrl: "https://platform.openai.com/docs/api-reference"
413
+ };
414
+
415
+ // src/adapters/openai/adapter.ts
416
+ var OpenAIAdapter = class {
417
+ vendor = openAIManifest.vendor;
418
+ acceptedAuth = ["apiKey"];
419
+ client;
420
+ init(auth, client) {
421
+ if (!auth.apiKey) {
422
+ throw new Error("OpenAIAdapter: apiKey is required");
423
+ }
424
+ this.client = new import_openai.default({
425
+ apiKey: auth.apiKey,
426
+ ...auth.baseURL ? { baseURL: auth.baseURL } : {},
427
+ ...client?.timeout !== void 0 ? { timeout: client.timeout } : {},
428
+ ...client?.maxRetries !== void 0 ? { maxRetries: client.maxRetries } : {}
429
+ });
430
+ }
431
+ stream(req) {
432
+ return streamFromOpenAI(this.ensureClient(), req, {
433
+ knownModels: openAIManifest.knownModels
434
+ });
435
+ }
436
+ appendToolResult(history, toolCallId, result) {
437
+ return appendOpenAIToolResult(history, toolCallId, result);
438
+ }
439
+ async listAvailableModels() {
440
+ return listOpenAICompatibleModels(this.ensureClient(), openAIManifest.knownModels);
441
+ }
442
+ async warmup() {
443
+ const client = this.ensureClient();
444
+ await client.models.list().catch(() => void 0);
445
+ }
446
+ ensureClient() {
447
+ if (!this.client) {
448
+ throw new Error("OpenAIAdapter: init() must be called before stream()/listAvailableModels()");
449
+ }
450
+ return this.client;
451
+ }
452
+ };
453
+
454
+ // src/adapters/openai/factory.ts
455
+ var openAIFactory = {
456
+ vendor: openAIManifest.vendor,
457
+ manifest: openAIManifest,
458
+ create: () => new OpenAIAdapter()
459
+ };
460
+ var deepseekManifest = {
461
+ vendor: "deepseek",
462
+ displayName: "DeepSeek",
463
+ authKinds: [
464
+ {
465
+ kind: "apiKey",
466
+ displayName: "API Key",
467
+ fields: [
468
+ {
469
+ name: "apiKey",
470
+ label: "API Key",
471
+ type: "password",
472
+ required: true,
473
+ help: "Get an API key from https://platform.deepseek.com/api_keys"
474
+ },
475
+ {
476
+ name: "baseURL",
477
+ label: "Base URL",
478
+ type: "url",
479
+ required: false,
480
+ default: "https://api.deepseek.com/v1",
481
+ help: "Override for self-hosted DeepSeek or proxy endpoints."
482
+ }
483
+ ]
484
+ }
485
+ ],
486
+ knownModels: [
487
+ {
488
+ id: "deepseek-chat",
489
+ displayName: "DeepSeek Chat",
490
+ capabilities: {
491
+ streaming: true,
492
+ tools: true,
493
+ vision: false,
494
+ systemPrompt: true,
495
+ maxContextTokens: 64e3
496
+ }
497
+ },
498
+ {
499
+ id: "deepseek-reasoner",
500
+ displayName: "DeepSeek Reasoner",
501
+ capabilities: {
502
+ streaming: true,
503
+ tools: false,
504
+ vision: false,
505
+ systemPrompt: true,
506
+ maxContextTokens: 64e3
507
+ }
508
+ }
509
+ ],
510
+ supportsModelListing: true,
511
+ docsUrl: "https://api-docs.deepseek.com/"
512
+ };
513
+ var DeepSeekAdapter = class extends OpenAIAdapter {
514
+ vendor = deepseekManifest.vendor;
515
+ init(auth, client) {
516
+ super.init(
517
+ {
518
+ ...auth,
519
+ baseURL: auth.baseURL ?? "https://api.deepseek.com/v1"
520
+ },
521
+ client
522
+ );
523
+ }
524
+ };
525
+ var deepseekFactory = {
526
+ vendor: deepseekManifest.vendor,
527
+ manifest: deepseekManifest,
528
+ create: () => new DeepSeekAdapter()
529
+ };
530
+
531
+ // src/adapters/anthropic/adapter.ts
532
+ var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
533
+
534
+ // src/adapters/anthropic/manifest.ts
535
+ var ANTHROPIC_KNOWN_MODELS = [
536
+ {
537
+ id: "claude-opus-4-7",
538
+ displayName: "Claude Opus 4.7",
539
+ capabilities: {
540
+ streaming: true,
541
+ tools: true,
542
+ vision: true,
543
+ systemPrompt: true,
544
+ maxContextTokens: 2e5
545
+ }
546
+ },
547
+ {
548
+ id: "claude-sonnet-4-6",
549
+ displayName: "Claude Sonnet 4.6",
550
+ capabilities: {
551
+ streaming: true,
552
+ tools: true,
553
+ vision: true,
554
+ systemPrompt: true,
555
+ maxContextTokens: 2e5
556
+ }
557
+ },
558
+ {
559
+ id: "claude-haiku-4-5-20251001",
560
+ displayName: "Claude Haiku 4.5",
561
+ capabilities: {
562
+ streaming: true,
563
+ tools: true,
564
+ vision: true,
565
+ systemPrompt: true,
566
+ maxContextTokens: 2e5
567
+ }
568
+ },
569
+ {
570
+ id: "claude-3-7-sonnet-20250219",
571
+ displayName: "Claude 3.7 Sonnet",
572
+ capabilities: {
573
+ streaming: true,
574
+ tools: true,
575
+ vision: true,
576
+ systemPrompt: true,
577
+ maxContextTokens: 2e5
578
+ }
579
+ },
580
+ {
581
+ id: "claude-3-5-sonnet-20241022",
582
+ displayName: "Claude 3.5 Sonnet",
583
+ capabilities: {
584
+ streaming: true,
585
+ tools: true,
586
+ vision: true,
587
+ systemPrompt: true,
588
+ maxContextTokens: 2e5
589
+ }
590
+ },
591
+ {
592
+ id: "claude-3-5-haiku-20241022",
593
+ displayName: "Claude 3.5 Haiku",
594
+ capabilities: {
595
+ streaming: true,
596
+ tools: true,
597
+ vision: false,
598
+ systemPrompt: true,
599
+ maxContextTokens: 2e5
600
+ }
601
+ }
602
+ ];
603
+ var anthropicManifest = {
604
+ vendor: "anthropic",
605
+ displayName: "Anthropic Claude",
606
+ authKinds: [
607
+ {
608
+ kind: "apiKey",
609
+ displayName: "API Key",
610
+ fields: [
611
+ {
612
+ name: "apiKey",
613
+ label: "API Key",
614
+ type: "password",
615
+ required: true,
616
+ help: "Get an API key from https://console.anthropic.com/settings/keys"
617
+ },
618
+ {
619
+ name: "baseURL",
620
+ label: "Base URL",
621
+ type: "url",
622
+ required: false,
623
+ default: "https://api.anthropic.com",
624
+ help: "Override for proxies or enterprise deployments."
625
+ }
626
+ ]
627
+ }
628
+ ],
629
+ knownModels: ANTHROPIC_KNOWN_MODELS,
630
+ supportsModelListing: true,
631
+ docsUrl: "https://docs.anthropic.com/en/api/overview"
632
+ };
633
+
634
+ // src/adapters/anthropic/adapter.ts
635
+ var AnthropicAdapter = class {
636
+ vendor = anthropicManifest.vendor;
637
+ acceptedAuth = ["apiKey"];
638
+ client;
639
+ init(auth, client) {
640
+ if (!auth.apiKey) {
641
+ throw new Error("AnthropicAdapter: apiKey is required");
642
+ }
643
+ this.client = new import_sdk.default({
644
+ apiKey: auth.apiKey,
645
+ ...auth.baseURL ? { baseURL: auth.baseURL } : {},
646
+ ...client?.timeout !== void 0 ? { timeout: client.timeout } : {},
647
+ ...client?.maxRetries !== void 0 ? { maxRetries: client.maxRetries } : {}
648
+ });
649
+ }
650
+ async *stream(req) {
651
+ assertValidRequest(req);
652
+ const client = this.ensureClient();
653
+ if (req.signal?.aborted) {
654
+ yield { type: "end", finishReason: "aborted" };
655
+ return;
656
+ }
657
+ const messages = buildWireMessages2(req);
658
+ const tools = req.tools && req.tools.length > 0 ? formatTools2(req.tools) : void 0;
659
+ const body = {
660
+ model: req.model,
661
+ messages,
662
+ max_tokens: req.maxTokens ?? 4096,
663
+ stream: true
664
+ };
665
+ if (req.system) body.system = req.system;
666
+ if (tools) body.tools = tools;
667
+ if (req.temperature !== void 0) body.temperature = req.temperature;
668
+ let stream;
669
+ try {
670
+ stream = await client.messages.create(
671
+ body,
672
+ { signal: req.signal }
673
+ );
674
+ } catch (err) {
675
+ if (isAbortError2(err)) {
676
+ yield { type: "end", finishReason: "aborted" };
677
+ return;
678
+ }
679
+ throw err;
680
+ }
681
+ let currentToolUse = null;
682
+ const completedToolCalls = [];
683
+ let stopReason;
684
+ let inputTokens;
685
+ let outputTokens;
686
+ try {
687
+ for await (const event of stream) {
688
+ if (req.signal?.aborted) {
689
+ yield { type: "end", finishReason: "aborted" };
690
+ return;
691
+ }
692
+ switch (event.type) {
693
+ case "message_start":
694
+ inputTokens = event.message?.usage?.input_tokens;
695
+ break;
696
+ case "content_block_start": {
697
+ const block = event.content_block;
698
+ if (block?.type === "tool_use") {
699
+ currentToolUse = {
700
+ id: block.id ?? "",
701
+ name: block.name ?? "",
702
+ argumentsText: ""
703
+ };
704
+ if (currentToolUse.id && currentToolUse.name) {
705
+ yield {
706
+ type: "toolCallStart",
707
+ id: currentToolUse.id,
708
+ name: currentToolUse.name
709
+ };
710
+ }
711
+ }
712
+ break;
713
+ }
714
+ case "content_block_delta": {
715
+ const delta = event.delta;
716
+ if (delta?.type === "text_delta" && delta.text) {
717
+ yield { type: "token", text: delta.text };
718
+ } else if (delta?.type === "input_json_delta" && currentToolUse && delta.partial_json) {
719
+ currentToolUse.argumentsText += delta.partial_json;
720
+ }
721
+ break;
722
+ }
723
+ case "content_block_stop":
724
+ if (currentToolUse && currentToolUse.id && currentToolUse.name) {
725
+ let parsed = {};
726
+ try {
727
+ parsed = currentToolUse.argumentsText ? JSON.parse(currentToolUse.argumentsText) : {};
728
+ } catch {
729
+ parsed = {};
730
+ }
731
+ completedToolCalls.push({
732
+ id: currentToolUse.id,
733
+ name: currentToolUse.name,
734
+ arguments: parsed
735
+ });
736
+ }
737
+ currentToolUse = null;
738
+ break;
739
+ case "message_delta":
740
+ if (event.delta?.stop_reason) {
741
+ stopReason = event.delta.stop_reason;
742
+ }
743
+ if (event.usage?.output_tokens !== void 0) {
744
+ outputTokens = event.usage.output_tokens;
745
+ }
746
+ break;
747
+ case "message_stop":
748
+ break;
749
+ default:
750
+ break;
751
+ }
752
+ }
753
+ } catch (err) {
754
+ if (isAbortError2(err)) {
755
+ yield { type: "end", finishReason: "aborted" };
756
+ return;
757
+ }
758
+ throw err;
759
+ }
760
+ if (req.signal?.aborted) {
761
+ yield { type: "end", finishReason: "aborted" };
762
+ return;
763
+ }
764
+ for (const tc of completedToolCalls) {
765
+ yield {
766
+ type: "toolCall",
767
+ id: tc.id,
768
+ name: tc.name,
769
+ arguments: tc.arguments
770
+ };
771
+ }
772
+ const finishReason = mapStopReason(stopReason, completedToolCalls.length > 0);
773
+ const usage = inputTokens !== void 0 || outputTokens !== void 0 ? {
774
+ ...inputTokens !== void 0 ? { inputTokens } : {},
775
+ ...outputTokens !== void 0 ? { outputTokens } : {},
776
+ ...inputTokens !== void 0 && outputTokens !== void 0 ? { totalTokens: inputTokens + outputTokens } : {}
777
+ } : void 0;
778
+ const endEvent = {
779
+ type: "end",
780
+ finishReason,
781
+ ...usage ? { usage } : {},
782
+ ...stopReason ? { rawReason: stopReason } : {}
783
+ };
784
+ yield endEvent;
785
+ }
786
+ appendToolResult(history, toolCallId, result) {
787
+ const content = typeof result === "string" ? result : JSON.stringify(result);
788
+ const wireMessage = {
789
+ role: "user",
790
+ content: [
791
+ {
792
+ type: "tool_result",
793
+ tool_use_id: toolCallId,
794
+ content
795
+ }
796
+ ]
797
+ };
798
+ return [
799
+ ...history,
800
+ {
801
+ role: "tool",
802
+ content,
803
+ vendorRaw: wireMessage
804
+ }
805
+ ];
806
+ }
807
+ async listAvailableModels() {
808
+ const client = this.ensureClient();
809
+ const result = await client.models.list();
810
+ const models = [];
811
+ for (const m of result.data) {
812
+ const known = anthropicManifest.knownModels.find((k) => k.id === m.id);
813
+ if (known) {
814
+ models.push(known);
815
+ } else {
816
+ models.push({
817
+ id: m.id,
818
+ displayName: m.display_name ?? void 0,
819
+ capabilities: defaultClaudeCapabilities()
820
+ });
821
+ }
822
+ }
823
+ return models;
824
+ }
825
+ async warmup() {
826
+ const client = this.ensureClient();
827
+ await client.models.list().catch(() => void 0);
828
+ }
829
+ ensureClient() {
830
+ if (!this.client) {
831
+ throw new Error("AnthropicAdapter: init() must be called before stream()/listAvailableModels()");
832
+ }
833
+ return this.client;
834
+ }
835
+ };
836
+ function buildWireMessages2(req) {
837
+ const out = [];
838
+ for (const msg of req.messages) {
839
+ if (msg.vendorRaw && typeof msg.vendorRaw === "object") {
840
+ out.push(msg.vendorRaw);
841
+ } else {
842
+ out.push({ role: msg.role, content: msg.content });
843
+ }
844
+ }
845
+ return out;
846
+ }
847
+ function formatTools2(tools) {
848
+ return tools.map((t) => ({
849
+ name: t.name,
850
+ description: t.description ?? "",
851
+ input_schema: t.parameters ?? { type: "object", properties: {} }
852
+ }));
853
+ }
854
+ function mapStopReason(r, hadToolCalls) {
855
+ if (hadToolCalls) return "tool";
856
+ switch (r) {
857
+ case "end_turn":
858
+ case "stop_sequence":
859
+ return "stop";
860
+ case "tool_use":
861
+ return "tool";
862
+ case "max_tokens":
863
+ return "length";
864
+ default:
865
+ return "stop";
866
+ }
867
+ }
868
+ function defaultClaudeCapabilities() {
869
+ return {
870
+ streaming: true,
871
+ tools: true,
872
+ vision: true,
873
+ systemPrompt: true
874
+ };
875
+ }
876
+ function isAbortError2(err) {
877
+ if (!err || typeof err !== "object") return false;
878
+ const e = err;
879
+ return e.name === "APIUserAbortError" || e.name === "AbortError" || e.code === "ABORT_ERR" || typeof e.message === "string" && /aborted/i.test(e.message);
880
+ }
881
+
882
+ // src/adapters/anthropic/factory.ts
883
+ var anthropicFactory = {
884
+ vendor: anthropicManifest.vendor,
885
+ manifest: anthropicManifest,
886
+ create: () => new AnthropicAdapter()
887
+ };
888
+
889
+ // src/adapters/google/adapter.ts
890
+ var import_genai = require("@google/genai");
891
+
892
+ // src/adapters/google/_streaming.ts
893
+ async function* streamFromGemini(client, req) {
894
+ assertValidRequest(req);
895
+ if (req.signal?.aborted) {
896
+ yield { type: "end", finishReason: "aborted" };
897
+ return;
898
+ }
899
+ const contents = buildWireContents(req);
900
+ const tools = req.tools && req.tools.length > 0 ? formatTools3(req.tools) : void 0;
901
+ const config = {};
902
+ if (req.system) {
903
+ config.systemInstruction = { parts: [{ text: req.system }] };
904
+ }
905
+ if (tools) config.tools = tools;
906
+ if (req.temperature !== void 0) config.temperature = req.temperature;
907
+ if (req.maxTokens !== void 0) config.maxOutputTokens = req.maxTokens;
908
+ if (req.signal) config.abortSignal = req.signal;
909
+ let stream;
910
+ try {
911
+ stream = await client.models.generateContentStream({
912
+ model: req.model,
913
+ contents,
914
+ config
915
+ });
916
+ } catch (err) {
917
+ if (isAbortError3(err)) {
918
+ yield { type: "end", finishReason: "aborted" };
919
+ return;
920
+ }
921
+ throw err;
922
+ }
923
+ const toolCallCounter = /* @__PURE__ */ new Map();
924
+ const completedToolCalls = [];
925
+ let stopReason;
926
+ let inputTokens;
927
+ let outputTokens;
928
+ let totalTokens;
929
+ try {
930
+ for await (const chunk of stream) {
931
+ if (req.signal?.aborted) {
932
+ yield { type: "end", finishReason: "aborted" };
933
+ return;
934
+ }
935
+ const usage2 = chunk.usageMetadata;
936
+ if (usage2) {
937
+ if (usage2.promptTokenCount !== void 0) inputTokens = usage2.promptTokenCount;
938
+ if (usage2.candidatesTokenCount !== void 0) outputTokens = usage2.candidatesTokenCount;
939
+ if (usage2.totalTokenCount !== void 0) totalTokens = usage2.totalTokenCount;
940
+ }
941
+ const candidate = chunk.candidates?.[0];
942
+ if (!candidate?.content?.parts) {
943
+ if (candidate?.finishReason) stopReason = candidate.finishReason;
944
+ continue;
945
+ }
946
+ for (const part of candidate.content.parts) {
947
+ if (typeof part.text === "string" && part.text.length > 0) {
948
+ yield { type: "token", text: part.text };
949
+ }
950
+ if (part.functionCall) {
951
+ const name = part.functionCall.name ?? "";
952
+ if (!name) continue;
953
+ const count = toolCallCounter.get(name) ?? 0;
954
+ toolCallCounter.set(name, count + 1);
955
+ const id = count === 0 ? name : `${name}#${count}`;
956
+ yield { type: "toolCallStart", id, name };
957
+ completedToolCalls.push({
958
+ id,
959
+ name,
960
+ arguments: part.functionCall.args ?? {}
961
+ });
962
+ }
963
+ }
964
+ if (candidate.finishReason) {
965
+ stopReason = candidate.finishReason;
966
+ }
967
+ }
968
+ } catch (err) {
969
+ if (isAbortError3(err)) {
970
+ yield { type: "end", finishReason: "aborted" };
971
+ return;
972
+ }
973
+ throw err;
974
+ }
975
+ if (req.signal?.aborted) {
976
+ yield { type: "end", finishReason: "aborted" };
977
+ return;
978
+ }
979
+ for (const tc of completedToolCalls) {
980
+ yield {
981
+ type: "toolCall",
982
+ id: tc.id,
983
+ name: tc.name,
984
+ arguments: tc.arguments
985
+ };
986
+ }
987
+ const finishReason = mapFinishReason2(stopReason, completedToolCalls.length > 0);
988
+ const usage = inputTokens !== void 0 || outputTokens !== void 0 || totalTokens !== void 0 ? {
989
+ ...inputTokens !== void 0 ? { inputTokens } : {},
990
+ ...outputTokens !== void 0 ? { outputTokens } : {},
991
+ ...totalTokens !== void 0 ? { totalTokens } : {}
992
+ } : void 0;
993
+ const endEvent = {
994
+ type: "end",
995
+ finishReason,
996
+ ...usage ? { usage } : {},
997
+ ...stopReason ? { rawReason: stopReason } : {}
998
+ };
999
+ yield endEvent;
1000
+ }
1001
+ function appendGeminiToolResult(history, toolCallId, result) {
1002
+ const name = parseToolName(toolCallId);
1003
+ const content = typeof result === "string" ? result : JSON.stringify(result);
1004
+ const wireMessage = {
1005
+ role: "user",
1006
+ parts: [
1007
+ {
1008
+ functionResponse: {
1009
+ name,
1010
+ response: { result: content }
1011
+ }
1012
+ }
1013
+ ]
1014
+ };
1015
+ return [
1016
+ ...history,
1017
+ {
1018
+ role: "tool",
1019
+ content,
1020
+ vendorRaw: wireMessage
1021
+ }
1022
+ ];
1023
+ }
1024
+ async function listGeminiModels(client, knownModels) {
1025
+ const out = [];
1026
+ const pager = await client.models.list();
1027
+ for await (const m of pager) {
1028
+ const id = stripModelPrefix(m.name ?? "");
1029
+ if (!id) continue;
1030
+ const known = knownModels.find((k) => k.id === id);
1031
+ if (known) {
1032
+ out.push(known);
1033
+ } else {
1034
+ out.push({
1035
+ id,
1036
+ displayName: m.displayName ?? void 0,
1037
+ capabilities: defaultGeminiCapabilities()
1038
+ });
1039
+ }
1040
+ }
1041
+ return out;
1042
+ }
1043
+ function buildWireContents(req) {
1044
+ const out = [];
1045
+ for (const msg of req.messages) {
1046
+ if (msg.vendorRaw && typeof msg.vendorRaw === "object") {
1047
+ out.push(msg.vendorRaw);
1048
+ continue;
1049
+ }
1050
+ const text = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1051
+ out.push({
1052
+ role: toGeminiRole(msg.role),
1053
+ parts: [{ text }]
1054
+ });
1055
+ }
1056
+ return out;
1057
+ }
1058
+ function toGeminiRole(role) {
1059
+ return role === "assistant" || role === "model" ? "model" : "user";
1060
+ }
1061
+ function formatTools3(tools) {
1062
+ return [
1063
+ {
1064
+ functionDeclarations: tools.map((t) => ({
1065
+ name: t.name,
1066
+ description: t.description ?? "",
1067
+ parameters: t.parameters ?? { type: "object", properties: {} }
1068
+ }))
1069
+ }
1070
+ ];
1071
+ }
1072
+ function mapFinishReason2(r, hadToolCalls) {
1073
+ if (hadToolCalls && (r === "STOP" || r === "TOOL_CALLS" || !r)) return "tool";
1074
+ switch (r) {
1075
+ case "STOP":
1076
+ return "stop";
1077
+ case "MAX_TOKENS":
1078
+ return "length";
1079
+ case "SAFETY":
1080
+ case "RECITATION":
1081
+ return "filtered";
1082
+ case "TOOL_CALLS":
1083
+ return "tool";
1084
+ default:
1085
+ return "stop";
1086
+ }
1087
+ }
1088
+ function parseToolName(id) {
1089
+ const hashIdx = id.lastIndexOf("#");
1090
+ if (hashIdx === -1) return id;
1091
+ const suffix = id.slice(hashIdx + 1);
1092
+ if (/^\d+$/.test(suffix)) return id.slice(0, hashIdx);
1093
+ return id;
1094
+ }
1095
+ function stripModelPrefix(name) {
1096
+ return name.startsWith("models/") ? name.slice("models/".length) : name;
1097
+ }
1098
+ function defaultGeminiCapabilities() {
1099
+ return {
1100
+ streaming: true,
1101
+ tools: true,
1102
+ vision: true,
1103
+ systemPrompt: true
1104
+ };
1105
+ }
1106
+ function isAbortError3(err) {
1107
+ if (!err || typeof err !== "object") return false;
1108
+ const e = err;
1109
+ return e.name === "APIUserAbortError" || e.name === "AbortError" || e.code === "ABORT_ERR" || typeof e.message === "string" && /aborted/i.test(e.message);
1110
+ }
1111
+
1112
+ // src/adapters/google/manifest.ts
1113
+ var GOOGLE_KNOWN_MODELS = [
1114
+ {
1115
+ id: "gemini-2.5-pro",
1116
+ displayName: "Gemini 2.5 Pro",
1117
+ capabilities: {
1118
+ streaming: true,
1119
+ tools: true,
1120
+ vision: true,
1121
+ systemPrompt: true,
1122
+ maxContextTokens: 1e6
1123
+ }
1124
+ },
1125
+ {
1126
+ id: "gemini-2.5-flash",
1127
+ displayName: "Gemini 2.5 Flash",
1128
+ capabilities: {
1129
+ streaming: true,
1130
+ tools: true,
1131
+ vision: true,
1132
+ systemPrompt: true,
1133
+ maxContextTokens: 1e6
1134
+ }
1135
+ },
1136
+ {
1137
+ id: "gemini-2.0-flash",
1138
+ displayName: "Gemini 2.0 Flash",
1139
+ capabilities: {
1140
+ streaming: true,
1141
+ tools: true,
1142
+ vision: true,
1143
+ systemPrompt: true,
1144
+ maxContextTokens: 1e6
1145
+ }
1146
+ },
1147
+ {
1148
+ id: "gemini-2.0-flash-lite",
1149
+ displayName: "Gemini 2.0 Flash Lite",
1150
+ capabilities: {
1151
+ streaming: true,
1152
+ tools: true,
1153
+ vision: false,
1154
+ systemPrompt: true,
1155
+ maxContextTokens: 1e6
1156
+ }
1157
+ },
1158
+ {
1159
+ id: "gemini-1.5-pro",
1160
+ displayName: "Gemini 1.5 Pro",
1161
+ capabilities: {
1162
+ streaming: true,
1163
+ tools: true,
1164
+ vision: true,
1165
+ systemPrompt: true,
1166
+ maxContextTokens: 2e6
1167
+ }
1168
+ },
1169
+ {
1170
+ id: "gemini-1.5-flash",
1171
+ displayName: "Gemini 1.5 Flash",
1172
+ capabilities: {
1173
+ streaming: true,
1174
+ tools: true,
1175
+ vision: true,
1176
+ systemPrompt: true,
1177
+ maxContextTokens: 1e6
1178
+ }
1179
+ }
1180
+ ];
1181
+ var googleManifest = {
1182
+ vendor: "google",
1183
+ displayName: "Google Gemini",
1184
+ authKinds: [
1185
+ {
1186
+ kind: "googleApiKey",
1187
+ displayName: "API Key",
1188
+ fields: [
1189
+ {
1190
+ name: "apiKey",
1191
+ label: "API Key",
1192
+ type: "password",
1193
+ required: true,
1194
+ help: "Get an API key from https://aistudio.google.com/apikey"
1195
+ }
1196
+ ]
1197
+ }
1198
+ ],
1199
+ knownModels: GOOGLE_KNOWN_MODELS,
1200
+ supportsModelListing: true,
1201
+ docsUrl: "https://ai.google.dev/gemini-api/docs"
1202
+ };
1203
+
1204
+ // src/adapters/google/adapter.ts
1205
+ var GoogleAdapter = class {
1206
+ vendor = googleManifest.vendor;
1207
+ acceptedAuth = ["googleApiKey"];
1208
+ client;
1209
+ init(auth, _client) {
1210
+ if (auth.kind !== "googleApiKey") {
1211
+ throw new Error(
1212
+ `GoogleAdapter: unsupported auth kind '${auth.kind}'`
1213
+ );
1214
+ }
1215
+ if (!auth.apiKey) {
1216
+ throw new Error("GoogleAdapter: apiKey is required");
1217
+ }
1218
+ this.client = new import_genai.GoogleGenAI({ apiKey: auth.apiKey });
1219
+ }
1220
+ stream(req) {
1221
+ return streamFromGemini(this.ensureClient(), req);
1222
+ }
1223
+ appendToolResult(history, toolCallId, result) {
1224
+ return appendGeminiToolResult(history, toolCallId, result);
1225
+ }
1226
+ async listAvailableModels() {
1227
+ return listGeminiModels(this.ensureClient(), googleManifest.knownModels);
1228
+ }
1229
+ async warmup() {
1230
+ }
1231
+ ensureClient() {
1232
+ if (!this.client) {
1233
+ throw new Error("GoogleAdapter: init() must be called before stream()/listAvailableModels()");
1234
+ }
1235
+ return this.client;
1236
+ }
1237
+ };
1238
+
1239
+ // src/adapters/google/factory.ts
1240
+ var googleFactory = {
1241
+ vendor: googleManifest.vendor,
1242
+ manifest: googleManifest,
1243
+ create: () => new GoogleAdapter()
1244
+ };
1245
+
1246
+ // src/adapters/vertex-gemini/adapter.ts
1247
+ var import_genai2 = require("@google/genai");
1248
+
1249
+ // src/adapters/vertex-gemini/manifest.ts
1250
+ var VERTEX_GEMINI_KNOWN_MODELS = [
1251
+ {
1252
+ id: "gemini-2.5-pro",
1253
+ displayName: "Gemini 2.5 Pro",
1254
+ capabilities: {
1255
+ streaming: true,
1256
+ tools: true,
1257
+ vision: true,
1258
+ systemPrompt: true,
1259
+ maxContextTokens: 1e6
1260
+ }
1261
+ },
1262
+ {
1263
+ id: "gemini-2.5-flash",
1264
+ displayName: "Gemini 2.5 Flash",
1265
+ capabilities: {
1266
+ streaming: true,
1267
+ tools: true,
1268
+ vision: true,
1269
+ systemPrompt: true,
1270
+ maxContextTokens: 1e6
1271
+ }
1272
+ },
1273
+ {
1274
+ id: "gemini-2.0-flash",
1275
+ displayName: "Gemini 2.0 Flash",
1276
+ capabilities: {
1277
+ streaming: true,
1278
+ tools: true,
1279
+ vision: true,
1280
+ systemPrompt: true,
1281
+ maxContextTokens: 1e6
1282
+ }
1283
+ },
1284
+ {
1285
+ id: "gemini-1.5-pro",
1286
+ displayName: "Gemini 1.5 Pro",
1287
+ capabilities: {
1288
+ streaming: true,
1289
+ tools: true,
1290
+ vision: true,
1291
+ systemPrompt: true,
1292
+ maxContextTokens: 2e6
1293
+ }
1294
+ },
1295
+ {
1296
+ id: "gemini-1.5-flash",
1297
+ displayName: "Gemini 1.5 Flash",
1298
+ capabilities: {
1299
+ streaming: true,
1300
+ tools: true,
1301
+ vision: true,
1302
+ systemPrompt: true,
1303
+ maxContextTokens: 1e6
1304
+ }
1305
+ }
1306
+ ];
1307
+ var vertexGeminiManifest = {
1308
+ vendor: "vertex-gemini",
1309
+ displayName: "Vertex AI \u2014 Gemini",
1310
+ authKinds: [
1311
+ {
1312
+ kind: "vertexServiceAccount",
1313
+ displayName: "Service Account JSON",
1314
+ fields: [
1315
+ {
1316
+ name: "credentials",
1317
+ label: "Service Account Key (JSON)",
1318
+ type: "json-file",
1319
+ required: true,
1320
+ help: "Upload the service account key JSON from Google Cloud Console."
1321
+ },
1322
+ {
1323
+ name: "projectId",
1324
+ label: "Project ID",
1325
+ type: "text",
1326
+ required: true,
1327
+ help: "GCP project that hosts the Vertex AI deployment."
1328
+ },
1329
+ {
1330
+ name: "location",
1331
+ label: "Region",
1332
+ type: "select",
1333
+ required: true,
1334
+ default: "us-central1",
1335
+ options: [
1336
+ { value: "us-central1", label: "us-central1" },
1337
+ { value: "us-east1", label: "us-east1" },
1338
+ { value: "us-east4", label: "us-east4" },
1339
+ { value: "us-west1", label: "us-west1" },
1340
+ { value: "us-west4", label: "us-west4" },
1341
+ { value: "europe-west1", label: "europe-west1" },
1342
+ { value: "europe-west2", label: "europe-west2" },
1343
+ { value: "europe-west3", label: "europe-west3" },
1344
+ { value: "europe-west4", label: "europe-west4" },
1345
+ { value: "asia-east1", label: "asia-east1" },
1346
+ { value: "asia-northeast1", label: "asia-northeast1" },
1347
+ { value: "asia-southeast1", label: "asia-southeast1" }
1348
+ ]
1349
+ }
1350
+ ]
1351
+ }
1352
+ ],
1353
+ knownModels: VERTEX_GEMINI_KNOWN_MODELS,
1354
+ supportsModelListing: true,
1355
+ docsUrl: "https://cloud.google.com/vertex-ai/generative-ai/docs"
1356
+ };
1357
+
1358
+ // src/adapters/vertex-gemini/adapter.ts
1359
+ var VertexGeminiAdapter = class {
1360
+ vendor = vertexGeminiManifest.vendor;
1361
+ acceptedAuth = ["vertexServiceAccount"];
1362
+ client;
1363
+ init(auth, _client) {
1364
+ if (auth.kind !== "vertexServiceAccount") {
1365
+ throw new Error(
1366
+ `VertexGeminiAdapter: unsupported auth kind '${auth.kind}'`
1367
+ );
1368
+ }
1369
+ if (!auth.credentials) {
1370
+ throw new Error("VertexGeminiAdapter: service-account credentials are required");
1371
+ }
1372
+ if (!auth.projectId) {
1373
+ throw new Error("VertexGeminiAdapter: projectId is required");
1374
+ }
1375
+ if (!auth.location) {
1376
+ throw new Error("VertexGeminiAdapter: location is required");
1377
+ }
1378
+ this.client = new import_genai2.GoogleGenAI({
1379
+ vertexai: true,
1380
+ project: auth.projectId,
1381
+ location: auth.location,
1382
+ googleAuthOptions: {
1383
+ credentials: auth.credentials
1384
+ }
1385
+ });
1386
+ }
1387
+ stream(req) {
1388
+ return streamFromGemini(this.ensureClient(), req);
1389
+ }
1390
+ appendToolResult(history, toolCallId, result) {
1391
+ return appendGeminiToolResult(history, toolCallId, result);
1392
+ }
1393
+ async listAvailableModels() {
1394
+ return listGeminiModels(this.ensureClient(), vertexGeminiManifest.knownModels);
1395
+ }
1396
+ async warmup() {
1397
+ }
1398
+ ensureClient() {
1399
+ if (!this.client) {
1400
+ throw new Error(
1401
+ "VertexGeminiAdapter: init() must be called before stream()/listAvailableModels()"
1402
+ );
1403
+ }
1404
+ return this.client;
1405
+ }
1406
+ };
1407
+
1408
+ // src/adapters/vertex-gemini/factory.ts
1409
+ var vertexGeminiFactory = {
1410
+ vendor: vertexGeminiManifest.vendor,
1411
+ manifest: vertexGeminiManifest,
1412
+ create: () => new VertexGeminiAdapter()
1413
+ };
1414
+
1415
+ // src/adapters/vertex-openai/adapter.ts
1416
+ var import_openai2 = __toESM(require("openai"), 1);
1417
+ var import_google_auth_library = require("google-auth-library");
1418
+
1419
+ // src/adapters/vertex-openai/manifest.ts
1420
+ var VERTEX_OPENAI_KNOWN_MODELS = [
1421
+ {
1422
+ id: "mistral-large",
1423
+ displayName: "Mistral Large (on Vertex)",
1424
+ capabilities: {
1425
+ streaming: true,
1426
+ tools: true,
1427
+ vision: false,
1428
+ systemPrompt: true,
1429
+ maxContextTokens: 128e3
1430
+ }
1431
+ },
1432
+ {
1433
+ id: "mistral-small",
1434
+ displayName: "Mistral Small (on Vertex)",
1435
+ capabilities: {
1436
+ streaming: true,
1437
+ tools: true,
1438
+ vision: false,
1439
+ systemPrompt: true,
1440
+ maxContextTokens: 32e3
1441
+ }
1442
+ },
1443
+ {
1444
+ id: "meta/llama-3.3-70b-instruct-maas",
1445
+ displayName: "Llama 3.3 70B Instruct (on Vertex)",
1446
+ capabilities: {
1447
+ streaming: true,
1448
+ tools: true,
1449
+ vision: false,
1450
+ systemPrompt: true,
1451
+ maxContextTokens: 128e3
1452
+ }
1453
+ },
1454
+ {
1455
+ id: "meta/llama-3.1-405b-instruct-maas",
1456
+ displayName: "Llama 3.1 405B Instruct (on Vertex)",
1457
+ capabilities: {
1458
+ streaming: true,
1459
+ tools: true,
1460
+ vision: false,
1461
+ systemPrompt: true,
1462
+ maxContextTokens: 128e3
1463
+ }
1464
+ }
1465
+ ];
1466
+ var vertexOpenAIManifest = {
1467
+ vendor: "vertex-openai",
1468
+ displayName: "Vertex AI \u2014 OpenAI-compatible",
1469
+ authKinds: [
1470
+ {
1471
+ kind: "vertexServiceAccount",
1472
+ displayName: "Service Account JSON",
1473
+ fields: [
1474
+ {
1475
+ name: "credentials",
1476
+ label: "Service Account Key (JSON)",
1477
+ type: "json-file",
1478
+ required: true,
1479
+ help: "Upload the service account key JSON from Google Cloud Console."
1480
+ },
1481
+ {
1482
+ name: "projectId",
1483
+ label: "Project ID",
1484
+ type: "text",
1485
+ required: true,
1486
+ help: "GCP project that hosts the Vertex AI deployment."
1487
+ },
1488
+ {
1489
+ name: "location",
1490
+ label: "Region",
1491
+ type: "select",
1492
+ required: true,
1493
+ default: "us-central1",
1494
+ options: [
1495
+ { value: "us-central1", label: "us-central1" },
1496
+ { value: "us-east4", label: "us-east4" },
1497
+ { value: "europe-west1", label: "europe-west1" },
1498
+ { value: "europe-west4", label: "europe-west4" },
1499
+ { value: "asia-southeast1", label: "asia-southeast1" }
1500
+ ]
1501
+ }
1502
+ ]
1503
+ }
1504
+ ],
1505
+ knownModels: VERTEX_OPENAI_KNOWN_MODELS,
1506
+ // The OpenAI-compatible endpoint on Vertex does not expose a /models list.
1507
+ supportsModelListing: false,
1508
+ docsUrl: "https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-openai"
1509
+ };
1510
+
1511
+ // src/adapters/vertex-openai/adapter.ts
1512
+ var VertexOpenAIAdapter = class {
1513
+ vendor = vertexOpenAIManifest.vendor;
1514
+ acceptedAuth = ["vertexServiceAccount"];
1515
+ client;
1516
+ init(auth, client) {
1517
+ if (auth.kind !== "vertexServiceAccount") {
1518
+ throw new Error(
1519
+ `VertexOpenAIAdapter: unsupported auth kind '${auth.kind}'`
1520
+ );
1521
+ }
1522
+ if (!auth.credentials) {
1523
+ throw new Error("VertexOpenAIAdapter: service-account credentials are required");
1524
+ }
1525
+ if (!auth.projectId) {
1526
+ throw new Error("VertexOpenAIAdapter: projectId is required");
1527
+ }
1528
+ if (!auth.location) {
1529
+ throw new Error("VertexOpenAIAdapter: location is required");
1530
+ }
1531
+ const baseURL = `https://${auth.location}-aiplatform.googleapis.com/v1/projects/${auth.projectId}/locations/${auth.location}/endpoints/openapi`;
1532
+ const googleAuth = new import_google_auth_library.GoogleAuth({
1533
+ credentials: auth.credentials,
1534
+ scopes: ["https://www.googleapis.com/auth/cloud-platform"]
1535
+ });
1536
+ const authedFetch = async (input, init2) => {
1537
+ const googleClient = await googleAuth.getClient();
1538
+ const token = await googleClient.getAccessToken();
1539
+ const headers = new Headers(init2?.headers);
1540
+ headers.set("Authorization", `Bearer ${token.token ?? ""}`);
1541
+ return fetch(input, { ...init2, headers });
1542
+ };
1543
+ this.client = new import_openai2.default({
1544
+ apiKey: "vertex-ai",
1545
+ baseURL,
1546
+ fetch: authedFetch,
1547
+ ...client?.timeout !== void 0 ? { timeout: client.timeout } : {},
1548
+ ...client?.maxRetries !== void 0 ? { maxRetries: client.maxRetries } : {}
1549
+ });
1550
+ }
1551
+ stream(req) {
1552
+ return streamFromOpenAI(this.ensureClient(), req, {
1553
+ knownModels: vertexOpenAIManifest.knownModels
1554
+ });
1555
+ }
1556
+ appendToolResult(history, toolCallId, result) {
1557
+ return appendOpenAIToolResult(history, toolCallId, result);
1558
+ }
1559
+ async listAvailableModels() {
1560
+ return [...vertexOpenAIManifest.knownModels];
1561
+ }
1562
+ async warmup() {
1563
+ }
1564
+ ensureClient() {
1565
+ if (!this.client) {
1566
+ throw new Error(
1567
+ "VertexOpenAIAdapter: init() must be called before stream()/listAvailableModels()"
1568
+ );
1569
+ }
1570
+ return this.client;
1571
+ }
1572
+ };
1573
+
1574
+ // src/adapters/vertex-openai/factory.ts
1575
+ var vertexOpenAIFactory = {
1576
+ vendor: vertexOpenAIManifest.vendor,
1577
+ manifest: vertexOpenAIManifest,
1578
+ create: () => new VertexOpenAIAdapter()
1579
+ };
1580
+
1581
+ // src/adapters/bedrock/adapter.ts
1582
+ var import_client_bedrock_runtime = require("@aws-sdk/client-bedrock-runtime");
1583
+
1584
+ // src/adapters/bedrock/manifest.ts
1585
+ var BEDROCK_KNOWN_MODELS = [
1586
+ {
1587
+ id: "anthropic.claude-opus-4-v1:0",
1588
+ displayName: "Claude Opus 4 (on Bedrock)",
1589
+ capabilities: {
1590
+ streaming: true,
1591
+ tools: true,
1592
+ vision: true,
1593
+ systemPrompt: true,
1594
+ maxContextTokens: 2e5
1595
+ }
1596
+ },
1597
+ {
1598
+ id: "anthropic.claude-sonnet-4-v1:0",
1599
+ displayName: "Claude Sonnet 4 (on Bedrock)",
1600
+ capabilities: {
1601
+ streaming: true,
1602
+ tools: true,
1603
+ vision: true,
1604
+ systemPrompt: true,
1605
+ maxContextTokens: 2e5
1606
+ }
1607
+ },
1608
+ {
1609
+ id: "anthropic.claude-3-7-sonnet-20250219-v1:0",
1610
+ displayName: "Claude 3.7 Sonnet (on Bedrock)",
1611
+ capabilities: {
1612
+ streaming: true,
1613
+ tools: true,
1614
+ vision: true,
1615
+ systemPrompt: true,
1616
+ maxContextTokens: 2e5
1617
+ }
1618
+ },
1619
+ {
1620
+ id: "anthropic.claude-3-5-sonnet-20241022-v2:0",
1621
+ displayName: "Claude 3.5 Sonnet v2 (on Bedrock)",
1622
+ capabilities: {
1623
+ streaming: true,
1624
+ tools: true,
1625
+ vision: true,
1626
+ systemPrompt: true,
1627
+ maxContextTokens: 2e5
1628
+ }
1629
+ },
1630
+ {
1631
+ id: "anthropic.claude-3-5-haiku-20241022-v1:0",
1632
+ displayName: "Claude 3.5 Haiku (on Bedrock)",
1633
+ capabilities: {
1634
+ streaming: true,
1635
+ tools: true,
1636
+ vision: false,
1637
+ systemPrompt: true,
1638
+ maxContextTokens: 2e5
1639
+ }
1640
+ },
1641
+ {
1642
+ id: "meta.llama3-3-70b-instruct-v1:0",
1643
+ displayName: "Llama 3.3 70B Instruct (on Bedrock)",
1644
+ capabilities: {
1645
+ streaming: true,
1646
+ tools: true,
1647
+ vision: false,
1648
+ systemPrompt: true,
1649
+ maxContextTokens: 128e3
1650
+ }
1651
+ },
1652
+ {
1653
+ id: "mistral.mistral-large-2407-v1:0",
1654
+ displayName: "Mistral Large (on Bedrock)",
1655
+ capabilities: {
1656
+ streaming: true,
1657
+ tools: true,
1658
+ vision: false,
1659
+ systemPrompt: true,
1660
+ maxContextTokens: 128e3
1661
+ }
1662
+ },
1663
+ {
1664
+ id: "amazon.nova-pro-v1:0",
1665
+ displayName: "Amazon Nova Pro",
1666
+ capabilities: {
1667
+ streaming: true,
1668
+ tools: true,
1669
+ vision: true,
1670
+ systemPrompt: true,
1671
+ maxContextTokens: 3e5
1672
+ }
1673
+ },
1674
+ {
1675
+ id: "amazon.nova-lite-v1:0",
1676
+ displayName: "Amazon Nova Lite",
1677
+ capabilities: {
1678
+ streaming: true,
1679
+ tools: true,
1680
+ vision: true,
1681
+ systemPrompt: true,
1682
+ maxContextTokens: 3e5
1683
+ }
1684
+ },
1685
+ {
1686
+ id: "amazon.nova-micro-v1:0",
1687
+ displayName: "Amazon Nova Micro",
1688
+ capabilities: {
1689
+ streaming: true,
1690
+ tools: true,
1691
+ vision: false,
1692
+ systemPrompt: true,
1693
+ maxContextTokens: 128e3
1694
+ }
1695
+ }
1696
+ ];
1697
+ var BEDROCK_REGIONS = [
1698
+ { value: "us-east-1", label: "us-east-1 (N. Virginia)" },
1699
+ { value: "us-east-2", label: "us-east-2 (Ohio)" },
1700
+ { value: "us-west-2", label: "us-west-2 (Oregon)" },
1701
+ { value: "eu-west-1", label: "eu-west-1 (Ireland)" },
1702
+ { value: "eu-west-3", label: "eu-west-3 (Paris)" },
1703
+ { value: "eu-central-1", label: "eu-central-1 (Frankfurt)" },
1704
+ { value: "ap-northeast-1", label: "ap-northeast-1 (Tokyo)" },
1705
+ { value: "ap-south-1", label: "ap-south-1 (Mumbai)" },
1706
+ { value: "ap-southeast-1", label: "ap-southeast-1 (Singapore)" },
1707
+ { value: "ap-southeast-2", label: "ap-southeast-2 (Sydney)" },
1708
+ { value: "ca-central-1", label: "ca-central-1 (Canada)" }
1709
+ ];
1710
+ var bedrockManifest = {
1711
+ vendor: "bedrock",
1712
+ displayName: "AWS Bedrock",
1713
+ authKinds: [
1714
+ {
1715
+ kind: "bedrockApiKey",
1716
+ displayName: "API Key",
1717
+ fields: [
1718
+ {
1719
+ name: "apiKey",
1720
+ label: "API Key",
1721
+ type: "password",
1722
+ required: true,
1723
+ help: "Bedrock API key (bearer token). Create one in the AWS console under Amazon Bedrock \u2192 API keys."
1724
+ },
1725
+ {
1726
+ name: "region",
1727
+ label: "Region",
1728
+ type: "select",
1729
+ required: true,
1730
+ default: "us-east-1",
1731
+ options: BEDROCK_REGIONS
1732
+ }
1733
+ ]
1734
+ },
1735
+ {
1736
+ kind: "bedrockIam",
1737
+ displayName: "IAM Credentials",
1738
+ fields: [
1739
+ {
1740
+ name: "accessKeyId",
1741
+ label: "Access Key ID",
1742
+ type: "text",
1743
+ required: true
1744
+ },
1745
+ {
1746
+ name: "secretAccessKey",
1747
+ label: "Secret Access Key",
1748
+ type: "password",
1749
+ required: true
1750
+ },
1751
+ {
1752
+ name: "sessionToken",
1753
+ label: "Session Token",
1754
+ type: "password",
1755
+ required: false,
1756
+ help: "Only required when using temporary credentials (e.g., STS)."
1757
+ },
1758
+ {
1759
+ name: "region",
1760
+ label: "Region",
1761
+ type: "select",
1762
+ required: true,
1763
+ default: "us-east-1",
1764
+ options: BEDROCK_REGIONS
1765
+ }
1766
+ ]
1767
+ }
1768
+ ],
1769
+ knownModels: BEDROCK_KNOWN_MODELS,
1770
+ // The Bedrock runtime client does not expose a `/models` listing — model
1771
+ // enumeration lives in `@aws-sdk/client-bedrock` (control plane), which we
1772
+ // don't pull in. Return the curated set from the manifest.
1773
+ supportsModelListing: false,
1774
+ docsUrl: "https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html"
1775
+ };
1776
+
1777
+ // src/adapters/bedrock/adapter.ts
1778
+ var BedrockAdapter = class {
1779
+ vendor = bedrockManifest.vendor;
1780
+ acceptedAuth = ["bedrockApiKey", "bedrockIam"];
1781
+ client;
1782
+ init(auth, client) {
1783
+ if (!auth.region) {
1784
+ throw new Error("BedrockAdapter: region is required");
1785
+ }
1786
+ const config = {
1787
+ region: auth.region,
1788
+ ...client?.endpoint ? { endpoint: client.endpoint } : {},
1789
+ ...client?.maxRetries !== void 0 ? { maxAttempts: client.maxRetries + 1 } : {}
1790
+ };
1791
+ if (auth.kind === "bedrockApiKey") {
1792
+ if (!auth.apiKey) {
1793
+ throw new Error("BedrockAdapter: apiKey is required for bedrockApiKey auth");
1794
+ }
1795
+ config.token = { token: auth.apiKey };
1796
+ config.authSchemePreference = ["httpBearerAuth"];
1797
+ } else if (auth.kind === "bedrockIam") {
1798
+ if (!auth.accessKeyId || !auth.secretAccessKey) {
1799
+ throw new Error("BedrockAdapter: accessKeyId and secretAccessKey required for bedrockIam auth");
1800
+ }
1801
+ config.credentials = {
1802
+ accessKeyId: auth.accessKeyId,
1803
+ secretAccessKey: auth.secretAccessKey,
1804
+ ...auth.sessionToken ? { sessionToken: auth.sessionToken } : {}
1805
+ };
1806
+ } else {
1807
+ throw new Error(
1808
+ `BedrockAdapter: unsupported auth kind '${auth.kind}'`
1809
+ );
1810
+ }
1811
+ this.client = new import_client_bedrock_runtime.BedrockRuntimeClient(config);
1812
+ }
1813
+ async *stream(req) {
1814
+ assertValidRequest(req);
1815
+ const client = this.ensureClient();
1816
+ if (req.signal?.aborted) {
1817
+ yield { type: "end", finishReason: "aborted" };
1818
+ return;
1819
+ }
1820
+ const messages = buildWireMessages3(req);
1821
+ const tools = req.tools && req.tools.length > 0 ? { tools: formatTools4(req.tools) } : void 0;
1822
+ const inferenceConfig = {};
1823
+ if (req.maxTokens !== void 0) inferenceConfig.maxTokens = req.maxTokens;
1824
+ if (req.temperature !== void 0) inferenceConfig.temperature = req.temperature;
1825
+ const commandInput = {
1826
+ modelId: req.model,
1827
+ messages
1828
+ };
1829
+ if (req.system) commandInput.system = [{ text: req.system }];
1830
+ if (tools) commandInput.toolConfig = tools;
1831
+ if (Object.keys(inferenceConfig).length > 0) {
1832
+ commandInput.inferenceConfig = inferenceConfig;
1833
+ }
1834
+ const command = new import_client_bedrock_runtime.ConverseStreamCommand(
1835
+ commandInput
1836
+ );
1837
+ let response;
1838
+ try {
1839
+ response = await client.send(command, { abortSignal: req.signal });
1840
+ } catch (err) {
1841
+ if (isAbortError4(err)) {
1842
+ yield { type: "end", finishReason: "aborted" };
1843
+ return;
1844
+ }
1845
+ throw err;
1846
+ }
1847
+ if (!response.stream) {
1848
+ yield { type: "end", finishReason: "stop" };
1849
+ return;
1850
+ }
1851
+ let currentToolUse = null;
1852
+ const completedToolCalls = [];
1853
+ let stopReason;
1854
+ let inputTokens;
1855
+ let outputTokens;
1856
+ let totalTokens;
1857
+ try {
1858
+ for await (const event of response.stream) {
1859
+ if (req.signal?.aborted) {
1860
+ yield { type: "end", finishReason: "aborted" };
1861
+ return;
1862
+ }
1863
+ if (event.contentBlockStart) {
1864
+ const start = event.contentBlockStart.start;
1865
+ if (start?.toolUse) {
1866
+ currentToolUse = {
1867
+ id: start.toolUse.toolUseId ?? "",
1868
+ name: start.toolUse.name ?? "",
1869
+ inputText: ""
1870
+ };
1871
+ if (currentToolUse.id && currentToolUse.name) {
1872
+ yield {
1873
+ type: "toolCallStart",
1874
+ id: currentToolUse.id,
1875
+ name: currentToolUse.name
1876
+ };
1877
+ }
1878
+ }
1879
+ } else if (event.contentBlockDelta) {
1880
+ const delta = event.contentBlockDelta.delta;
1881
+ if (delta?.text) {
1882
+ yield { type: "token", text: delta.text };
1883
+ }
1884
+ if (delta?.toolUse && currentToolUse && typeof delta.toolUse.input === "string") {
1885
+ currentToolUse.inputText += delta.toolUse.input;
1886
+ }
1887
+ } else if (event.contentBlockStop) {
1888
+ if (currentToolUse && currentToolUse.id && currentToolUse.name) {
1889
+ let parsed = {};
1890
+ try {
1891
+ parsed = currentToolUse.inputText ? JSON.parse(currentToolUse.inputText) : {};
1892
+ } catch {
1893
+ parsed = {};
1894
+ }
1895
+ completedToolCalls.push({
1896
+ id: currentToolUse.id,
1897
+ name: currentToolUse.name,
1898
+ arguments: parsed
1899
+ });
1900
+ }
1901
+ currentToolUse = null;
1902
+ } else if (event.messageStop) {
1903
+ stopReason = event.messageStop.stopReason;
1904
+ } else if (event.metadata) {
1905
+ if (event.metadata.usage) {
1906
+ inputTokens = event.metadata.usage.inputTokens;
1907
+ outputTokens = event.metadata.usage.outputTokens;
1908
+ totalTokens = event.metadata.usage.totalTokens;
1909
+ }
1910
+ }
1911
+ }
1912
+ } catch (err) {
1913
+ if (isAbortError4(err)) {
1914
+ yield { type: "end", finishReason: "aborted" };
1915
+ return;
1916
+ }
1917
+ throw err;
1918
+ }
1919
+ if (req.signal?.aborted) {
1920
+ yield { type: "end", finishReason: "aborted" };
1921
+ return;
1922
+ }
1923
+ for (const tc of completedToolCalls) {
1924
+ yield {
1925
+ type: "toolCall",
1926
+ id: tc.id,
1927
+ name: tc.name,
1928
+ arguments: tc.arguments
1929
+ };
1930
+ }
1931
+ const finishReason = mapStopReason2(stopReason, completedToolCalls.length > 0);
1932
+ const usage = inputTokens !== void 0 || outputTokens !== void 0 || totalTokens !== void 0 ? {
1933
+ ...inputTokens !== void 0 ? { inputTokens } : {},
1934
+ ...outputTokens !== void 0 ? { outputTokens } : {},
1935
+ ...totalTokens !== void 0 ? { totalTokens } : {}
1936
+ } : void 0;
1937
+ const endEvent = {
1938
+ type: "end",
1939
+ finishReason,
1940
+ ...usage ? { usage } : {},
1941
+ ...stopReason ? { rawReason: stopReason } : {}
1942
+ };
1943
+ yield endEvent;
1944
+ }
1945
+ appendToolResult(history, toolCallId, result) {
1946
+ const text = typeof result === "string" ? result : JSON.stringify(result);
1947
+ const wireMessage = {
1948
+ role: "user",
1949
+ content: [
1950
+ {
1951
+ toolResult: {
1952
+ toolUseId: toolCallId,
1953
+ content: [{ text }]
1954
+ }
1955
+ }
1956
+ ]
1957
+ };
1958
+ return [
1959
+ ...history,
1960
+ {
1961
+ role: "tool",
1962
+ content: text,
1963
+ vendorRaw: wireMessage
1964
+ }
1965
+ ];
1966
+ }
1967
+ async listAvailableModels() {
1968
+ return [...bedrockManifest.knownModels];
1969
+ }
1970
+ async warmup() {
1971
+ }
1972
+ ensureClient() {
1973
+ if (!this.client) {
1974
+ throw new Error(
1975
+ "BedrockAdapter: init() must be called before stream()/listAvailableModels()"
1976
+ );
1977
+ }
1978
+ return this.client;
1979
+ }
1980
+ };
1981
+ function buildWireMessages3(req) {
1982
+ const out = [];
1983
+ for (const msg of req.messages) {
1984
+ if (msg.vendorRaw && typeof msg.vendorRaw === "object") {
1985
+ out.push(msg.vendorRaw);
1986
+ continue;
1987
+ }
1988
+ const text = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1989
+ const role = msg.role === "tool" ? "user" : msg.role;
1990
+ out.push({
1991
+ role,
1992
+ content: [{ text }]
1993
+ });
1994
+ }
1995
+ return out;
1996
+ }
1997
+ function formatTools4(tools) {
1998
+ return tools.map((t) => ({
1999
+ toolSpec: {
2000
+ name: t.name,
2001
+ // Bedrock rejects empty-string descriptions; fall back to a single space.
2002
+ description: t.description && t.description.length > 0 ? t.description : " ",
2003
+ inputSchema: {
2004
+ json: t.parameters ?? { type: "object", properties: {} }
2005
+ }
2006
+ }
2007
+ }));
2008
+ }
2009
+ function mapStopReason2(r, hadToolCalls) {
2010
+ if (hadToolCalls) return "tool";
2011
+ switch (r) {
2012
+ case "end_turn":
2013
+ case "stop_sequence":
2014
+ return "stop";
2015
+ case "tool_use":
2016
+ return "tool";
2017
+ case "max_tokens":
2018
+ return "length";
2019
+ case "content_filtered":
2020
+ case "guardrail_intervened":
2021
+ return "filtered";
2022
+ default:
2023
+ return "stop";
2024
+ }
2025
+ }
2026
+ function isAbortError4(err) {
2027
+ if (!err || typeof err !== "object") return false;
2028
+ const e = err;
2029
+ return e.name === "AbortError" || e.name === "APIUserAbortError" || e.code === "ABORT_ERR" || typeof e.message === "string" && /aborted/i.test(e.message);
2030
+ }
2031
+
2032
+ // src/adapters/bedrock/factory.ts
2033
+ var bedrockFactory = {
2034
+ vendor: bedrockManifest.vendor,
2035
+ manifest: bedrockManifest,
2036
+ create: () => new BedrockAdapter()
2037
+ };
2038
+
2039
+ // src/adapters/index.ts
2040
+ registerAdapter(openAIFactory);
2041
+ registerAdapter(deepseekFactory);
2042
+ registerAdapter(anthropicFactory);
2043
+ registerAdapter(googleFactory);
2044
+ registerAdapter(vertexGeminiFactory);
2045
+ registerAdapter(vertexOpenAIFactory);
2046
+ registerAdapter(bedrockFactory);
2047
+
2048
+ // src/index.ts
2049
+ async function createLlm(args) {
2050
+ const factory = getAdapterFactory(args.vendor);
2051
+ if (!factory.manifest.authKinds.some((k) => k.kind === args.auth.kind)) {
2052
+ const accepted = factory.manifest.authKinds.map((k) => k.kind).join(", ");
2053
+ throw new Error(
2054
+ `Vendor '${args.vendor}' does not accept auth kind '${args.auth.kind}'. Accepted kinds: ${accepted}`
2055
+ );
2056
+ }
2057
+ const instance = factory.create();
2058
+ await Promise.resolve(instance.init(args.auth, args.client));
2059
+ return instance;
2060
+ }
2061
+
2062
+ // src/test-kit/runner.ts
2063
+ var VALID_FINISH_REASONS = [
2064
+ "stop",
2065
+ "tool",
2066
+ "length",
2067
+ "filtered",
2068
+ "error",
2069
+ "aborted"
2070
+ ];
2071
+ var VALID_FORM_FIELD_TYPES = ["text", "password", "url", "json-file", "select"];
2072
+ function runContractTests(harness) {
2073
+ (0, import_vitest.describe)(`contract: ${harness.vendor}`, () => {
2074
+ (0, import_vitest.beforeEach)(() => {
2075
+ _resetRegistryForTests();
2076
+ registerAdapter(harness.factory);
2077
+ });
2078
+ (0, import_vitest.afterEach)(async () => {
2079
+ await harness.cleanup();
2080
+ _resetRegistryForTests();
2081
+ });
2082
+ (0, import_vitest.it)("[1] manifest is well-formed", () => {
2083
+ const m = harness.factory.manifest;
2084
+ (0, import_vitest.expect)(m.vendor).toMatch(/^[a-z][a-z0-9-]*$/);
2085
+ (0, import_vitest.expect)(m.displayName.length).toBeGreaterThan(0);
2086
+ (0, import_vitest.expect)(m.authKinds.length).toBeGreaterThan(0);
2087
+ for (const ak of m.authKinds) {
2088
+ (0, import_vitest.expect)(ak.displayName.length).toBeGreaterThan(0);
2089
+ for (const field of ak.fields) {
2090
+ (0, import_vitest.expect)(field.name.length).toBeGreaterThan(0);
2091
+ (0, import_vitest.expect)(field.label.length).toBeGreaterThan(0);
2092
+ (0, import_vitest.expect)(VALID_FORM_FIELD_TYPES).toContain(field.type);
2093
+ if (field.type === "select") {
2094
+ (0, import_vitest.expect)(field.options?.length ?? 0).toBeGreaterThan(0);
2095
+ }
2096
+ }
2097
+ }
2098
+ (0, import_vitest.expect)(m.knownModels.length).toBeGreaterThan(0);
2099
+ for (const model of m.knownModels) {
2100
+ (0, import_vitest.expect)(model.id.length).toBeGreaterThan(0);
2101
+ (0, import_vitest.expect)(typeof model.capabilities.streaming).toBe("boolean");
2102
+ (0, import_vitest.expect)(typeof model.capabilities.tools).toBe("boolean");
2103
+ (0, import_vitest.expect)(typeof model.capabilities.vision).toBe("boolean");
2104
+ (0, import_vitest.expect)(typeof model.capabilities.systemPrompt).toBe("boolean");
2105
+ }
2106
+ (0, import_vitest.expect)(typeof m.supportsModelListing).toBe("boolean");
2107
+ });
2108
+ (0, import_vitest.it)("[2] createLlm returns an adapter with matching vendor id", async () => {
2109
+ const firstKind = harness.factory.manifest.authKinds[0].kind;
2110
+ const adapter = await createLlm({
2111
+ vendor: harness.vendor,
2112
+ auth: harness.authFor(firstKind)
2113
+ });
2114
+ (0, import_vitest.expect)(adapter.vendor).toBe(harness.vendor);
2115
+ });
2116
+ (0, import_vitest.it)("[3] init() accepts each declared auth kind", async () => {
2117
+ for (const ak of harness.factory.manifest.authKinds) {
2118
+ await (0, import_vitest.expect)(
2119
+ createLlm({ vendor: harness.vendor, auth: harness.authFor(ak.kind) })
2120
+ ).resolves.toBeDefined();
2121
+ }
2122
+ });
2123
+ if (harness.unsupportedAuth) {
2124
+ (0, import_vitest.it)("[4] init() rejects an unsupported auth kind", async () => {
2125
+ await (0, import_vitest.expect)(
2126
+ createLlm({
2127
+ vendor: harness.vendor,
2128
+ auth: harness.unsupportedAuth
2129
+ })
2130
+ ).rejects.toThrow();
2131
+ });
2132
+ }
2133
+ (0, import_vitest.it)("[18] empty messages array is rejected with a clear error", async () => {
2134
+ const adapter = await init(harness);
2135
+ await (0, import_vitest.expect)(
2136
+ drainStream(adapter, {
2137
+ model: harness.toolCapableModel,
2138
+ messages: []
2139
+ })
2140
+ ).rejects.toThrowError(/messages/i);
2141
+ });
2142
+ (0, import_vitest.it)("[5,6,7] stream emits exactly one end event, as the last event, with a valid finishReason", async () => {
2143
+ await harness.mockScenario("simple-stream");
2144
+ const adapter = await init(harness);
2145
+ const events = await drainStream(adapter, {
2146
+ model: harness.toolCapableModel,
2147
+ messages: [{ role: "user", content: "hello" }]
2148
+ });
2149
+ const endIndexes = events.map((e, i) => e.type === "end" ? i : -1).filter((i) => i >= 0);
2150
+ (0, import_vitest.expect)(endIndexes).toHaveLength(1);
2151
+ (0, import_vitest.expect)(endIndexes[0]).toBe(events.length - 1);
2152
+ const end = events[events.length - 1];
2153
+ (0, import_vitest.expect)(VALID_FINISH_REASONS).toContain(end.finishReason);
2154
+ });
2155
+ (0, import_vitest.it)("[8] tokens stream incrementally (at least two chunks)", async () => {
2156
+ await harness.mockScenario("simple-stream");
2157
+ const adapter = await init(harness);
2158
+ const events = await drainStream(adapter, {
2159
+ model: harness.toolCapableModel,
2160
+ messages: [{ role: "user", content: "hello" }]
2161
+ });
2162
+ const tokens = events.filter((e) => e.type === "token");
2163
+ (0, import_vitest.expect)(tokens.length).toBeGreaterThanOrEqual(2);
2164
+ });
2165
+ (0, import_vitest.it)("[9] pre-fired AbortSignal yields end(aborted) within 500ms", async () => {
2166
+ await harness.mockScenario("simple-stream");
2167
+ const adapter = await init(harness);
2168
+ const controller = new AbortController();
2169
+ controller.abort();
2170
+ const start = Date.now();
2171
+ const events = await drainStream(adapter, {
2172
+ model: harness.toolCapableModel,
2173
+ messages: [{ role: "user", content: "hello" }],
2174
+ signal: controller.signal
2175
+ });
2176
+ const elapsed = Date.now() - start;
2177
+ (0, import_vitest.expect)(elapsed).toBeLessThan(500);
2178
+ const end = events[events.length - 1];
2179
+ (0, import_vitest.expect)(end.type).toBe("end");
2180
+ (0, import_vitest.expect)(end.finishReason).toBe("aborted");
2181
+ (0, import_vitest.expect)(events.filter((e) => e.type === "token").length).toBe(0);
2182
+ });
2183
+ (0, import_vitest.it)("[10] mid-stream abort prevents any pending toolCall from firing", async () => {
2184
+ await harness.mockScenario("long-stream-with-pending-tool");
2185
+ const adapter = await init(harness);
2186
+ const controller = new AbortController();
2187
+ const events = [];
2188
+ let aborted = false;
2189
+ for await (const evt of adapter.stream({
2190
+ model: harness.toolCapableModel,
2191
+ messages: [{ role: "user", content: "go" }],
2192
+ signal: controller.signal
2193
+ })) {
2194
+ events.push(evt);
2195
+ if (!aborted && evt.type === "token") {
2196
+ controller.abort();
2197
+ aborted = true;
2198
+ }
2199
+ }
2200
+ const end = events[events.length - 1];
2201
+ (0, import_vitest.expect)(end.type).toBe("end");
2202
+ (0, import_vitest.expect)(end.finishReason).toBe("aborted");
2203
+ (0, import_vitest.expect)(events.filter((e) => e.type === "toolCall")).toHaveLength(0);
2204
+ });
2205
+ (0, import_vitest.it)("[11] tool-capable request yields a well-formed toolCall event", async () => {
2206
+ await harness.mockScenario("tool-call");
2207
+ const adapter = await init(harness);
2208
+ const events = await drainStream(adapter, {
2209
+ model: harness.toolCapableModel,
2210
+ messages: [{ role: "user", content: "call the tool" }],
2211
+ tools: [
2212
+ {
2213
+ name: "test_tool",
2214
+ description: "A test tool",
2215
+ parameters: { type: "object", properties: {} }
2216
+ }
2217
+ ]
2218
+ });
2219
+ const toolCalls = events.filter(
2220
+ (e) => e.type === "toolCall"
2221
+ );
2222
+ (0, import_vitest.expect)(toolCalls.length).toBeGreaterThanOrEqual(1);
2223
+ const tc = toolCalls[0];
2224
+ (0, import_vitest.expect)(typeof tc.id).toBe("string");
2225
+ (0, import_vitest.expect)(tc.id.length).toBeGreaterThan(0);
2226
+ (0, import_vitest.expect)(typeof tc.name).toBe("string");
2227
+ (0, import_vitest.expect)(tc.name.length).toBeGreaterThan(0);
2228
+ (0, import_vitest.expect)(tc.arguments).toBeDefined();
2229
+ });
2230
+ if (harness.emitsToolCallStart) {
2231
+ (0, import_vitest.it)("[12] every toolCallStart precedes its matching toolCall with the same id", async () => {
2232
+ await harness.mockScenario("tool-call-after-tokens");
2233
+ const adapter = await init(harness);
2234
+ const events = await drainStream(adapter, {
2235
+ model: harness.toolCapableModel,
2236
+ messages: [{ role: "user", content: "hi" }],
2237
+ tools: [
2238
+ {
2239
+ name: "test_tool",
2240
+ description: "A test tool",
2241
+ parameters: { type: "object", properties: {} }
2242
+ }
2243
+ ]
2244
+ });
2245
+ const startIndexById = /* @__PURE__ */ new Map();
2246
+ for (let i = 0; i < events.length; i++) {
2247
+ const evt = events[i];
2248
+ if (evt.type === "toolCallStart") {
2249
+ startIndexById.set(evt.id, i);
2250
+ } else if (evt.type === "toolCall") {
2251
+ const startIndex = startIndexById.get(evt.id);
2252
+ (0, import_vitest.expect)(startIndex, `missing toolCallStart for id ${evt.id}`).toBeDefined();
2253
+ (0, import_vitest.expect)(startIndex).toBeLessThan(i);
2254
+ }
2255
+ }
2256
+ });
2257
+ }
2258
+ (0, import_vitest.it)("[13] appendToolResult produces a history that re-streams without throwing", async () => {
2259
+ await harness.mockScenario("tool-call");
2260
+ const adapter = await init(harness);
2261
+ const events = await drainStream(adapter, {
2262
+ model: harness.toolCapableModel,
2263
+ messages: [{ role: "user", content: "call it" }],
2264
+ tools: [
2265
+ { name: "test_tool", description: "x", parameters: { type: "object" } }
2266
+ ]
2267
+ });
2268
+ const tc = events.find(
2269
+ (e) => e.type === "toolCall"
2270
+ );
2271
+ (0, import_vitest.expect)(tc).toBeDefined();
2272
+ const history = [
2273
+ { role: "user", content: "call it" },
2274
+ harness.buildAssistantWithToolCall(tc)
2275
+ ];
2276
+ const withResult = adapter.appendToolResult(history, tc.id, { ok: true });
2277
+ (0, import_vitest.expect)(withResult.length).toBe(history.length + 1);
2278
+ await harness.mockScenario("simple-stream");
2279
+ await (0, import_vitest.expect)(
2280
+ drainStream(adapter, {
2281
+ model: harness.toolCapableModel,
2282
+ messages: withResult
2283
+ })
2284
+ ).resolves.toBeDefined();
2285
+ });
2286
+ (0, import_vitest.it)("[14] appendToolResult is deterministic for the same inputs", async () => {
2287
+ const adapter = await init(harness);
2288
+ const history = [{ role: "user", content: "hi" }];
2289
+ const a = adapter.appendToolResult(history, "tc_1", { a: 1 });
2290
+ const b = adapter.appendToolResult(history, "tc_1", { a: 1 });
2291
+ (0, import_vitest.expect)(JSON.stringify(a)).toBe(JSON.stringify(b));
2292
+ });
2293
+ (0, import_vitest.it)("[15] listAvailableModels returns a non-empty list", async () => {
2294
+ await harness.mockScenario("list-models");
2295
+ const adapter = await init(harness);
2296
+ const models = await adapter.listAvailableModels();
2297
+ (0, import_vitest.expect)(models.length).toBeGreaterThan(0);
2298
+ for (const m of models) {
2299
+ (0, import_vitest.expect)(m.id.length).toBeGreaterThan(0);
2300
+ (0, import_vitest.expect)(typeof m.capabilities.tools).toBe("boolean");
2301
+ }
2302
+ });
2303
+ if (harness.nonToolCapableModel) {
2304
+ (0, import_vitest.it)("[16] non-tool-capable model with tools declared either fails fast or runs without tool calls", async () => {
2305
+ await harness.mockScenario("simple-stream");
2306
+ const adapter = await init(harness);
2307
+ const run = async () => drainStream(adapter, {
2308
+ model: harness.nonToolCapableModel,
2309
+ messages: [{ role: "user", content: "hi" }],
2310
+ tools: [
2311
+ { name: "test_tool", description: "x", parameters: { type: "object" } }
2312
+ ]
2313
+ });
2314
+ try {
2315
+ const events = await run();
2316
+ (0, import_vitest.expect)(events.filter((e) => e.type === "toolCall")).toHaveLength(0);
2317
+ const end = events[events.length - 1];
2318
+ (0, import_vitest.expect)(end.finishReason).not.toBe("error");
2319
+ } catch (err) {
2320
+ (0, import_vitest.expect)(err).toBeInstanceOf(Error);
2321
+ }
2322
+ });
2323
+ }
2324
+ (0, import_vitest.it)("[17] system prompt is present in the upstream request", async () => {
2325
+ await harness.mockScenario("simple-stream");
2326
+ const adapter = await init(harness);
2327
+ await drainStream(adapter, {
2328
+ model: harness.toolCapableModel,
2329
+ system: "You are a test agent.",
2330
+ messages: [{ role: "user", content: "hi" }]
2331
+ });
2332
+ const captured = harness.getCapturedRequest();
2333
+ (0, import_vitest.expect)(captured).not.toBeNull();
2334
+ (0, import_vitest.expect)(captured.system).toBe("You are a test agent.");
2335
+ });
2336
+ (0, import_vitest.it)("[19] multi-turn conversation is preserved in the upstream request", async () => {
2337
+ await harness.mockScenario("simple-stream");
2338
+ const adapter = await init(harness);
2339
+ const messages = [
2340
+ { role: "user", content: "first" },
2341
+ { role: "assistant", content: "one" },
2342
+ { role: "user", content: "second" },
2343
+ { role: "assistant", content: "two" },
2344
+ { role: "user", content: "third" }
2345
+ ];
2346
+ await drainStream(adapter, { model: harness.toolCapableModel, messages });
2347
+ const captured = harness.getCapturedRequest();
2348
+ (0, import_vitest.expect)(captured).not.toBeNull();
2349
+ (0, import_vitest.expect)(captured.messageCount).toBe(messages.length);
2350
+ });
2351
+ (0, import_vitest.it)("[20] vendorRaw on an assistant message round-trips through the next request", async () => {
2352
+ await harness.mockScenario("tool-call");
2353
+ const adapter = await init(harness);
2354
+ const first = await drainStream(adapter, {
2355
+ model: harness.toolCapableModel,
2356
+ messages: [{ role: "user", content: "go" }],
2357
+ tools: [
2358
+ { name: "test_tool", description: "x", parameters: { type: "object" } }
2359
+ ]
2360
+ });
2361
+ const tc = first.find(
2362
+ (e) => e.type === "toolCall"
2363
+ );
2364
+ (0, import_vitest.expect)(tc).toBeDefined();
2365
+ const history = [
2366
+ { role: "user", content: "go" },
2367
+ harness.buildAssistantWithToolCall(tc)
2368
+ ];
2369
+ const withResult = adapter.appendToolResult(history, tc.id, { ok: true });
2370
+ await harness.mockScenario("simple-stream");
2371
+ await drainStream(adapter, {
2372
+ model: harness.toolCapableModel,
2373
+ messages: withResult
2374
+ });
2375
+ const captured = harness.getCapturedRequest();
2376
+ (0, import_vitest.expect)(captured).not.toBeNull();
2377
+ (0, import_vitest.expect)(captured.vendorRawHonored).toBe(true);
2378
+ });
2379
+ });
2380
+ }
2381
+ async function init(harness) {
2382
+ const kind = harness.factory.manifest.authKinds[0].kind;
2383
+ return createLlm({ vendor: harness.vendor, auth: harness.authFor(kind) });
2384
+ }
2385
+ async function drainStream(adapter, req) {
2386
+ const events = [];
2387
+ for await (const evt of adapter.stream(req)) {
2388
+ events.push(evt);
2389
+ }
2390
+ return events;
2391
+ }
2392
+
2393
+ // src/test-kit/fake-adapter.ts
2394
+ var FakeAdapter = class {
2395
+ constructor(state) {
2396
+ this.state = state;
2397
+ }
2398
+ state;
2399
+ vendor = fakeManifest.vendor;
2400
+ acceptedAuth = ["apiKey"];
2401
+ initialized = false;
2402
+ init(auth, _client) {
2403
+ if (auth.kind !== "apiKey") {
2404
+ throw new Error(`FakeAdapter: unsupported auth kind '${auth.kind}'`);
2405
+ }
2406
+ if (!auth.apiKey) {
2407
+ throw new Error("FakeAdapter: apiKey is required");
2408
+ }
2409
+ this.initialized = true;
2410
+ }
2411
+ async *stream(req) {
2412
+ this.ensureInitialized();
2413
+ assertValidRequest(req);
2414
+ this.capture(req);
2415
+ const scenario = this.state.scenario ?? "simple-stream";
2416
+ if (req.signal?.aborted) {
2417
+ yield { type: "end", finishReason: "aborted" };
2418
+ return;
2419
+ }
2420
+ switch (scenario) {
2421
+ case "simple-stream":
2422
+ yield* simpleStream(req.signal);
2423
+ return;
2424
+ case "tool-call":
2425
+ yield* toolCallOnly(req.signal);
2426
+ return;
2427
+ case "tool-call-after-tokens":
2428
+ yield* toolCallAfterTokens(req.signal);
2429
+ return;
2430
+ case "long-stream":
2431
+ yield* longStream(req.signal);
2432
+ return;
2433
+ case "long-stream-with-pending-tool":
2434
+ yield* longStreamWithPendingTool(req.signal);
2435
+ return;
2436
+ case "list-models":
2437
+ yield* simpleStream(req.signal);
2438
+ return;
2439
+ default:
2440
+ throw new Error(`FakeAdapter: unknown scenario '${scenario}'`);
2441
+ }
2442
+ }
2443
+ appendToolResult(history, toolCallId, result) {
2444
+ const content = typeof result === "string" ? result : JSON.stringify(result);
2445
+ return [
2446
+ ...history,
2447
+ {
2448
+ role: "tool",
2449
+ content,
2450
+ vendorRaw: { tool_call_id: toolCallId }
2451
+ }
2452
+ ];
2453
+ }
2454
+ async listAvailableModels() {
2455
+ this.ensureInitialized();
2456
+ return fakeManifest.knownModels;
2457
+ }
2458
+ ensureInitialized() {
2459
+ if (!this.initialized) {
2460
+ throw new Error("FakeAdapter: init() must be called before stream()/listAvailableModels()");
2461
+ }
2462
+ }
2463
+ capture(req) {
2464
+ this.state.captured = {
2465
+ messageCount: req.messages.length,
2466
+ vendorRawHonored: req.messages.some((m) => m.vendorRaw !== void 0),
2467
+ ...req.system !== void 0 ? { system: req.system } : {}
2468
+ };
2469
+ }
2470
+ };
2471
+ async function* simpleStream(signal) {
2472
+ const chunks = ["Hello", ", ", "world", "!"];
2473
+ for (const text of chunks) {
2474
+ if (signal?.aborted) {
2475
+ yield { type: "end", finishReason: "aborted" };
2476
+ return;
2477
+ }
2478
+ yield { type: "token", text };
2479
+ }
2480
+ yield { type: "end", finishReason: "stop", usage: { inputTokens: 5, outputTokens: 4 } };
2481
+ }
2482
+ async function* toolCallOnly(signal) {
2483
+ if (signal?.aborted) {
2484
+ yield { type: "end", finishReason: "aborted" };
2485
+ return;
2486
+ }
2487
+ yield { type: "toolCallStart", id: "call_fake_1", name: "test_tool" };
2488
+ yield {
2489
+ type: "toolCall",
2490
+ id: "call_fake_1",
2491
+ name: "test_tool",
2492
+ arguments: { foo: "bar" }
2493
+ };
2494
+ yield { type: "end", finishReason: "tool" };
2495
+ }
2496
+ async function* toolCallAfterTokens(signal) {
2497
+ const tokens = ["Let ", "me ", "check"];
2498
+ for (const text of tokens) {
2499
+ if (signal?.aborted) {
2500
+ yield { type: "end", finishReason: "aborted" };
2501
+ return;
2502
+ }
2503
+ yield { type: "token", text };
2504
+ }
2505
+ if (signal?.aborted) {
2506
+ yield { type: "end", finishReason: "aborted" };
2507
+ return;
2508
+ }
2509
+ yield { type: "toolCallStart", id: "call_fake_2", name: "test_tool" };
2510
+ yield {
2511
+ type: "toolCall",
2512
+ id: "call_fake_2",
2513
+ name: "test_tool",
2514
+ arguments: { q: "hello" }
2515
+ };
2516
+ yield { type: "end", finishReason: "tool" };
2517
+ }
2518
+ async function* longStream(signal) {
2519
+ for (let i = 0; i < 12; i++) {
2520
+ if (signal?.aborted) {
2521
+ yield { type: "end", finishReason: "aborted" };
2522
+ return;
2523
+ }
2524
+ yield { type: "token", text: `chunk-${i} ` };
2525
+ await sleep(20);
2526
+ }
2527
+ yield { type: "end", finishReason: "stop" };
2528
+ }
2529
+ async function* longStreamWithPendingTool(signal) {
2530
+ for (let i = 0; i < 5; i++) {
2531
+ if (signal?.aborted) {
2532
+ yield { type: "end", finishReason: "aborted" };
2533
+ return;
2534
+ }
2535
+ yield { type: "token", text: `chunk-${i} ` };
2536
+ await sleep(25);
2537
+ }
2538
+ if (signal?.aborted) {
2539
+ yield { type: "end", finishReason: "aborted" };
2540
+ return;
2541
+ }
2542
+ yield { type: "toolCallStart", id: "call_fake_3", name: "test_tool" };
2543
+ yield {
2544
+ type: "toolCall",
2545
+ id: "call_fake_3",
2546
+ name: "test_tool",
2547
+ arguments: { q: "never-reached" }
2548
+ };
2549
+ yield { type: "end", finishReason: "tool" };
2550
+ }
2551
+ function sleep(ms) {
2552
+ return new Promise((resolve) => setTimeout(resolve, ms));
2553
+ }
2554
+ var fakeManifest = {
2555
+ vendor: "fake",
2556
+ displayName: "Fake (test-kit reference)",
2557
+ authKinds: [
2558
+ {
2559
+ kind: "apiKey",
2560
+ displayName: "API Key",
2561
+ fields: [
2562
+ { name: "apiKey", label: "API Key", type: "password", required: true }
2563
+ ]
2564
+ }
2565
+ ],
2566
+ knownModels: [
2567
+ {
2568
+ id: "fake-tool-model",
2569
+ displayName: "Fake Tool-Capable Model",
2570
+ capabilities: {
2571
+ streaming: true,
2572
+ tools: true,
2573
+ vision: false,
2574
+ systemPrompt: true,
2575
+ maxContextTokens: 8e3
2576
+ }
2577
+ },
2578
+ {
2579
+ id: "fake-plain-model",
2580
+ displayName: "Fake Plain Model (no tools)",
2581
+ capabilities: {
2582
+ streaming: true,
2583
+ tools: false,
2584
+ vision: false,
2585
+ systemPrompt: true,
2586
+ maxContextTokens: 4e3
2587
+ }
2588
+ }
2589
+ ],
2590
+ supportsModelListing: true
2591
+ };
2592
+ function createFakeHarness() {
2593
+ const state = { scenario: null, captured: null };
2594
+ const factory = {
2595
+ vendor: fakeManifest.vendor,
2596
+ manifest: fakeManifest,
2597
+ create: () => new FakeAdapter(state)
2598
+ };
2599
+ return {
2600
+ vendor: fakeManifest.vendor,
2601
+ factory,
2602
+ authFor: (kind) => {
2603
+ if (kind === "apiKey") return { kind: "apiKey", apiKey: "sk-fake" };
2604
+ throw new Error(`FakeHarness: asked for unsupported authFor kind '${kind}'`);
2605
+ },
2606
+ unsupportedAuth: {
2607
+ kind: "bedrockIam",
2608
+ accessKeyId: "x",
2609
+ secretAccessKey: "y",
2610
+ region: "us-east-1"
2611
+ },
2612
+ mockScenario(scenario) {
2613
+ state.scenario = scenario;
2614
+ state.captured = null;
2615
+ },
2616
+ cleanup() {
2617
+ state.scenario = null;
2618
+ state.captured = null;
2619
+ },
2620
+ getCapturedRequest() {
2621
+ return state.captured;
2622
+ },
2623
+ toolCapableModel: "fake-tool-model",
2624
+ nonToolCapableModel: "fake-plain-model",
2625
+ emitsToolCallStart: true,
2626
+ buildAssistantWithToolCall(tc) {
2627
+ return {
2628
+ role: "assistant",
2629
+ content: "",
2630
+ vendorRaw: {
2631
+ role: "assistant",
2632
+ toolCall: { id: tc.id, name: tc.name, arguments: tc.arguments }
2633
+ }
2634
+ };
2635
+ }
2636
+ };
2637
+ }
2638
+ // Annotate the CommonJS export names for ESM import in node:
2639
+ 0 && (module.exports = {
2640
+ FakeAdapter,
2641
+ createFakeHarness,
2642
+ fakeManifest,
2643
+ runContractTests
2644
+ });
2645
+ //# sourceMappingURL=index.cjs.map