@opencode/ai 0.0.0-dev-491 → 0.0.0-dev-513

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 (57) hide show
  1. package/dist/protocols/anthropic-messages.js +35 -89
  2. package/dist/protocols/bedrock-converse.js +2 -3
  3. package/dist/protocols/gemini.js +26 -40
  4. package/dist/protocols/open-responses-channel.js +6 -19
  5. package/dist/protocols/open-responses-continuation.d.ts +1 -5
  6. package/dist/protocols/open-responses-continuation.js +1 -3
  7. package/dist/protocols/utils/bedrock-cache.js +2 -5
  8. package/dist/protocols/utils/cache.d.ts +3 -0
  9. package/dist/protocols/utils/cache.js +15 -2
  10. package/dist/providers/baseten.d.ts +1 -1
  11. package/dist/providers/baseten.js +5 -11
  12. package/dist/providers/cerebras.d.ts +1 -1
  13. package/dist/providers/cerebras.js +2 -8
  14. package/dist/providers/cloudflare-ai-gateway.js +5 -25
  15. package/dist/providers/cloudflare-shared.d.ts +9 -0
  16. package/dist/providers/cloudflare-shared.js +25 -0
  17. package/dist/providers/cloudflare-workers-ai.js +4 -20
  18. package/dist/providers/cohere.d.ts +1 -1
  19. package/dist/providers/cohere.js +4 -6
  20. package/dist/providers/deepinfra.d.ts +1 -1
  21. package/dist/providers/deepinfra.js +3 -6
  22. package/dist/providers/deepseek.d.ts +1 -1
  23. package/dist/providers/deepseek.js +2 -8
  24. package/dist/providers/digitalocean.d.ts +1 -1
  25. package/dist/providers/digitalocean.js +5 -7
  26. package/dist/providers/fireworks.d.ts +1 -1
  27. package/dist/providers/fireworks.js +2 -8
  28. package/dist/providers/google-vertex-chat.js +3 -29
  29. package/dist/providers/google-vertex-messages.js +3 -29
  30. package/dist/providers/google-vertex-mistral.js +3 -29
  31. package/dist/providers/google-vertex-responses.js +3 -29
  32. package/dist/providers/google-vertex-shared.d.ts +30 -0
  33. package/dist/providers/google-vertex-shared.js +25 -0
  34. package/dist/providers/groq.d.ts +1 -1
  35. package/dist/providers/groq.js +2 -8
  36. package/dist/providers/meta.d.ts +1 -1
  37. package/dist/providers/meta.js +2 -8
  38. package/dist/providers/minimax.d.ts +1 -1
  39. package/dist/providers/minimax.js +3 -10
  40. package/dist/providers/mistral.d.ts +1 -1
  41. package/dist/providers/mistral.js +2 -8
  42. package/dist/providers/moonshot.d.ts +1 -1
  43. package/dist/providers/moonshot.js +2 -8
  44. package/dist/providers/openrouter.d.ts +1 -1
  45. package/dist/providers/openrouter.js +5 -8
  46. package/dist/providers/settings.d.ts +21 -0
  47. package/dist/providers/settings.js +10 -0
  48. package/dist/providers/togetherai.d.ts +1 -1
  49. package/dist/providers/togetherai.js +2 -8
  50. package/dist/providers/vercel-ai-gateway.d.ts +1 -1
  51. package/dist/providers/vercel-ai-gateway.js +2 -8
  52. package/dist/providers/zai-coding-plan.d.ts +1 -1
  53. package/dist/providers/zai-coding-plan.js +2 -8
  54. package/dist/providers/zai.d.ts +1 -1
  55. package/dist/providers/zai.js +4 -12
  56. package/dist/schema/events.js +31 -64
  57. package/package.json +3 -3
@@ -402,11 +402,8 @@ const ANTHROPIC_BREAKPOINT_CAP = 4;
402
402
  const cacheControl = (breakpoints, cache) => {
403
403
  if (cache?.type !== "ephemeral" && cache?.type !== "persistent")
404
404
  return undefined;
405
- if (breakpoints.remaining <= 0) {
406
- breakpoints.dropped += 1;
405
+ if (!Cache.take(breakpoints))
407
406
  return undefined;
408
- }
409
- breakpoints.remaining -= 1;
410
407
  return { type: "ephemeral", ...(cache.ttl === undefined ? {} : { ttl: cache.ttl }) };
411
408
  };
412
409
  const providerMetadata = (key, metadata) => ({ [key]: metadata });
@@ -568,104 +565,55 @@ const lowerMedia = Effect.fnUntraced(function* (part, request, breakpoints) {
568
565
  };
569
566
  }
570
567
  const fileId = fileIdFromMetadata(part.metadata);
571
- // SDK file sources: FileImageSource:2350 / FileDocumentSource:2344 {type:"file", file_id}
572
- if (fileId) {
573
- if (mime.startsWith("image/"))
574
- return {
575
- type: "image",
576
- source: { type: "file", file_id: fileId },
577
- ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
578
- ...(transformationsFromMetadata(part.metadata) === undefined
579
- ? {}
580
- : { transformations: transformationsFromMetadata(part.metadata) }),
581
- };
568
+ const image = (source) => {
569
+ const transformations = transformationsFromMetadata(part.metadata);
570
+ return {
571
+ type: "image",
572
+ source,
573
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
574
+ ...(transformations === undefined ? {} : { transformations }),
575
+ };
576
+ };
577
+ const document = (source) => {
578
+ const title = documentTitleFromPart(part);
579
+ const context = documentContextFromMetadata(part.metadata);
580
+ const citations = citationsFromMetadata(part.metadata);
582
581
  return {
583
582
  type: "document",
584
- source: { type: "file", file_id: fileId },
583
+ source,
585
584
  ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
586
- ...(documentTitleFromPart(part) === undefined ? {} : { title: documentTitleFromPart(part) }),
587
- ...(documentContextFromMetadata(part.metadata) === undefined
588
- ? {}
589
- : { context: documentContextFromMetadata(part.metadata) }),
590
- ...(citationsFromMetadata(part.metadata) === undefined
591
- ? {}
592
- : { citations: citationsFromMetadata(part.metadata) }),
585
+ ...(title === undefined ? {} : { title }),
586
+ ...(context === undefined ? {} : { context }),
587
+ ...(citations === undefined ? {} : { citations }),
593
588
  };
589
+ };
590
+ // SDK file sources: FileImageSource:2350 / FileDocumentSource:2344 {type:"file", file_id}
591
+ if (fileId) {
592
+ if (mime.startsWith("image/"))
593
+ return image({ type: "file", file_id: fileId });
594
+ return document({ type: "file", file_id: fileId });
594
595
  }
595
596
  const rawString = ProviderShared.mediaUrl(part.media)?.trim();
596
597
  // SDK URL sources: URLImageSource:3817 / URLPDFSource:3823 {type:"url", url}
597
598
  if (rawString && isHttpUrl(rawString)) {
598
599
  if (mime.startsWith("image/"))
599
- return {
600
- type: "image",
601
- source: { type: "url", url: rawString },
602
- ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
603
- ...(transformationsFromMetadata(part.metadata) === undefined
604
- ? {}
605
- : { transformations: transformationsFromMetadata(part.metadata) }),
606
- };
600
+ return image({ type: "url", url: rawString });
607
601
  if (mime === "application/pdf")
608
- return {
609
- type: "document",
610
- source: { type: "url", url: rawString },
611
- ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
612
- ...(documentTitleFromPart(part) === undefined ? {} : { title: documentTitleFromPart(part) }),
613
- ...(documentContextFromMetadata(part.metadata) === undefined
614
- ? {}
615
- : { context: documentContextFromMetadata(part.metadata) }),
616
- ...(citationsFromMetadata(part.metadata) === undefined
617
- ? {}
618
- : { citations: citationsFromMetadata(part.metadata) }),
619
- };
602
+ return document({ type: "url", url: rawString });
620
603
  }
621
604
  const media = yield* ProviderShared.requireInlineMedia("Anthropic Messages", part.media);
622
605
  // SDK PlainTextSource:2716 {type:"text", media_type:"text/plain", data}
623
- if (mime === "text/plain") {
624
- const textData = Buffer.from(media.base64, "base64").toString("utf8");
625
- return {
626
- type: "document",
627
- source: { type: "text", media_type: "text/plain", data: textData },
628
- ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
629
- ...(documentTitleFromPart(part) === undefined ? {} : { title: documentTitleFromPart(part) }),
630
- ...(documentContextFromMetadata(part.metadata) === undefined
631
- ? {}
632
- : { context: documentContextFromMetadata(part.metadata) }),
633
- ...(citationsFromMetadata(part.metadata) === undefined
634
- ? {}
635
- : { citations: citationsFromMetadata(part.metadata) }),
636
- };
637
- }
606
+ if (mime === "text/plain")
607
+ return document({
608
+ type: "text",
609
+ media_type: "text/plain",
610
+ data: Buffer.from(media.base64, "base64").toString("utf8"),
611
+ });
638
612
  if (media.mime === "application/pdf")
639
- return {
640
- type: "document",
641
- source: {
642
- type: "base64",
643
- media_type: "application/pdf",
644
- data: media.base64,
645
- },
646
- ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
647
- ...(documentTitleFromPart(part) === undefined ? {} : { title: documentTitleFromPart(part) }),
648
- ...(documentContextFromMetadata(part.metadata) === undefined
649
- ? {}
650
- : { context: documentContextFromMetadata(part.metadata) }),
651
- ...(citationsFromMetadata(part.metadata) === undefined
652
- ? {}
653
- : { citations: citationsFromMetadata(part.metadata) }),
654
- };
613
+ return document({ type: "base64", media_type: "application/pdf", data: media.base64 });
655
614
  if (!media.mime.startsWith("image/"))
656
615
  return yield* invalid(`Anthropic Messages does not support media type ${part.media.mediaType}`);
657
- return {
658
- type: "image",
659
- source: {
660
- type: "base64",
661
- media_type: media.mime,
662
- data: media.base64,
663
- },
664
- ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
665
- ...(transformationsFromMetadata(part.metadata) === undefined
666
- ? {}
667
- : { transformations: transformationsFromMetadata(part.metadata) }),
668
- };
616
+ return image({ type: "base64", media_type: media.mime, data: media.base64 });
669
617
  });
670
618
  // Tool results may carry structured text, images, and documents. Keep media as provider-native
671
619
  // content instead of JSON-stringifying base64 into a prompt string.
@@ -931,9 +879,7 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
931
879
  cache_control: cacheControl(breakpoints, part.cache),
932
880
  }));
933
881
  const messages = yield* lowerMessages(flattened.request, breakpoints);
934
- if (breakpoints.dropped > 0) {
935
- yield* Effect.logWarning(`Anthropic Messages: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${ANTHROPIC_BREAKPOINT_CAP} per request.`);
936
- }
882
+ yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP);
937
883
  const output_config = updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format };
938
884
  const maxTokens = generation?.maxTokens ?? DEFAULT_MAX_TOKENS;
939
885
  const body = {
@@ -9,6 +9,7 @@ import { classifyProviderFailure } from "../provider-error.js";
9
9
  import { JsonObject, optionalArray, ProviderShared } from "./shared.js";
10
10
  import { BedrockAuth } from "./utils/bedrock-auth.js";
11
11
  import { BedrockCache } from "./utils/bedrock-cache.js";
12
+ import { warnDropped } from "./utils/cache.js";
12
13
  import { BedrockMedia } from "./utils/bedrock-media.js";
13
14
  import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js";
14
15
  import { Lifecycle } from "./utils/lifecycle.js";
@@ -501,9 +502,7 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request)
501
502
  })();
502
503
  const system = lowerSystem(breakpoints, request.system);
503
504
  const messages = yield* lowerMessages(flattened.request, breakpoints);
504
- if (breakpoints.dropped > 0) {
505
- yield* Effect.logWarning(`Bedrock Converse: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${BedrockCache.BEDROCK_BREAKPOINT_CAP} per request.`);
506
- }
505
+ yield* warnDropped(breakpoints, "Bedrock Converse", BedrockCache.BEDROCK_BREAKPOINT_CAP);
507
506
  const inferenceConfig = (() => {
508
507
  if (maxTokens === undefined &&
509
508
  generation?.temperature === undefined &&
@@ -202,6 +202,7 @@ const lowerContentPart = Effect.fnUntraced(function* (part) {
202
202
  return yield* GeminiGenerateContent.mediaPart("Gemini", part.media);
203
203
  });
204
204
  const providerMetadata = (key, metadata) => ({ [key]: metadata });
205
+ const signatureMetadata = (key, signature) => signature ? providerMetadata(key, { thoughtSignature: signature }) : undefined;
205
206
  const thoughtSignature = (metadata, key) => {
206
207
  const value = metadata?.[key];
207
208
  return typeof value?.thoughtSignature === "string" ? value.thoughtSignature : undefined;
@@ -472,13 +473,9 @@ const finish = (state) => {
472
473
  const events = [];
473
474
  let lifecycle = state.lifecycle;
474
475
  if (state.reasoningId !== undefined)
475
- lifecycle = Lifecycle.reasoningEnd(lifecycle, events, state.reasoningId, state.reasoningSignature === undefined
476
- ? undefined
477
- : providerMetadata(state.providerMetadataKey, { thoughtSignature: state.reasoningSignature }));
476
+ lifecycle = Lifecycle.reasoningEnd(lifecycle, events, state.reasoningId, signatureMetadata(state.providerMetadataKey, state.reasoningSignature));
478
477
  if (state.textId !== undefined)
479
- lifecycle = Lifecycle.textEnd(lifecycle, events, state.textId, state.textSignature === undefined
480
- ? undefined
481
- : providerMetadata(state.providerMetadataKey, { thoughtSignature: state.textSignature }));
478
+ lifecycle = Lifecycle.textEnd(lifecycle, events, state.textId, signatureMetadata(state.providerMetadataKey, state.textSignature));
482
479
  Lifecycle.finish(lifecycle, events, {
483
480
  reason: {
484
481
  normalized: promptBlockReason === undefined ? mapFinishReason(finishReason, state.hasToolCalls) : "content-filter",
@@ -546,6 +543,21 @@ const step = (state, event) => {
546
543
  let nextTextId = nextState.nextTextId;
547
544
  // Supplier ids must be tracked across chunks of the same response, not just within one event's parts.
548
545
  const seenCallIds = new Set(nextState.seenCallIds);
546
+ const signed = (signature) => signatureMetadata(state.providerMetadataKey, signature);
547
+ const endReasoning = () => {
548
+ if (reasoningId === undefined)
549
+ return;
550
+ lifecycle = Lifecycle.reasoningEnd(lifecycle, events, reasoningId, signed(reasoningSignature));
551
+ reasoningId = undefined;
552
+ reasoningSignature = undefined;
553
+ };
554
+ const endText = () => {
555
+ if (textId === undefined)
556
+ return;
557
+ lifecycle = Lifecycle.textEnd(lifecycle, events, textId, signed(textSignature));
558
+ textId = undefined;
559
+ textSignature = undefined;
560
+ };
549
561
  for (const input of candidate.content.parts ?? []) {
550
562
  if (ProviderShared.isRecord(input) &&
551
563
  !("text" in input) &&
@@ -569,40 +581,26 @@ const step = (state, event) => {
569
581
  lifecycle = Lifecycle.stepStart(lifecycle, events);
570
582
  events.push(LLMEvent.media({
571
583
  media: Media.base64(part.inlineData.data, part.inlineData.mimeType),
572
- providerMetadata: signature
573
- ? providerMetadata(state.providerMetadataKey, { thoughtSignature: signature })
574
- : undefined,
584
+ providerMetadata: signed(signature),
575
585
  }));
576
586
  continue;
577
587
  }
578
588
  if ("text" in part && part.text.length > 0) {
579
589
  if (part.thought) {
580
- if (textId !== undefined) {
581
- lifecycle = Lifecycle.textEnd(lifecycle, events, textId, textSignature
582
- ? providerMetadata(state.providerMetadataKey, { thoughtSignature: textSignature })
583
- : undefined);
584
- textId = undefined;
585
- textSignature = undefined;
586
- }
590
+ endText();
587
591
  if (reasoningId === undefined) {
588
592
  reasoningId = `reasoning-${nextReasoningId}`;
589
593
  nextReasoningId += 1;
590
594
  }
591
- lifecycle = Lifecycle.reasoningDelta(lifecycle, events, reasoningId, part.text, signature ? providerMetadata(state.providerMetadataKey, { thoughtSignature: signature }) : undefined);
595
+ lifecycle = Lifecycle.reasoningDelta(lifecycle, events, reasoningId, part.text, signed(signature));
592
596
  continue;
593
597
  }
594
- if (reasoningId !== undefined) {
595
- lifecycle = Lifecycle.reasoningEnd(lifecycle, events, reasoningId, reasoningSignature
596
- ? providerMetadata(state.providerMetadataKey, { thoughtSignature: reasoningSignature })
597
- : undefined);
598
- reasoningId = undefined;
599
- reasoningSignature = undefined;
600
- }
598
+ endReasoning();
601
599
  if (textId === undefined) {
602
600
  textId = `text-${nextTextId}`;
603
601
  nextTextId += 1;
604
602
  }
605
- lifecycle = Lifecycle.textDelta(lifecycle, events, textId, part.text, textSignature ? providerMetadata(state.providerMetadataKey, { thoughtSignature: textSignature }) : undefined);
603
+ lifecycle = Lifecycle.textDelta(lifecycle, events, textId, part.text, signed(textSignature));
606
604
  textSignature = undefined;
607
605
  continue;
608
606
  }
@@ -617,26 +615,14 @@ const step = (state, event) => {
617
615
  if (supplied !== undefined)
618
616
  seenCallIds.add(supplied);
619
617
  const id = supplied !== undefined && !duplicate ? supplied : `tool_${crypto.randomUUID().replaceAll("-", "")}`;
620
- if (reasoningId !== undefined) {
621
- lifecycle = Lifecycle.reasoningEnd(lifecycle, events, reasoningId, reasoningSignature
622
- ? providerMetadata(state.providerMetadataKey, { thoughtSignature: reasoningSignature })
623
- : undefined);
624
- reasoningId = undefined;
625
- reasoningSignature = undefined;
626
- }
627
- if (textId !== undefined) {
628
- lifecycle = Lifecycle.textEnd(lifecycle, events, textId, textSignature ? providerMetadata(state.providerMetadataKey, { thoughtSignature: textSignature }) : undefined);
629
- textId = undefined;
630
- textSignature = undefined;
631
- }
618
+ endReasoning();
619
+ endText();
632
620
  lifecycle = Lifecycle.stepStart(lifecycle, events);
633
621
  events.push(LLMEvent.toolCall({
634
622
  id,
635
623
  name: part.functionCall.name,
636
624
  input,
637
- providerMetadata: part.thoughtSignature
638
- ? providerMetadata(state.providerMetadataKey, { thoughtSignature: part.thoughtSignature })
639
- : undefined,
625
+ providerMetadata: signed(signature),
640
626
  }));
641
627
  hasToolCalls = true;
642
628
  }
@@ -9,18 +9,16 @@ const WebSocketResponseCreate = Schema.StructWithRest(Schema.Struct({ type: Sche
9
9
  Schema.Record(Schema.String, Schema.Unknown),
10
10
  ]);
11
11
  const decodeMessage = ProviderShared.validateWith(Schema.decodeUnknownEffect(WebSocketResponseCreate));
12
- const encodeMessage = Schema.encodeSync(Schema.fromJsonString(WebSocketResponseCreate));
13
12
  const message = (body) => Effect.gen(function* () {
14
13
  if (!ProviderShared.isRecord(body))
15
14
  return yield* ProviderShared.invalidRequest("Open Responses WebSocket body must be a JSON object");
16
15
  const { stream: _stream, stream_options: _streamOptions, background: _background, ...request } = body;
17
- const decoded = yield* decodeMessage({ ...request, type: "response.create" });
18
- return { request: decoded, message: encodeMessage(decoded) };
16
+ return yield* decodeMessage({ ...request, type: "response.create" });
19
17
  });
20
- const driver = (options, body) => {
18
+ const observer = (options) => {
21
19
  let responseID;
22
20
  let terminal = false;
23
- const observeEvent = Effect.fnUntraced(function* (_create, frame, event) {
21
+ return Effect.fnUntraced(function* (_create, frame, event) {
24
22
  if (terminal)
25
23
  return yield* ProviderShared.eventError(options.id, `${options.name} emitted ${event.type} after a terminal event`, frame);
26
24
  if (event.type === "error") {
@@ -65,15 +63,6 @@ const driver = (options, body) => {
65
63
  }
66
64
  return { type: "frame", frame };
67
65
  });
68
- return {
69
- create: () => Effect.sync(() => {
70
- responseID = undefined;
71
- terminal = false;
72
- return { message: body, mode: "full" };
73
- }),
74
- observeEvent,
75
- observe: (create, frame) => OpenResponses.decodeChannelEvent(frame).pipe(Effect.mapError((cause) => ProviderShared.eventError(options.id, `Invalid ${options.name} WebSocket event`, frame, cause)), Effect.flatMap((event) => observeEvent(create, frame, event))),
76
- };
77
66
  };
78
67
  export const transport = (options) => {
79
68
  const http = HttpTransport.sseJson.with();
@@ -84,8 +73,7 @@ export const transport = (options) => {
84
73
  const headers = Headers.remove(options.headers?.(parts.headers) ?? parts.headers, "content-length");
85
74
  const channel = input.webSocket && (options.enabled?.(parts.url) ?? true)
86
75
  ? yield* Effect.gen(function* () {
87
- const create = yield* message(parts.jsonBody);
88
- const base = driver(options, create.message);
76
+ const request = yield* message(parts.jsonBody);
89
77
  return {
90
78
  url: yield* WebSocketTransport.toWebSocketUrl(options.url?.(parts.url) ?? parts.url),
91
79
  headers,
@@ -93,9 +81,8 @@ export const transport = (options) => {
93
81
  driver: OpenResponsesContinuation.driver({
94
82
  id: options.id,
95
83
  name: options.name,
96
- request: create.request,
97
- message: create.message,
98
- base,
84
+ request,
85
+ base: observer(options),
99
86
  continuation: options.continuation,
100
87
  }),
101
88
  };
@@ -7,15 +7,11 @@ import { OpenResponses } from "./open-responses.js";
7
7
  * Whether omitted fields carry over from the continued response is provider behavior the route must know.
8
8
  */
9
9
  export type Shape = (request: Readonly<Record<string, unknown>>) => Readonly<Record<string, unknown>> | undefined;
10
- export interface BaseDriver extends WebSocketChannelDriver {
11
- readonly observeEvent?: (create: ChannelCreate, frame: string, event: OpenResponses.Event) => Effect.Effect<ChannelObservation, AIError>;
12
- }
13
10
  export interface DriverInput {
14
11
  readonly id: string;
15
12
  readonly name: string;
16
13
  readonly request: Readonly<Record<string, unknown>>;
17
- readonly message: string;
18
- readonly base: BaseDriver;
14
+ readonly base: (create: ChannelCreate, frame: string, event: OpenResponses.Event) => Effect.Effect<ChannelObservation, AIError>;
19
15
  readonly continuation?: Shape;
20
16
  }
21
17
  export declare const driver: (input: DriverInput) => WebSocketChannelDriver;
@@ -121,9 +121,7 @@ export const driver = (input) => {
121
121
  }),
122
122
  observe: (create, frame) => Effect.gen(function* () {
123
123
  const event = yield* OpenResponses.decodeChannelEvent(frame).pipe(Effect.mapError((cause) => ProviderShared.eventError(input.id, `Invalid ${input.name} WebSocket event`, frame, cause)));
124
- const observation = yield* input.base.observeEvent
125
- ? input.base.observeEvent(create, frame, event)
126
- : input.base.observe(create, frame);
124
+ const observation = yield* input.base(create, frame, event);
127
125
  if (event.type === "response.output_item.done" && event.item)
128
126
  output.push(event.item);
129
127
  if (observation.type === "provider-failure") {
@@ -1,6 +1,6 @@
1
1
  import { Schema } from "effect";
2
2
  import { CacheTTL } from "../../schema/index.js";
3
- import { newBreakpoints } from "./cache.js";
3
+ import { newBreakpoints, take } from "./cache.js";
4
4
  // Bedrock cache markers are positional: emit a `cachePoint` block immediately
5
5
  // after the content the caller wants treated as a cacheable prefix. Bedrock
6
6
  // accepts an optional `ttl` such as "5m" or "1h" on cachePoint.
@@ -40,11 +40,8 @@ export const block = (breakpoints, cache) => {
40
40
  return undefined;
41
41
  if (cache?.type !== "ephemeral" && cache?.type !== "persistent")
42
42
  return undefined;
43
- if (breakpoints.remaining <= 0) {
44
- breakpoints.dropped += 1;
43
+ if (!take(breakpoints))
45
44
  return undefined;
46
- }
47
- breakpoints.remaining -= 1;
48
45
  // Older Claude releases cache for five minutes only, so a one-hour request falls back to the default.
49
46
  const ttl = cache.ttl === "1h" && !breakpoints.ttl1h ? undefined : cache.ttl;
50
47
  return { cachePoint: { type: "default", ...(ttl === undefined ? {} : { ttl }) } };
@@ -1,9 +1,12 @@
1
+ import { Effect } from "effect";
1
2
  import type { CacheHint, CacheTTL } from "../../schema/index.js";
2
3
  export interface Breakpoints {
3
4
  remaining: number;
4
5
  dropped: number;
5
6
  }
6
7
  export declare const newBreakpoints: (cap: number) => Breakpoints;
8
+ export declare const take: (breakpoints: Breakpoints) => boolean;
9
+ export declare const warnDropped: (breakpoints: Breakpoints, protocol: string, cap: number) => Effect.Effect<void, never, never>;
7
10
  export declare const cacheControl: () => (cache: CacheHint | undefined) => {
8
11
  type: "ephemeral";
9
12
  ttl: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
@@ -1,10 +1,23 @@
1
+ // Shared counter and lifetime mapping for provider cache lowering.
2
+ import { Effect } from "effect";
1
3
  export const newBreakpoints = (cap) => ({ remaining: cap, dropped: 0 });
4
+ // Spends one breakpoint, or records it as dropped once the budget is gone.
5
+ export const take = (breakpoints) => {
6
+ if (breakpoints.remaining <= 0) {
7
+ breakpoints.dropped += 1;
8
+ return false;
9
+ }
10
+ breakpoints.remaining -= 1;
11
+ return true;
12
+ };
13
+ export const warnDropped = (breakpoints, protocol, cap) => breakpoints.dropped === 0
14
+ ? Effect.void
15
+ : Effect.logWarning(`${protocol}: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${cap} per request.`);
2
16
  export const cacheControl = () => {
3
17
  const breakpoints = newBreakpoints(4);
4
18
  return (cache) => {
5
- if (cache === undefined || breakpoints.remaining === 0)
19
+ if (cache === undefined || !take(breakpoints))
6
20
  return undefined;
7
- breakpoints.remaining -= 1;
8
21
  return { type: "ephemeral", ttl: cache.ttl };
9
22
  };
10
23
  };
@@ -1,5 +1,5 @@
1
1
  import type { ProviderPackage } from "../provider-package.js";
2
- import { type ProviderAuthOption } from "../route/auth-options.js";
2
+ import type { ProviderAuthOption } from "../route/auth-options.js";
3
3
  import { Route, type RouteDefaultsInput } from "../route/client.js";
4
4
  import { type ModelID, type ProviderOptions } from "../schema/index.js";
5
5
  import type { OpenAIProviderOptionsInput } from "./openai-options.js";
@@ -1,12 +1,11 @@
1
1
  import { Effect } from "effect";
2
2
  import { OpenAIChat } from "../protocols/openai-chat.js";
3
3
  import { SystemOne } from "../protocols/system-one.js";
4
- import { AuthOptions } from "../route/auth-options.js";
5
4
  import { Route } from "../route/client.js";
6
5
  import { DecisionRoute } from "../route/decision.js";
7
6
  import { Endpoint } from "../route/endpoint.js";
8
7
  import { ProviderID } from "../schema/index.js";
9
- import { toConfig } from "./settings.js";
8
+ import { bearerRouteDefaults, toConfig } from "./settings.js";
10
9
  export const id = ProviderID.make("baseten");
11
10
  const baseURL = "https://inference.baseten.co/v1";
12
11
  export const route = Route.make({
@@ -28,20 +27,15 @@ const decisionProtocol = DecisionRoute.protocol({
28
27
  },
29
28
  });
30
29
  export const configure = (input = {}) => {
31
- const { apiKey: _apiKey, auth: _auth, baseURL: endpoint, ...defaults } = input;
32
- const auth = AuthOptions.bearer(input, "BASETEN_API_KEY");
33
- const configured = route.with({
34
- ...defaults,
35
- endpoint: { baseURL: endpoint ?? baseURL },
36
- auth,
37
- });
30
+ const options = bearerRouteDefaults(input, "BASETEN_API_KEY", baseURL);
31
+ const configured = route.with(options);
38
32
  const decisionRoute = DecisionRoute.make({
39
33
  id: decisionProtocol.id,
40
34
  provider: id,
41
35
  providerMetadataKey: "baseten",
42
36
  protocol: decisionProtocol,
43
- endpoint: Endpoint.path("/systemone", { baseURL: endpoint ?? baseURL }),
44
- auth,
37
+ endpoint: Endpoint.path("/systemone", { baseURL: options.endpoint.baseURL }),
38
+ auth: options.auth,
45
39
  headers: input.headers,
46
40
  http: input.http,
47
41
  });
@@ -1,5 +1,5 @@
1
1
  import type { ProviderPackage } from "../provider-package.js";
2
- import { type ProviderAuthOption } from "../route/auth-options.js";
2
+ import type { ProviderAuthOption } from "../route/auth-options.js";
3
3
  import { Route, type RouteDefaultsInput } from "../route/client.js";
4
4
  import { type ModelID } from "../schema/index.js";
5
5
  import type { OpenAIProviderOptionsInput } from "./openai-options.js";
@@ -1,9 +1,8 @@
1
1
  import { OpenAIChat } from "../protocols/openai-chat.js";
2
- import { AuthOptions } from "../route/auth-options.js";
3
2
  import { Route } from "../route/client.js";
4
3
  import { Endpoint } from "../route/endpoint.js";
5
4
  import { ProviderID } from "../schema/index.js";
6
- import { toConfig } from "./settings.js";
5
+ import { bearerRouteDefaults, toConfig } from "./settings.js";
7
6
  export const id = ProviderID.make("cerebras");
8
7
  const baseURL = "https://api.cerebras.ai/v1";
9
8
  export const route = Route.make({
@@ -16,12 +15,7 @@ export const route = Route.make({
16
15
  });
17
16
  export const routes = [route];
18
17
  export const configure = (input = {}) => {
19
- const { apiKey: _apiKey, auth: _auth, baseURL: endpoint, ...defaults } = input;
20
- const configured = route.with({
21
- ...defaults,
22
- endpoint: { baseURL: endpoint ?? baseURL },
23
- auth: AuthOptions.bearer(input, "CEREBRAS_API_KEY"),
24
- });
18
+ const configured = route.with(bearerRouteDefaults(input, "CEREBRAS_API_KEY", baseURL));
25
19
  return {
26
20
  id,
27
21
  model: (modelID) => configured.model({
@@ -1,38 +1,18 @@
1
1
  import { CloudflareRunDecisions } from "../protocols/cloudflare-run-decisions.js";
2
2
  import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../protocols/index.js";
3
3
  import { Auth } from "../route/auth.js";
4
- import { Endpoint } from "../route/endpoint.js";
5
4
  import { AuthOptions } from "../route/auth-options.js";
6
- import { ProviderConfigurationError, ProviderID } from "../schema/index.js";
5
+ import { ProviderID } from "../schema/index.js";
7
6
  import { encodeJson } from "../utils/json.js";
7
+ import { CloudflareShared } from "./cloudflare-shared.js";
8
8
  export const id = ProviderID.make("cloudflare-ai-gateway");
9
9
  export const authEnvVars = ["CLOUDFLARE_API_TOKEN", "CF_AIG_TOKEN"];
10
- export const baseURL = (input) => {
11
- if (input.baseURL)
12
- return input.baseURL;
13
- return `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(requireAccountId(input))}/ai/v1`;
14
- };
10
+ export const baseURL = (input) => CloudflareShared.baseURL(input, id, "CloudflareAIGateway");
15
11
  /** The Run API (`/ai/run`) next to the OpenAI-compatible `/ai/v1` base. */
16
- export const runBaseURL = (input) => {
17
- const url = Endpoint.trimBaseUrl(baseURL(input));
18
- if (!url.endsWith("/ai/v1"))
19
- throw new ProviderConfigurationError({
20
- provider: id,
21
- message: "CloudflareAIGateway needs accountId or a baseURL ending in /ai/v1 to derive the Run API base",
22
- });
23
- return `${url.slice(0, -"/v1".length)}/run`;
24
- };
12
+ export const runBaseURL = (input) => CloudflareShared.runBaseURL(input, id, "CloudflareAIGateway");
25
13
  // Cloudflare's REST API rejects parts of the Anthropic Messages and OpenAI Responses request shapes, such as
26
14
  // system prompt blocks and `minimal` reasoning effort, so these models use the provider-native gateway endpoints.
27
- const passthroughURL = (input, provider) => `https://gateway.ai.cloudflare.com/v1/${encodeURIComponent(requireAccountId(input))}/${encodeURIComponent(gatewayId(input))}/${provider}`;
28
- const requireAccountId = (input) => {
29
- if (input.accountId)
30
- return input.accountId;
31
- throw new ProviderConfigurationError({
32
- provider: id,
33
- message: "CloudflareAIGateway.configure requires accountId unless baseURL is supplied",
34
- });
35
- };
15
+ const passthroughURL = (input, provider) => `https://gateway.ai.cloudflare.com/v1/${encodeURIComponent(CloudflareShared.requireAccountId(input, id, "CloudflareAIGateway"))}/${encodeURIComponent(gatewayId(input))}/${provider}`;
36
16
  const gatewayId = (input) => input.gatewayId?.trim() || "default";
37
17
  export const responsesRoute = OpenAIResponses.route.with({
38
18
  id: "cloudflare-ai-gateway-responses",
@@ -0,0 +1,9 @@
1
+ import { type ProviderID } from "../schema/index.js";
2
+ type AccountURL = {
3
+ readonly accountId?: string;
4
+ readonly baseURL?: string;
5
+ };
6
+ export declare const requireAccountId: (input: AccountURL, provider: ProviderID, name: string) => string;
7
+ export declare const baseURL: (input: AccountURL, provider: ProviderID, name: string) => string;
8
+ export declare const runBaseURL: (input: AccountURL, provider: ProviderID, name: string) => string;
9
+ export * as CloudflareShared from "./cloudflare-shared.js";
@@ -0,0 +1,25 @@
1
+ import { Endpoint } from "../route/endpoint.js";
2
+ import { ProviderConfigurationError } from "../schema/index.js";
3
+ export const requireAccountId = (input, provider, name) => {
4
+ if (input.accountId)
5
+ return input.accountId;
6
+ throw new ProviderConfigurationError({
7
+ provider,
8
+ message: `${name}.configure requires accountId unless baseURL is supplied`,
9
+ });
10
+ };
11
+ export const baseURL = (input, provider, name) => {
12
+ if (input.baseURL)
13
+ return input.baseURL;
14
+ return `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(requireAccountId(input, provider, name))}/ai/v1`;
15
+ };
16
+ export const runBaseURL = (input, provider, name) => {
17
+ const url = Endpoint.trimBaseUrl(baseURL(input, provider, name));
18
+ if (!url.endsWith("/ai/v1"))
19
+ throw new ProviderConfigurationError({
20
+ provider,
21
+ message: `${name} needs accountId or a baseURL ending in /ai/v1 to derive the Run API base`,
22
+ });
23
+ return `${url.slice(0, -"/v1".length)}/run`;
24
+ };
25
+ export * as CloudflareShared from "./cloudflare-shared.js";