opencode-crs-bedrock 1.0.4 → 1.0.5

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 (3) hide show
  1. package/dist/index.js +555 -0
  2. package/index.ts +31 -2
  3. package/package.json +4 -2
package/dist/index.js ADDED
@@ -0,0 +1,555 @@
1
+ // index.ts
2
+ var PROVIDER_ID = "crs";
3
+ var VALID_SSE_EVENT_TYPES = new Set([
4
+ "message_start",
5
+ "content_block_start",
6
+ "content_block_delta",
7
+ "content_block_stop",
8
+ "message_delta",
9
+ "message_stop",
10
+ "ping",
11
+ "error"
12
+ ]);
13
+ var DEBUG_SSE = process.env.CRS_DEBUG_SSE === "true";
14
+ function debugLog(...args) {
15
+ if (DEBUG_SSE) {
16
+ console.error("[CRS-SSE]", ...args);
17
+ }
18
+ }
19
+ function generateToolUseId() {
20
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
21
+ let id = "toolu_01";
22
+ for (let i = 0;i < 22; i++) {
23
+ id += chars.charAt(Math.floor(Math.random() * chars.length));
24
+ }
25
+ return id;
26
+ }
27
+ function emitSSEEvent(controller, eventType, data) {
28
+ controller.enqueue(`event: ${eventType}
29
+ `);
30
+ controller.enqueue(`data: ${JSON.stringify(data)}
31
+ `);
32
+ controller.enqueue(`
33
+ `);
34
+ }
35
+ function emitEventHeader(controller, eventType) {
36
+ controller.enqueue(`event: ${eventType}
37
+ `);
38
+ }
39
+ function buildToolSchemas(tools) {
40
+ const schemas = new Map;
41
+ for (const tool of tools) {
42
+ const params = tool.input_schema?.properties || {};
43
+ const required = new Set(tool.input_schema?.required || []);
44
+ schemas.set(tool.name, { params, required });
45
+ }
46
+ return schemas;
47
+ }
48
+ function inferToolName(jsonStr, toolSchemas) {
49
+ try {
50
+ const input = JSON.parse(jsonStr);
51
+ const inputKeys = new Set(Object.keys(input));
52
+ let bestMatch = null;
53
+ let bestScore = -1;
54
+ for (const [toolName, schema] of toolSchemas) {
55
+ const schemaKeys = new Set(Object.keys(schema.params));
56
+ let matchCount = 0;
57
+ let mismatchCount = 0;
58
+ for (const key of inputKeys) {
59
+ if (schemaKeys.has(key)) {
60
+ matchCount++;
61
+ } else {
62
+ mismatchCount++;
63
+ }
64
+ }
65
+ let hasAllRequired = true;
66
+ for (const req of schema.required) {
67
+ if (!inputKeys.has(req)) {
68
+ hasAllRequired = false;
69
+ break;
70
+ }
71
+ }
72
+ const score = matchCount - mismatchCount + (hasAllRequired ? 10 : 0);
73
+ if (score > bestScore) {
74
+ bestScore = score;
75
+ bestMatch = toolName;
76
+ }
77
+ }
78
+ return bestMatch;
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ var BEDROCK_MODEL_MAPPINGS = {
84
+ "us.anthropic.claude-sonnet-4-20250514-v1:0": "claude-sonnet-4-20250514",
85
+ "us.anthropic.claude-opus-4-20250514-v1:0": "claude-opus-4-20250514",
86
+ "us.anthropic.claude-3-5-sonnet-20241022-v2:0": "claude-3-5-sonnet-20241022",
87
+ "us.anthropic.claude-3-5-haiku-20241022-v1:0": "claude-3-5-haiku-20241022",
88
+ "us.anthropic.claude-3-opus-20240229-v1:0": "claude-3-opus-20240229"
89
+ };
90
+ function mapBedrockModelId(bedrockModelId) {
91
+ if (BEDROCK_MODEL_MAPPINGS[bedrockModelId]) {
92
+ return BEDROCK_MODEL_MAPPINGS[bedrockModelId];
93
+ }
94
+ const match = bedrockModelId.match(/us\.anthropic\.(.+?)-v\d+:\d+$/);
95
+ if (match) {
96
+ return match[1];
97
+ }
98
+ return bedrockModelId;
99
+ }
100
+
101
+ class SSETransformState {
102
+ toolSchemas;
103
+ buffer;
104
+ currentEventType;
105
+ startedBlocks;
106
+ pendingToolBlocks;
107
+ constructor(toolSchemas) {
108
+ this.toolSchemas = toolSchemas;
109
+ this.buffer = "";
110
+ this.currentEventType = null;
111
+ this.startedBlocks = new Map;
112
+ this.pendingToolBlocks = new Map;
113
+ }
114
+ trackBlockStart(index, contentBlock) {
115
+ const blockType = contentBlock?.type || "text";
116
+ if (blockType === "tool_use") {
117
+ const toolBlock = contentBlock;
118
+ this.startedBlocks.set(index, {
119
+ type: "tool_use",
120
+ id: toolBlock.id || generateToolUseId(),
121
+ name: toolBlock.name || "unknown",
122
+ inputBuffer: "",
123
+ emitted: true
124
+ });
125
+ } else {
126
+ this.startedBlocks.set(index, { type: "text", emitted: true });
127
+ }
128
+ }
129
+ bufferToolDelta(index, eventType, data, partialJson) {
130
+ if (!this.pendingToolBlocks.has(index)) {
131
+ this.pendingToolBlocks.set(index, {
132
+ toolId: generateToolUseId(),
133
+ deltas: [],
134
+ inputBuffer: ""
135
+ });
136
+ }
137
+ const pending = this.pendingToolBlocks.get(index);
138
+ pending.inputBuffer += partialJson;
139
+ pending.deltas.push({ event: eventType, data: { ...data } });
140
+ debugLog("Buffering tool delta, accumulated:", pending.inputBuffer);
141
+ }
142
+ hasPendingToolBlock(index) {
143
+ return this.pendingToolBlocks.has(index);
144
+ }
145
+ flushPendingToolBlocks(controller) {
146
+ for (const [blockIndex, pending] of this.pendingToolBlocks) {
147
+ const inferredName = inferToolName(pending.inputBuffer, this.toolSchemas);
148
+ if (!inferredName) {
149
+ debugLog("Could not infer tool name for block", blockIndex, "- converting to text with available tools list");
150
+ const availableTools = Array.from(this.toolSchemas.keys()).join(", ");
151
+ const helpText = `Tool inference failed. The model attempted to call a tool but the tool name could not be determined from the input parameters. Available tools: ${availableTools}. Please specify which tool you want to use.`;
152
+ emitSSEEvent(controller, "content_block_start", {
153
+ type: "content_block_start",
154
+ index: blockIndex,
155
+ content_block: {
156
+ type: "text",
157
+ text: helpText
158
+ }
159
+ });
160
+ emitSSEEvent(controller, "content_block_stop", {
161
+ type: "content_block_stop",
162
+ index: blockIndex
163
+ });
164
+ continue;
165
+ }
166
+ debugLog("Flushing pending tool block", blockIndex, "with inferred name:", inferredName);
167
+ emitSSEEvent(controller, "content_block_start", {
168
+ type: "content_block_start",
169
+ index: blockIndex,
170
+ content_block: {
171
+ type: "tool_use",
172
+ id: pending.toolId,
173
+ name: inferredName,
174
+ input: {}
175
+ }
176
+ });
177
+ for (const buffered of pending.deltas) {
178
+ emitSSEEvent(controller, buffered.event, {
179
+ type: buffered.event,
180
+ ...buffered.data
181
+ });
182
+ }
183
+ this.startedBlocks.set(blockIndex, {
184
+ type: "tool_use",
185
+ id: pending.toolId,
186
+ name: inferredName,
187
+ inputBuffer: pending.inputBuffer,
188
+ emitted: true
189
+ });
190
+ }
191
+ this.pendingToolBlocks.clear();
192
+ }
193
+ closeAllBlocks(controller) {
194
+ for (const [blockIndex] of this.startedBlocks) {
195
+ emitSSEEvent(controller, "content_block_stop", {
196
+ type: "content_block_stop",
197
+ index: blockIndex
198
+ });
199
+ }
200
+ this.startedBlocks.clear();
201
+ }
202
+ }
203
+ function createSSETransformStream(tools = []) {
204
+ const state = new SSETransformState(buildToolSchemas(tools));
205
+ return new TransformStream({
206
+ transform(chunk, controller) {
207
+ state.buffer += chunk;
208
+ const lines = state.buffer.split(`
209
+ `);
210
+ state.buffer = lines.pop() || "";
211
+ for (const line of lines) {
212
+ const result = processSSELine(line, state, controller);
213
+ if (result === "skip")
214
+ continue;
215
+ }
216
+ },
217
+ flush(controller) {
218
+ if (state.buffer.trim()) {
219
+ controller.enqueue(state.buffer);
220
+ }
221
+ }
222
+ });
223
+ }
224
+ function processSSELine(line, state, controller) {
225
+ const trimmedLine = line.trim();
226
+ if (trimmedLine === "") {
227
+ controller.enqueue(`
228
+ `);
229
+ state.currentEventType = null;
230
+ return;
231
+ }
232
+ if (trimmedLine.startsWith(":")) {
233
+ controller.enqueue(line + `
234
+ `);
235
+ return;
236
+ }
237
+ if (trimmedLine.startsWith("event:")) {
238
+ const eventType = trimmedLine.slice(6).trim();
239
+ if (!VALID_SSE_EVENT_TYPES.has(eventType)) {
240
+ state.currentEventType = null;
241
+ return "skip";
242
+ }
243
+ state.currentEventType = eventType;
244
+ controller.enqueue(line + `
245
+ `);
246
+ return;
247
+ }
248
+ if (trimmedLine.startsWith("data:")) {
249
+ return processDataLine(trimmedLine, line, state, controller);
250
+ }
251
+ controller.enqueue(line + `
252
+ `);
253
+ }
254
+ function processDataLine(trimmedLine, originalLine, state, controller) {
255
+ const dataContent = trimmedLine.slice(5).trim();
256
+ if (dataContent === "[DONE]") {
257
+ controller.enqueue(originalLine + `
258
+ `);
259
+ return;
260
+ }
261
+ if (state.currentEventType === null) {
262
+ return "skip";
263
+ }
264
+ try {
265
+ const data = JSON.parse(dataContent);
266
+ debugLog("Event:", state.currentEventType, "Data:", JSON.stringify(data).slice(0, 500));
267
+ const shouldSkip = handleEventData(data, state, controller);
268
+ if (shouldSkip)
269
+ return "skip";
270
+ const normalized = normalizeEventData(data, state.currentEventType);
271
+ controller.enqueue(`data: ${JSON.stringify(normalized)}
272
+ `);
273
+ } catch {
274
+ controller.enqueue(originalLine + `
275
+ `);
276
+ }
277
+ }
278
+ function handleEventData(data, state, controller) {
279
+ const eventType = state.currentEventType;
280
+ if (eventType === "content_block_start" && typeof data.index === "number") {
281
+ const blockData = data;
282
+ state.trackBlockStart(blockData.index, blockData.content_block);
283
+ return false;
284
+ }
285
+ if (eventType === "content_block_delta" && typeof data.index === "number") {
286
+ return handleContentBlockDelta(data, state, controller);
287
+ }
288
+ if (eventType === "content_block_stop" && typeof data.index === "number") {
289
+ state.startedBlocks.delete(data.index);
290
+ return false;
291
+ }
292
+ if (eventType === "message_delta") {
293
+ state.flushPendingToolBlocks(controller);
294
+ if (state.startedBlocks.size > 0) {
295
+ state.closeAllBlocks(controller);
296
+ }
297
+ emitEventHeader(controller, eventType);
298
+ return false;
299
+ }
300
+ return false;
301
+ }
302
+ function handleContentBlockDelta(data, state, controller) {
303
+ const index = data.index;
304
+ const deltaType = data.delta?.type;
305
+ if (!state.startedBlocks.has(index)) {
306
+ if (deltaType === "input_json_delta") {
307
+ const jsonDelta = data.delta;
308
+ state.bufferToolDelta(index, state.currentEventType, data, jsonDelta.partial_json || "");
309
+ return true;
310
+ } else {
311
+ injectTextBlockStart(index, state, controller);
312
+ }
313
+ } else if (deltaType === "input_json_delta" && state.hasPendingToolBlock(index)) {
314
+ const jsonDelta = data.delta;
315
+ state.bufferToolDelta(index, state.currentEventType, data, jsonDelta.partial_json || "");
316
+ return true;
317
+ } else if (deltaType === "input_json_delta") {
318
+ const blockInfo = state.startedBlocks.get(index);
319
+ if (blockInfo?.type === "tool_use") {
320
+ const jsonDelta = data.delta;
321
+ blockInfo.inputBuffer = (blockInfo.inputBuffer || "") + (jsonDelta.partial_json || "");
322
+ }
323
+ }
324
+ fixDeltaTypeMismatch(data, state.startedBlocks.get(index));
325
+ return false;
326
+ }
327
+ function injectTextBlockStart(index, state, controller) {
328
+ state.startedBlocks.set(index, { type: "text", emitted: true });
329
+ emitSSEEvent(controller, "content_block_start", {
330
+ type: "content_block_start",
331
+ index,
332
+ content_block: { type: "text", text: "" }
333
+ });
334
+ emitEventHeader(controller, state.currentEventType);
335
+ }
336
+ function fixDeltaTypeMismatch(data, blockInfo) {
337
+ if (!blockInfo || !data.delta)
338
+ return;
339
+ const blockType = blockInfo.type || "text";
340
+ if (blockType === "tool_use" && data.delta.type === "text_delta") {
341
+ const textDelta = data.delta;
342
+ data.delta = {
343
+ type: "input_json_delta",
344
+ partial_json: textDelta.text || ""
345
+ };
346
+ } else if (blockType === "text" && data.delta.type === "input_json_delta") {
347
+ const jsonDelta = data.delta;
348
+ data.delta = {
349
+ type: "text_delta",
350
+ text: jsonDelta.partial_json || ""
351
+ };
352
+ }
353
+ }
354
+ function normalizeEventData(data, eventType) {
355
+ const normalized = { ...data };
356
+ if (!normalized.type) {
357
+ normalized.type = eventType;
358
+ }
359
+ if (eventType === "message_start") {
360
+ return normalizeMessageStart(data);
361
+ }
362
+ if (eventType === "content_block_start") {
363
+ return normalizeContentBlockStart(normalized);
364
+ }
365
+ return normalized;
366
+ }
367
+ function normalizeMessageStart(data) {
368
+ if (data.type === "message" || !data.message) {
369
+ const messageData = { ...data };
370
+ delete messageData.type;
371
+ if (typeof messageData.model === "string" && messageData.model.includes("us.anthropic.")) {
372
+ messageData.model = mapBedrockModelId(messageData.model);
373
+ }
374
+ return { type: "message_start", message: messageData };
375
+ }
376
+ if (data.message?.model?.includes("us.anthropic.")) {
377
+ const normalized = {
378
+ ...data,
379
+ message: {
380
+ ...data.message,
381
+ model: mapBedrockModelId(data.message.model)
382
+ }
383
+ };
384
+ return normalized;
385
+ }
386
+ return data;
387
+ }
388
+ function normalizeContentBlockStart(normalized) {
389
+ if (!normalized.content_block) {
390
+ return {
391
+ ...normalized,
392
+ content_block: { type: "text", text: "" }
393
+ };
394
+ } else if (normalized.content_block.type === "tool_use") {
395
+ const toolBlock = normalized.content_block;
396
+ return {
397
+ ...normalized,
398
+ content_block: {
399
+ ...toolBlock,
400
+ id: toolBlock.id || generateToolUseId(),
401
+ name: toolBlock.name || "unknown"
402
+ }
403
+ };
404
+ }
405
+ return normalized;
406
+ }
407
+ function extractToolsFromBody(body) {
408
+ if (!body)
409
+ return [];
410
+ try {
411
+ const bodyStr = typeof body === "string" ? body : new TextDecoder().decode(body);
412
+ const bodyJson = JSON.parse(bodyStr);
413
+ return Array.isArray(bodyJson.tools) ? bodyJson.tools : [];
414
+ } catch {
415
+ return [];
416
+ }
417
+ }
418
+ function buildRequestHeaders(input, init, apiKey) {
419
+ const headers = new Headers;
420
+ if (input instanceof Request) {
421
+ input.headers.forEach((value, key) => headers.set(key, value));
422
+ }
423
+ if (init?.headers) {
424
+ const initHeaders = init.headers;
425
+ if (initHeaders instanceof Headers) {
426
+ initHeaders.forEach((value, key) => headers.set(key, value));
427
+ } else if (Array.isArray(initHeaders)) {
428
+ for (const [key, value] of initHeaders) {
429
+ if (value !== undefined)
430
+ headers.set(key, String(value));
431
+ }
432
+ } else {
433
+ for (const [key, value] of Object.entries(initHeaders)) {
434
+ if (value !== undefined)
435
+ headers.set(key, String(value));
436
+ }
437
+ }
438
+ }
439
+ headers.set("x-api-key", apiKey);
440
+ if (!headers.has("anthropic-version")) {
441
+ headers.set("anthropic-version", "2023-06-01");
442
+ }
443
+ return headers;
444
+ }
445
+ function normalizeApiUrl(input) {
446
+ const url = input instanceof Request ? input.url : String(input);
447
+ const urlObj = new URL(url);
448
+ if (!urlObj.pathname.includes("/v1/")) {
449
+ if (urlObj.pathname.includes("/api/")) {
450
+ urlObj.pathname = urlObj.pathname.replace("/api/", "/api/v1/");
451
+ } else {
452
+ urlObj.pathname = urlObj.pathname.replace(/^\/?/, "/v1/");
453
+ }
454
+ }
455
+ return urlObj.toString();
456
+ }
457
+ function transformStreamingResponse(response, tools) {
458
+ const reader = response.body.getReader();
459
+ const decoder = new TextDecoder;
460
+ const encoder = new TextEncoder;
461
+ const transformStream = createSSETransformStream(tools);
462
+ const writer = transformStream.writable.getWriter();
463
+ (async () => {
464
+ try {
465
+ while (true) {
466
+ const { done, value } = await reader.read();
467
+ if (done) {
468
+ await writer.close();
469
+ break;
470
+ }
471
+ await writer.write(decoder.decode(value, { stream: true }));
472
+ }
473
+ } catch (error) {
474
+ await writer.abort(error);
475
+ }
476
+ })();
477
+ const transformedBody = transformStream.readable.pipeThrough(new TransformStream({
478
+ transform(chunk, controller) {
479
+ controller.enqueue(encoder.encode(chunk));
480
+ }
481
+ }));
482
+ return new Response(transformedBody, {
483
+ status: response.status,
484
+ statusText: response.statusText,
485
+ headers: response.headers
486
+ });
487
+ }
488
+ async function transformJsonResponse(response) {
489
+ try {
490
+ const text = await response.text();
491
+ const data = JSON.parse(text);
492
+ if (data.model?.includes("us.anthropic.")) {
493
+ data.model = mapBedrockModelId(data.model);
494
+ }
495
+ return new Response(JSON.stringify(data), {
496
+ status: response.status,
497
+ statusText: response.statusText,
498
+ headers: response.headers
499
+ });
500
+ } catch {
501
+ return response;
502
+ }
503
+ }
504
+ function createCRSFetch(authKey) {
505
+ return async function crsFetch(input, init) {
506
+ const url = normalizeApiUrl(input);
507
+ const headers = buildRequestHeaders(input, init, authKey);
508
+ const tools = extractToolsFromBody(init?.body);
509
+ const response = await fetch(url, { ...init, headers });
510
+ const contentType = response.headers.get("content-type") || "";
511
+ if (contentType.includes("text/event-stream") && response.body) {
512
+ return transformStreamingResponse(response, tools);
513
+ }
514
+ if (contentType.includes("application/json")) {
515
+ return transformJsonResponse(response);
516
+ }
517
+ return response;
518
+ };
519
+ }
520
+ var CRSAuthPlugin = async ({ client }) => {
521
+ debugLog("CRS Bedrock plugin initializing...");
522
+ return {
523
+ auth: {
524
+ provider: PROVIDER_ID,
525
+ loader: async (getAuth, _provider) => {
526
+ debugLog("CRS auth loader called");
527
+ const auth = await getAuth();
528
+ const apiKey = auth.apiKey;
529
+ const baseURL = auth.baseURL || process.env.ANTHROPIC_BASE_URL || "https://crs.tonob.net/api";
530
+ debugLog("Auth details:", { hasApiKey: !!apiKey, baseURL });
531
+ if (!apiKey) {
532
+ debugLog("No API key found, returning baseURL only");
533
+ return { baseURL };
534
+ }
535
+ debugLog("Returning full config with custom fetch");
536
+ return {
537
+ apiKey,
538
+ baseURL,
539
+ fetch: createCRSFetch(apiKey)
540
+ };
541
+ },
542
+ methods: [
543
+ {
544
+ label: "Enter CRS API Key",
545
+ type: "api"
546
+ }
547
+ ]
548
+ }
549
+ };
550
+ };
551
+ var opencode_crs_bedrock_default = CRSAuthPlugin;
552
+ export {
553
+ opencode_crs_bedrock_default as default,
554
+ CRSAuthPlugin
555
+ };
package/index.ts CHANGED
@@ -434,8 +434,37 @@ class SSETransformState {
434
434
  controller: TransformStreamDefaultController<string>
435
435
  ): void {
436
436
  for (const [blockIndex, pending] of this.pendingToolBlocks) {
437
- const inferredName =
438
- inferToolName(pending.inputBuffer, this.toolSchemas) || "unknown";
437
+ const inferredName = inferToolName(pending.inputBuffer, this.toolSchemas);
438
+
439
+ // If we couldn't infer a tool name, emit a helpful text block instead of a broken tool_use
440
+ if (!inferredName) {
441
+ debugLog(
442
+ "Could not infer tool name for block",
443
+ blockIndex,
444
+ "- converting to text with available tools list"
445
+ );
446
+
447
+ const availableTools = Array.from(this.toolSchemas.keys()).join(", ");
448
+ const helpText = `Tool inference failed. The model attempted to call a tool but the tool name could not be determined from the input parameters. Available tools: ${availableTools}. Please specify which tool you want to use.`;
449
+
450
+ // Emit as a text block instead of a tool_use
451
+ emitSSEEvent(controller, "content_block_start", {
452
+ type: "content_block_start",
453
+ index: blockIndex,
454
+ content_block: {
455
+ type: "text",
456
+ text: helpText,
457
+ },
458
+ });
459
+
460
+ emitSSEEvent(controller, "content_block_stop", {
461
+ type: "content_block_stop",
462
+ index: blockIndex,
463
+ });
464
+
465
+ continue;
466
+ }
467
+
439
468
  debugLog(
440
469
  "Flushing pending tool block",
441
470
  blockIndex,
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "opencode-crs-bedrock",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "OpenCode plugin for FeedMob CRS proxy to AWS Bedrock Anthropic models",
5
5
  "type": "module",
6
- "module": "index.ts",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.js",
7
8
  "files": [
9
+ "dist",
8
10
  "index.ts"
9
11
  ],
10
12
  "keywords": [