@opencode/ai 2.1.4 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +283 -114
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/cache-policy.d.ts +4 -0
  5. package/dist/cache-policy.js +20 -6
  6. package/dist/decision-client.d.ts +21 -0
  7. package/dist/decision-client.js +55 -0
  8. package/dist/decision.d.ts +472 -0
  9. package/dist/decision.js +158 -0
  10. package/dist/effect.d.ts +38 -0
  11. package/dist/effect.js +27 -0
  12. package/dist/effort-updates.d.ts +2 -2
  13. package/dist/experimental/cloudflare-run-extraction.d.ts +13 -0
  14. package/dist/experimental/cloudflare-run-extraction.js +83 -0
  15. package/dist/experimental/extraction.d.ts +183 -0
  16. package/dist/experimental/extraction.js +102 -0
  17. package/dist/experimental/realtime.d.ts +7 -2
  18. package/dist/experimental/realtime.js +5 -5
  19. package/dist/experimental.d.ts +2 -3
  20. package/dist/experimental.js +1 -2
  21. package/dist/image-client.d.ts +5 -14
  22. package/dist/image-client.js +0 -1
  23. package/dist/image.d.ts +6 -176
  24. package/dist/image.js +4 -11
  25. package/dist/index.d.ts +1426 -34
  26. package/dist/index.js +127 -24
  27. package/dist/llm.d.ts +16 -1
  28. package/dist/llm.js +34 -0
  29. package/dist/media-client.d.ts +2 -1
  30. package/dist/media-model.d.ts +3 -0
  31. package/dist/media-model.js +4 -1
  32. package/dist/media.d.ts +0 -7
  33. package/dist/media.js +0 -6
  34. package/dist/protocols/alibaba-chat.d.ts +20 -0
  35. package/dist/protocols/alibaba-images.d.ts +22 -0
  36. package/dist/protocols/alibaba-images.js +77 -0
  37. package/dist/protocols/alibaba-messages.d.ts +52 -17
  38. package/dist/protocols/alibaba-responses.d.ts +6 -3
  39. package/dist/protocols/anthropic-messages.d.ts +160 -54
  40. package/dist/protocols/anthropic-messages.js +44 -13
  41. package/dist/protocols/bedrock-converse.d.ts +110 -15
  42. package/dist/protocols/bedrock-converse.js +112 -15
  43. package/dist/protocols/bedrock-event-stream.js +1 -0
  44. package/dist/protocols/bfl-images.d.ts +9 -0
  45. package/dist/protocols/bfl-images.js +17 -15
  46. package/dist/protocols/cartesia-speech.d.ts +0 -18
  47. package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
  48. package/dist/protocols/cloudflare-run-decisions.js +36 -0
  49. package/dist/protocols/cloudflare-workers-ai-images.d.ts +23 -0
  50. package/dist/protocols/cloudflare-workers-ai-images.js +80 -0
  51. package/dist/protocols/deepgram-speech.d.ts +0 -18
  52. package/dist/protocols/elevenlabs-speech.d.ts +0 -18
  53. package/dist/protocols/fal-images.d.ts +10 -1
  54. package/dist/protocols/fal-images.js +16 -25
  55. package/dist/protocols/fal-video.js +1 -1
  56. package/dist/protocols/gemini.d.ts +3 -0
  57. package/dist/protocols/gemini.js +11 -6
  58. package/dist/protocols/google-images.d.ts +2 -2
  59. package/dist/protocols/google-images.js +8 -37
  60. package/dist/protocols/google-interactions.d.ts +4 -0
  61. package/dist/protocols/google-interactions.js +12 -5
  62. package/dist/protocols/google-speech.d.ts +0 -18
  63. package/dist/protocols/google-speech.js +0 -1
  64. package/dist/protocols/google-transcription.d.ts +0 -18
  65. package/dist/protocols/google-transcription.js +0 -1
  66. package/dist/protocols/google-video.d.ts +1 -1
  67. package/dist/protocols/google-video.js +2 -7
  68. package/dist/protocols/index.d.ts +3 -0
  69. package/dist/protocols/index.js +3 -0
  70. package/dist/protocols/meta-images.d.ts +7 -1
  71. package/dist/protocols/meta-images.js +10 -8
  72. package/dist/protocols/meta-messages.d.ts +52 -17
  73. package/dist/protocols/meta-messages.js +14 -1
  74. package/dist/protocols/meta-responses.d.ts +6 -0
  75. package/dist/protocols/meta-responses.js +29 -1
  76. package/dist/protocols/open-responses.d.ts +30 -0
  77. package/dist/protocols/open-responses.js +8 -18
  78. package/dist/protocols/openai-chat.d.ts +713 -1
  79. package/dist/protocols/openai-chat.js +35 -22
  80. package/dist/protocols/openai-compatible-chat.d.ts +22 -1
  81. package/dist/protocols/openai-compatible-responses.d.ts +8 -5
  82. package/dist/protocols/openai-decisions.d.ts +22 -0
  83. package/dist/protocols/openai-decisions.js +128 -0
  84. package/dist/protocols/openai-images.d.ts +21 -24
  85. package/dist/protocols/openai-images.js +100 -34
  86. package/dist/protocols/openai-responses.d.ts +82 -24
  87. package/dist/protocols/openai-responses.js +32 -2
  88. package/dist/protocols/openai-speech.d.ts +0 -18
  89. package/dist/protocols/openai-speech.js +15 -5
  90. package/dist/protocols/openai-transcription.d.ts +0 -18
  91. package/dist/protocols/openai-transcription.js +3 -4
  92. package/dist/protocols/replicate-images.js +1 -1
  93. package/dist/protocols/runway-video.d.ts +1 -1
  94. package/dist/protocols/runway-video.js +1 -1
  95. package/dist/protocols/shared.d.ts +9 -1
  96. package/dist/protocols/shared.js +13 -2
  97. package/dist/protocols/stability-images.d.ts +5 -0
  98. package/dist/protocols/stability-images.js +4 -9
  99. package/dist/protocols/system-one.d.ts +101 -0
  100. package/dist/protocols/system-one.js +230 -0
  101. package/dist/protocols/utils/bedrock-cache.d.ts +2 -2
  102. package/dist/protocols/utils/bedrock-cache.js +7 -6
  103. package/dist/protocols/utils/cache.d.ts +14 -3
  104. package/dist/protocols/utils/cache.js +11 -4
  105. package/dist/protocols/utils/gemini-generate-content.d.ts +3 -3
  106. package/dist/protocols/utils/gemini-generate-content.js +10 -16
  107. package/dist/protocols/utils/gemini-json-schema.d.ts +5 -0
  108. package/dist/protocols/utils/gemini-json-schema.js +3 -3
  109. package/dist/protocols/utils/image-sizing.d.ts +31 -0
  110. package/dist/protocols/utils/image-sizing.js +73 -0
  111. package/dist/protocols/utils/media-input.d.ts +4 -5
  112. package/dist/protocols/utils/media-input.js +8 -5
  113. package/dist/protocols/utils/speech-stream.d.ts +0 -1
  114. package/dist/protocols/utils/speech-stream.js +0 -1
  115. package/dist/protocols/utils/tool-schema.js +15 -5
  116. package/dist/protocols/utils/tool-stream.d.ts +9 -0
  117. package/dist/protocols/venice-chat.d.ts +19 -0
  118. package/dist/protocols/venice-chat.js +1 -1
  119. package/dist/protocols/xai-images.d.ts +1 -2
  120. package/dist/protocols/xai-images.js +9 -2
  121. package/dist/protocols/xai-responses.d.ts +10 -0
  122. package/dist/protocols/xai-responses.js +28 -2
  123. package/dist/protocols/xai-video.d.ts +1 -1
  124. package/dist/protocols/xai-video.js +11 -8
  125. package/dist/protocols/zai-chat.d.ts +21 -0
  126. package/dist/protocols/zai-images.d.ts +3 -1
  127. package/dist/protocols/zai-images.js +12 -11
  128. package/dist/protocols/zai-messages.d.ts +52 -17
  129. package/dist/provider-error.js +19 -4
  130. package/dist/providers/alibaba/images.d.ts +2 -0
  131. package/dist/providers/alibaba/images.js +1 -0
  132. package/dist/providers/alibaba.d.ts +79 -18
  133. package/dist/providers/alibaba.js +16 -8
  134. package/dist/providers/amazon-bedrock-mantle.d.ts +197 -138
  135. package/dist/providers/amazon-bedrock.d.ts +34 -14
  136. package/dist/providers/amazon-bedrock.js +11 -11
  137. package/dist/providers/anthropic-compatible.d.ts +52 -17
  138. package/dist/providers/anthropic.d.ts +52 -17
  139. package/dist/providers/azure/images.d.ts +2 -0
  140. package/dist/providers/azure/images.js +1 -0
  141. package/dist/providers/azure.d.ts +50 -9
  142. package/dist/providers/azure.js +19 -1
  143. package/dist/providers/baseten/decisions.d.ts +2 -0
  144. package/dist/providers/baseten/decisions.js +1 -0
  145. package/dist/providers/baseten.d.ts +51 -1
  146. package/dist/providers/baseten.js +41 -8
  147. package/dist/providers/cerebras.d.ts +42 -0
  148. package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
  149. package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
  150. package/dist/providers/cloudflare-ai-gateway.d.ts +177 -43
  151. package/dist/providers/cloudflare-ai-gateway.js +32 -4
  152. package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
  153. package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
  154. package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
  155. package/dist/providers/cloudflare-workers-ai/images.js +1 -0
  156. package/dist/providers/cloudflare-workers-ai.d.ts +55 -1
  157. package/dist/providers/cloudflare-workers-ai.js +45 -9
  158. package/dist/providers/cohere.d.ts +42 -0
  159. package/dist/providers/deepinfra.d.ts +42 -0
  160. package/dist/providers/deepseek.d.ts +42 -0
  161. package/dist/providers/digitalocean/decisions.d.ts +2 -0
  162. package/dist/providers/digitalocean/decisions.js +1 -0
  163. package/dist/providers/digitalocean/images.d.ts +2 -0
  164. package/dist/providers/digitalocean/images.js +1 -0
  165. package/dist/providers/digitalocean.d.ts +72 -1
  166. package/dist/providers/digitalocean.js +39 -8
  167. package/dist/providers/fireworks.d.ts +42 -0
  168. package/dist/providers/google/images.d.ts +2 -0
  169. package/dist/providers/google/images.js +1 -0
  170. package/dist/providers/google-vertex/images.d.ts +2 -0
  171. package/dist/providers/google-vertex/images.js +1 -0
  172. package/dist/providers/google-vertex-chat.d.ts +21 -0
  173. package/dist/providers/google-vertex-messages.d.ts +52 -17
  174. package/dist/providers/google-vertex-responses.d.ts +3 -0
  175. package/dist/providers/google-vertex.d.ts +3 -1
  176. package/dist/providers/google-vertex.js +30 -13
  177. package/dist/providers/google.d.ts +5 -4
  178. package/dist/providers/google.js +15 -8
  179. package/dist/providers/groq.d.ts +42 -4
  180. package/dist/providers/groq.js +0 -6
  181. package/dist/providers/meta.d.ts +197 -138
  182. package/dist/providers/minimax.d.ts +76 -17
  183. package/dist/providers/moonshot.d.ts +76 -17
  184. package/dist/providers/openai/images.d.ts +2 -0
  185. package/dist/providers/openai/images.js +1 -0
  186. package/dist/providers/openai-compatible/images.d.ts +2 -0
  187. package/dist/providers/openai-compatible/images.js +1 -0
  188. package/dist/providers/openai-compatible-responses.d.ts +3 -0
  189. package/dist/providers/openai-compatible.d.ts +24 -1
  190. package/dist/providers/openai-compatible.js +21 -9
  191. package/dist/providers/openai-options.d.ts +3 -1
  192. package/dist/providers/openai.d.ts +46 -9
  193. package/dist/providers/openai.js +20 -4
  194. package/dist/providers/opencode/decisions.d.ts +2 -0
  195. package/dist/providers/opencode/decisions.js +1 -0
  196. package/dist/providers/opencode.d.ts +9 -10
  197. package/dist/providers/opencode.js +10 -8
  198. package/dist/providers/openrouter/decisions.d.ts +2 -0
  199. package/dist/providers/openrouter/decisions.js +1 -0
  200. package/dist/providers/openrouter/images.d.ts +2 -0
  201. package/dist/providers/openrouter/images.js +1 -0
  202. package/dist/providers/openrouter.d.ts +92 -11
  203. package/dist/providers/openrouter.js +38 -16
  204. package/dist/providers/togetherai.d.ts +42 -0
  205. package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
  206. package/dist/providers/typesafe-ai/decisions.js +1 -0
  207. package/dist/providers/typesafe-ai.d.ts +9 -10
  208. package/dist/providers/typesafe-ai.js +10 -8
  209. package/dist/providers/venice.d.ts +19 -0
  210. package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
  211. package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
  212. package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
  213. package/dist/providers/vercel-ai-gateway/images.js +1 -0
  214. package/dist/providers/vercel-ai-gateway.d.ts +10 -16
  215. package/dist/providers/vercel-ai-gateway.js +31 -85
  216. package/dist/providers/xai/images.d.ts +2 -0
  217. package/dist/providers/xai/images.js +1 -0
  218. package/dist/providers/xai.d.ts +28 -5
  219. package/dist/providers/xai.js +15 -8
  220. package/dist/providers/zai/images.d.ts +2 -0
  221. package/dist/providers/zai/images.js +1 -0
  222. package/dist/providers/zai-coding-plan.d.ts +76 -17
  223. package/dist/providers/zai.d.ts +26 -4
  224. package/dist/providers/zai.js +15 -8
  225. package/dist/route/client.d.ts +2 -2
  226. package/dist/route/client.js +26 -4
  227. package/dist/route/decision.d.ts +58 -0
  228. package/dist/route/decision.js +75 -0
  229. package/dist/route/executor.d.ts +1 -1
  230. package/dist/route/framing.d.ts +2 -0
  231. package/dist/route/index.d.ts +3 -0
  232. package/dist/route/index.js +3 -0
  233. package/dist/route/media-protocol.d.ts +1 -0
  234. package/dist/route/media-protocol.js +12 -8
  235. package/dist/route/media.d.ts +5 -1
  236. package/dist/route/media.js +6 -2
  237. package/dist/route/transport/http.js +1 -0
  238. package/dist/route/transport/index.d.ts +1 -0
  239. package/dist/schema/events.d.ts +148 -6
  240. package/dist/schema/events.js +20 -0
  241. package/dist/schema/messages.d.ts +6 -2
  242. package/dist/schema/messages.js +3 -0
  243. package/dist/schema/options.d.ts +5 -3
  244. package/dist/schema/options.js +8 -3
  245. package/dist/speech-client.d.ts +5 -14
  246. package/dist/speech-client.js +0 -1
  247. package/dist/speech.d.ts +0 -135
  248. package/dist/speech.js +2 -4
  249. package/dist/testing.d.ts +25 -24
  250. package/dist/testing.js +3 -21
  251. package/dist/transcription-client.d.ts +5 -14
  252. package/dist/transcription.d.ts +0 -135
  253. package/dist/transcription.js +1 -1
  254. package/dist/utils/media-type.js +22 -1
  255. package/dist/video-client.d.ts +5 -14
  256. package/dist/video-client.js +0 -1
  257. package/dist/video.d.ts +1 -136
  258. package/dist/video.js +3 -5
  259. package/package.json +513 -11
  260. package/dist/experimental/evaluation-client.d.ts +0 -21
  261. package/dist/experimental/evaluation-client.js +0 -64
  262. package/dist/experimental/evaluation.d.ts +0 -242
  263. package/dist/experimental/evaluation.js +0 -108
  264. package/dist/experimental/system-one.d.ts +0 -16
  265. package/dist/experimental/system-one.js +0 -135
  266. package/dist/promise.d.ts +0 -1021
  267. package/dist/promise.js +0 -101
  268. package/dist/provider.d.ts +0 -23
  269. package/dist/provider.js +0 -2
@@ -1,8 +1,8 @@
1
- import { Effect, Schema } from "effect";
1
+ import { Effect, Schema, SchemaGetter } from "effect";
2
2
  import { Framing } from "../route/framing.js";
3
3
  import { MediaProtocol } from "../route/media-protocol.js";
4
4
  import { MediaRoute } from "../route/media.js";
5
- import { mergeJsonRecords } from "../schema/index.js";
5
+ import { mergeJsonRecords, tokenUsage } from "../schema/index.js";
6
6
  import { SpeechModel } from "../speech.js";
7
7
  import { SpeechStream } from "./utils/speech-stream.js";
8
8
  const route = MediaProtocol.identity({ id: "openai-speech", name: "OpenAI Speech", provider: "openai" });
@@ -13,6 +13,14 @@ const PCM_SAMPLE_RATE = 24000;
13
13
  // ---------------------------------------------------------------------------
14
14
  // 3. Streaming event schema
15
15
  // ---------------------------------------------------------------------------
16
+ const EVENT_TYPES = new Set(["speech.audio.delta", "speech.audio.done"]);
17
+ /** OpenAI may add stream event types; frames outside `EVENT_TYPES` are ignored, while a malformed known type still fails decoding. */
18
+ const UnknownEvent = Schema.Struct({
19
+ type: Schema.String.check(Schema.makeFilter((type) => !EVENT_TYPES.has(type))),
20
+ }).pipe(Schema.decodeTo(Schema.Struct({ type: Schema.Literal("unknown"), rawType: Schema.String }), {
21
+ decode: SchemaGetter.transform((event) => ({ type: "unknown", rawType: event.type })),
22
+ encode: SchemaGetter.forbidden(() => "Unknown OpenAI Speech stream events are decode-only"),
23
+ }));
16
24
  const SpeechStreamEvent = Schema.Union([
17
25
  Schema.Struct({ type: Schema.Literal("speech.audio.delta"), audio: Schema.Uint8ArrayFromBase64 }),
18
26
  Schema.Struct({
@@ -23,6 +31,7 @@ const SpeechStreamEvent = Schema.Union([
23
31
  total_tokens: Schema.optional(Schema.Number),
24
32
  })),
25
33
  }),
34
+ UnknownEvent,
26
35
  ]);
27
36
  const decodeEvent = route.decodeFrame(SpeechStreamEvent);
28
37
  // ---------------------------------------------------------------------------
@@ -53,6 +62,8 @@ const fromRequest = Effect.fn("OpenAISpeech.fromRequest")(function* (request) {
53
62
  const isSse = (body) => body.type === "json" && body.value.stream_format === "sse";
54
63
  const onEvent = Effect.fnUntraced(function* (state, frame) {
55
64
  const event = yield* decodeEvent(frame);
65
+ if (event.type === "unknown")
66
+ return [state, []];
56
67
  if (event.type === "speech.audio.delta")
57
68
  return SpeechStream.delta(state, event.audio);
58
69
  const usage = event.usage;
@@ -62,13 +73,12 @@ const onEvent = Effect.fnUntraced(function* (state, frame) {
62
73
  done: true,
63
74
  usage: usage === undefined
64
75
  ? undefined
65
- : {
66
- type: "tokens",
76
+ : tokenUsage({
67
77
  input: usage.input_tokens,
68
78
  output: usage.output_tokens,
69
79
  total: usage.total_tokens,
70
80
  details: { openai: usage },
71
- },
81
+ }),
72
82
  },
73
83
  [],
74
84
  ];
@@ -115,15 +115,6 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
115
115
  readonly [x: string]: unknown;
116
116
  } | undefined;
117
117
  } | undefined;
118
- readonly notices?: readonly {
119
- readonly type: "filtered" | "moderated" | "other";
120
- readonly message: string;
121
- readonly providerMetadata?: {
122
- readonly [x: string]: {
123
- readonly [x: string]: unknown;
124
- };
125
- } | undefined;
126
- }[] | undefined;
127
118
  readonly providerMetadata?: {
128
119
  readonly [x: string]: {
129
120
  readonly [x: string]: unknown;
@@ -190,15 +181,6 @@ export declare const OpenAITranscription: {
190
181
  readonly [x: string]: unknown;
191
182
  } | undefined;
192
183
  } | undefined;
193
- readonly notices?: readonly {
194
- readonly type: "filtered" | "moderated" | "other";
195
- readonly message: string;
196
- readonly providerMetadata?: {
197
- readonly [x: string]: {
198
- readonly [x: string]: unknown;
199
- };
200
- } | undefined;
201
- }[] | undefined;
202
184
  readonly providerMetadata?: {
203
185
  readonly [x: string]: {
204
186
  readonly [x: string]: unknown;
@@ -3,7 +3,7 @@ import { classifyProviderFailure } from "../provider-error.js";
3
3
  import { Framing } from "../route/framing.js";
4
4
  import { MediaProtocol } from "../route/media-protocol.js";
5
5
  import { MediaRoute } from "../route/media.js";
6
- import { AIError, mergeJsonRecords } from "../schema/index.js";
6
+ import { AIError, mergeJsonRecords, tokenUsage } from "../schema/index.js";
7
7
  import { TranscriptionFinishEvent, TranscriptionModel, TranscriptionSegmentEvent, TranscriptionTextDeltaEvent, } from "../transcription.js";
8
8
  import { mediaTypeExtension } from "../utils/media-type.js";
9
9
  import { ProviderShared } from "./shared.js";
@@ -163,13 +163,12 @@ const usage = (value) => {
163
163
  return undefined;
164
164
  if (value.type === "duration")
165
165
  return { type: "seconds", seconds: value.seconds };
166
- return {
167
- type: "tokens",
166
+ return tokenUsage({
168
167
  input: value.input_tokens,
169
168
  output: value.output_tokens,
170
169
  total: value.total_tokens,
171
170
  details: { openai: value },
172
- };
171
+ });
173
172
  };
174
173
  const finish = (state) => {
175
174
  const transcript = state.transcript;
@@ -110,7 +110,7 @@ const decodeResult = Effect.fn("ReplicateImages.decodeResult")(function* (respon
110
110
  // ---------------------------------------------------------------------------
111
111
  export const protocol = MediaProtocol.queued(route, {
112
112
  token: Token,
113
- unsupported: ["images", "mask", "n", "size", "aspectRatio", "seed", "format"],
113
+ unsupported: ["images", "n", "aspect", "resolution"],
114
114
  start: { body: { from: fromRequest }, decode: decodeStart },
115
115
  status: { path: (token) => token.getURL, decode: decodeStatus },
116
116
  result: { path: (token) => token.getURL, decode: decodeResult },
@@ -11,7 +11,7 @@ export declare const IMAGE_TO_VIDEO_PATH = "/image_to_video";
11
11
  export declare const VIDEO_TO_VIDEO_PATH = "/video_to_video";
12
12
  export declare const TASKS_PATH = "/tasks";
13
13
  /**
14
- * Provider-native options. Common fields lower to Runway's names: `aspectRatio` → `ratio` (Runway expects pixel
14
+ * Provider-native options. Common fields lower to Runway's names: `aspect` → `ratio` (Runway expects pixel
15
15
  * ratios such as `1280:720` for most models), `durationSeconds` → `duration`, `audio`, `negativePrompt`,
16
16
  * `resolution`, `references`, and `frames` → `promptImage`.
17
17
  */
@@ -58,7 +58,7 @@ const fromRequest = Effect.fn("RunwayVideo.fromRequest")(function* (request) {
58
58
  promptImage: promptImage.length === 0 ? undefined : promptImage,
59
59
  videoUri,
60
60
  references: references.length === 0 ? undefined : references,
61
- ratio: request.aspectRatio,
61
+ ratio: request.aspect,
62
62
  duration: request.durationSeconds,
63
63
  resolution: request.resolution,
64
64
  audio: request.audio,
@@ -13,6 +13,14 @@ export declare const optionalNull: <const S extends Schema.Top>(schema: S) => Sc
13
13
  export declare const optionalNullish: <const S extends Schema.Top>(schema: S) => Schema.decodeTo<Schema.optional<Schema.toType<S>>, Schema.optional<Schema.NullOr<S>>, never, never>;
14
14
  /** Optional field whose malformed value decodes to `undefined` instead of failing the enclosing struct. */
15
15
  export declare const lenient: <const S extends Schema.Top>(schema: S) => Schema.optionalKey<Schema.middlewareDecoding<Schema.UndefinedOr<S>, S["DecodingServices"]>>;
16
+ /** Billing an endpoint reports beside its token usage: `cost` is the USD it charged (OpenRouter, LiteLLM, OpenCode Zen). */
17
+ export declare const ReportedBilling: Schema.Struct<{
18
+ readonly cost: Schema.optionalKey<Schema.middlewareDecoding<Schema.UndefinedOr<Schema.Finite>, never>>;
19
+ }>;
20
+ /** Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it. */
21
+ export declare const reportedBilling: (usage: unknown) => {} | {
22
+ cost: number | undefined;
23
+ };
16
24
  /**
17
25
  * Accepts stream frames that carry no `type`, alongside the typed event schema. Gateways inject such frames as
18
26
  * keep-alives, so they decode as an ignored event; one with an `error` still decodes as an error event.
@@ -143,7 +151,7 @@ export type MediaReference = {
143
151
  */
144
152
  export declare const mediaReference: (asset: Media.Asset, provider: ProviderID | undefined, label: string) => Effect.Effect<MediaReference, AIError>;
145
153
  /**
146
- * Lift a tool-result file into a `MediaPart`. Tool files carry either a data URL, an `http(s)` URL, or raw base64 in
154
+ * Lift a tool-result file into a `MediaPart`. Tool files carry either a data URL, a URI, or raw base64 in
147
155
  * `uri`; the declared `mime` wins over any data-URL prefix so tool authors control the type the model sees.
148
156
  */
149
157
  export declare const toolFileMedia: (item: Tool.FileContent) => MediaPart;
@@ -17,6 +17,17 @@ export const optionalNullish = (schema) => Schema.optional(Schema.NullOr(schema)
17
17
  })));
18
18
  /** Optional field whose malformed value decodes to `undefined` instead of failing the enclosing struct. */
19
19
  export const lenient = (schema) => Schema.optionalKey(Schema.UndefinedOr(schema).pipe(Schema.catchDecoding(() => Effect.succeed(Option.some(undefined)))));
20
+ /** A billed amount in USD; a malformed or negative one decodes as absent. */
21
+ const billedAmount = lenient(Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)));
22
+ /** Billing an endpoint reports beside its token usage: `cost` is the USD it charged (OpenRouter, LiteLLM, OpenCode Zen). */
23
+ export const ReportedBilling = Schema.Struct({
24
+ cost: billedAmount,
25
+ });
26
+ /** Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it. */
27
+ export const reportedBilling = (usage) => Option.match(Schema.decodeUnknownOption(ReportedBilling)(usage), {
28
+ onNone: () => ({}),
29
+ onSome: (billing) => ({ cost: billing.cost }),
30
+ });
20
31
  /**
21
32
  * Accepts stream frames that carry no `type`, alongside the typed event schema. Gateways inject such frames as
22
33
  * keep-alives, so they decode as an ignored event; one with an `error` still decodes as an error event.
@@ -175,14 +186,14 @@ export const mediaReference = (asset, provider, label) => {
175
186
  return Effect.fail(invalidRequest(`${label} accepts inline bytes, data URLs, http(s) URLs${accepted}${got}`));
176
187
  };
177
188
  /**
178
- * Lift a tool-result file into a `MediaPart`. Tool files carry either a data URL, an `http(s)` URL, or raw base64 in
189
+ * Lift a tool-result file into a `MediaPart`. Tool files carry either a data URL, a URI, or raw base64 in
179
190
  * `uri`; the declared `mime` wins over any data-URL prefix so tool authors control the type the model sees.
180
191
  */
181
192
  export const toolFileMedia = (item) => {
182
193
  const parsed = Media.parseDataUrl(item.uri);
183
194
  const asset = parsed
184
195
  ? Media.from({ ...parsed.source, mediaType: item.mime })
185
- : /^https?:\/\//.test(item.uri)
196
+ : item.uri.includes("://")
186
197
  ? Media.url(item.uri, { mediaType: item.mime })
187
198
  : Media.base64(item.uri, item.mime);
188
199
  return Message.media(asset, { filename: item.name });
@@ -5,7 +5,10 @@ import { MediaRoute } from "../route/media.js";
5
5
  import { type OpenString } from "../schema/index.js";
6
6
  export declare const DEFAULT_BASE_URL = "https://api.stability.ai";
7
7
  export type StabilityStylePreset = OpenString<"enhance" | "anime" | "photographic" | "digital-art" | "comic-book" | "fantasy-art" | "line-art" | "analog-film" | "neon-punk" | "isometric" | "low-poly" | "origami" | "modeling-compound" | "cinematic" | "3d-model" | "pixel-art" | "tile-texture">;
8
+ /** Native form fields; `aspect` lowers to `aspect_ratio`. */
8
9
  export type StabilityImageOptions = {
10
+ readonly seed?: number;
11
+ readonly output_format?: OpenString<"jpeg" | "png" | "webp">;
9
12
  readonly negative_prompt?: string;
10
13
  readonly style_preset?: StabilityStylePreset;
11
14
  readonly strength?: number;
@@ -13,6 +16,8 @@ export type StabilityImageOptions = {
13
16
  } & Record<string, unknown>;
14
17
  /** Creative upscale options; the one `images` source is the image to upscale. */
15
18
  export type StabilityUpscaleOptions = {
19
+ readonly seed?: number;
20
+ readonly output_format?: OpenString<"jpeg" | "png" | "webp">;
16
21
  readonly negative_prompt?: string;
17
22
  readonly style_preset?: StabilityStylePreset;
18
23
  readonly creativity?: number;
@@ -49,9 +49,7 @@ const fromRequest = Effect.fn("StabilityImages.fromRequest")(function* (request)
49
49
  return yield* route.unsupported("media.images", `${route.name} core is text-to-image only; use ultra or sd3.5-*`);
50
50
  return yield* form(route, {
51
51
  prompt: request.prompt,
52
- aspect_ratio: request.aspectRatio,
53
- seed: request.seed,
54
- output_format: request.format,
52
+ aspect_ratio: request.aspect,
55
53
  model: target === "sd3" ? request.model.id : undefined,
56
54
  mode: target === "sd3" && edit ? "image-to-image" : undefined,
57
55
  }, mergeJsonRecords(request.providerOptions, request.http?.body), request.images);
@@ -59,7 +57,7 @@ const fromRequest = Effect.fn("StabilityImages.fromRequest")(function* (request)
59
57
  const fromUpscaleRequest = Effect.fn("StabilityImages.fromUpscaleRequest")(function* (request) {
60
58
  if ((request.images?.length ?? 0) === 0)
61
59
  return yield* ProviderShared.invalidRequest(`${upscaleRoute.name} upscale requires the source image in images`);
62
- return yield* form(upscaleRoute, { prompt: request.prompt, seed: request.seed, output_format: request.format }, mergeJsonRecords(request.providerOptions, request.http?.body), request.images);
60
+ return yield* form(upscaleRoute, { prompt: request.prompt }, mergeJsonRecords(request.providerOptions, request.http?.body), request.images);
63
61
  });
64
62
  // ---------------------------------------------------------------------------
65
63
  // 6. Response decoding
@@ -75,9 +73,6 @@ const decodeImageDocument = (identity) => {
75
73
  const image = yield* MediaInput.decodedAsset(output.invalid, `${identity.name} result`, data, undefined);
76
74
  return new ImageResponse({
77
75
  images: [image],
78
- notices: document.finish_reason === "CONTENT_FILTERED"
79
- ? [{ type: "moderated", message: `${identity.name} blurred the image for violating its content policy` }]
80
- : undefined,
81
76
  providerMetadata: { stability: { seed: document.seed, finishReason: document.finish_reason } },
82
77
  });
83
78
  });
@@ -104,13 +99,13 @@ const decodeUpscaleResult = Effect.fn("StabilityImages.decodeUpscaleResult")(fun
104
99
  // 7. Protocol and route
105
100
  // ---------------------------------------------------------------------------
106
101
  export const protocol = MediaProtocol.inline(route, {
107
- unsupported: ["size", "mask"],
102
+ unsupported: ["resolution"],
108
103
  body: { from: fromRequest },
109
104
  response: { decode: decodeResponse },
110
105
  });
111
106
  export const upscaleProtocol = MediaProtocol.queued(upscaleRoute, {
112
107
  token: Token,
113
- unsupported: ["n", "size", "aspectRatio", "mask"],
108
+ unsupported: ["n", "aspect", "resolution"],
114
109
  start: { body: { from: fromUpscaleRequest }, decode: decodeStart },
115
110
  status: { path: (token) => `${RESULTS_PATH}/${token.id}`, decode: decodeStatus },
116
111
  result: { path: (token) => `${RESULTS_PATH}/${token.id}`, decode: decodeUpscaleResult },
@@ -0,0 +1,101 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionResponse, type DecisionModelCompatibility, type DecisionRequestFor } from "../decision.js";
3
+ import { DecisionRoute } from "../route/decision.js";
4
+ import { AIError } from "../schema/index.js";
5
+ export declare const DEFAULT_PATH = "/systemone";
6
+ export declare const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1";
7
+ /** `state.messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */
8
+ type MediaInput = NonNullable<DecisionModelCompatibility["mediaInput"]> | "state.messages";
9
+ export declare const Response: Schema.Struct<{
10
+ readonly model: Schema.String;
11
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
12
+ readonly type: Schema.Literal<"noul">;
13
+ readonly noul: Schema.Number;
14
+ }>, Schema.Struct<{
15
+ readonly type: Schema.Literal<"choice">;
16
+ readonly choice: Schema.String;
17
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
18
+ readonly confidence: Schema.Number;
19
+ }>, Schema.Struct<{
20
+ readonly type: Schema.Literal<"score">;
21
+ readonly score: Schema.Number;
22
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
23
+ readonly confidence: Schema.Number;
24
+ }>]>>;
25
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
26
+ readonly input_tokens: Schema.optional<Schema.Number>;
27
+ readonly output_tokens: Schema.optional<Schema.Number>;
28
+ readonly cost: Schema.optional<Schema.Number>;
29
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
30
+ readonly id: Schema.optional<Schema.String>;
31
+ readonly provider: Schema.optional<Schema.String>;
32
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
33
+ }>;
34
+ export type Response = Schema.Schema.Type<typeof Response>;
35
+ /** The System One body without `model`; media goes where the model's `mediaInput` says, else `fallback`. */
36
+ export declare const encodeBody: (request: DecisionRequestFor, fallback: MediaInput) => Effect.Effect<{
37
+ questions: any;
38
+ state: unknown;
39
+ assets?: undefined;
40
+ } | {
41
+ questions: any;
42
+ state: readonly unknown[];
43
+ assets: {
44
+ [k: string]: {
45
+ type: string;
46
+ format: string;
47
+ data_base64: string;
48
+ };
49
+ };
50
+ }, AIError, never>;
51
+ /** Map System One's answers, keyed by question name, back to the request's question order. */
52
+ export declare const toResponse: (data: Response, request: DecisionRequestFor, providerMetadataKey: string, invalid: (message: string) => AIError) => Effect.Effect<never, AIError, never> | Effect.Effect<DecisionResponse, never, never>;
53
+ export declare const protocol: DecisionRoute.Protocol;
54
+ /** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
55
+ export declare const route: DecisionRoute.Route;
56
+ export declare const SystemOne: {
57
+ readonly Response: Schema.Struct<{
58
+ readonly model: Schema.String;
59
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
60
+ readonly type: Schema.Literal<"noul">;
61
+ readonly noul: Schema.Number;
62
+ }>, Schema.Struct<{
63
+ readonly type: Schema.Literal<"choice">;
64
+ readonly choice: Schema.String;
65
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
66
+ readonly confidence: Schema.Number;
67
+ }>, Schema.Struct<{
68
+ readonly type: Schema.Literal<"score">;
69
+ readonly score: Schema.Number;
70
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
71
+ readonly confidence: Schema.Number;
72
+ }>]>>;
73
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
74
+ readonly input_tokens: Schema.optional<Schema.Number>;
75
+ readonly output_tokens: Schema.optional<Schema.Number>;
76
+ readonly cost: Schema.optional<Schema.Number>;
77
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
78
+ readonly id: Schema.optional<Schema.String>;
79
+ readonly provider: Schema.optional<Schema.String>;
80
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
81
+ }>;
82
+ readonly encodeBody: (request: DecisionRequestFor, fallback: MediaInput) => Effect.Effect<{
83
+ questions: any;
84
+ state: unknown;
85
+ assets?: undefined;
86
+ } | {
87
+ questions: any;
88
+ state: readonly unknown[];
89
+ assets: {
90
+ [k: string]: {
91
+ type: string;
92
+ format: string;
93
+ data_base64: string;
94
+ };
95
+ };
96
+ }, AIError, never>;
97
+ readonly toResponse: typeof toResponse;
98
+ readonly protocol: DecisionRoute.Protocol;
99
+ readonly route: DecisionRoute.Route;
100
+ };
101
+ export {};
@@ -0,0 +1,230 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionResponse, DecisionUsage, } from "../decision.js";
3
+ import { DecisionRoute } from "../route/decision.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { MediaProtocol } from "../route/media-protocol.js";
6
+ import { AIError, UnsupportedOperationError, mergeJsonRecords } from "../schema/index.js";
7
+ import { encodeJson } from "../utils/json.js";
8
+ import { JsonObject, ProviderShared } from "./shared.js";
9
+ export const DEFAULT_PATH = "/systemone";
10
+ export const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1";
11
+ const Probability = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }));
12
+ const Answer = Schema.Union([
13
+ Schema.Struct({ type: Schema.Literal("noul"), noul: Probability }),
14
+ Schema.Struct({
15
+ type: Schema.Literal("choice"),
16
+ choice: Schema.String,
17
+ probabilities: Schema.Record(Schema.String, Probability),
18
+ confidence: Probability,
19
+ }),
20
+ Schema.Struct({
21
+ type: Schema.Literal("score"),
22
+ score: Schema.Number,
23
+ probabilities: Schema.Record(Schema.String, Probability),
24
+ confidence: Probability,
25
+ }),
26
+ ]).pipe(Schema.toTaggedUnion("type"));
27
+ const NativeUsage = Schema.StructWithRest(Schema.Struct({
28
+ input_tokens: Schema.optional(Schema.Number),
29
+ output_tokens: Schema.optional(Schema.Number),
30
+ cost: Schema.optional(Schema.Number),
31
+ }), [JsonObject]);
32
+ export const Response = Schema.Struct({
33
+ model: Schema.String,
34
+ answers: Schema.Record(Schema.String, Answer),
35
+ usage: Schema.optional(NativeUsage),
36
+ id: Schema.optional(Schema.String),
37
+ provider: Schema.optional(Schema.String),
38
+ provider_metadata: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown))),
39
+ });
40
+ const ID = "system-one";
41
+ const NAME = "System One";
42
+ /** The System One body without `model`; media goes where the model's `mediaInput` says, else `fallback`. */
43
+ export const encodeBody = Effect.fn("SystemOne.encodeBody")(function* (request, fallback) {
44
+ const questions = yield* encodeQuestions(request.questions);
45
+ const placed = yield* placeMedia(request, request.model.compatibility?.mediaInput ?? fallback);
46
+ return { ...mergeJsonRecords(request.providerOptions, request.http?.body), ...placed, questions };
47
+ });
48
+ const encodeQuestions = (questions) => Effect.forEach(questions, (question) => {
49
+ if (question.type === "predicate")
50
+ return Effect.succeed([question.name, { type: "noul", instructions: question.instructions }]);
51
+ if (question.type === "score")
52
+ return Effect.succeed([
53
+ question.name,
54
+ {
55
+ type: "score",
56
+ instructions: question.instructions,
57
+ criteria: question.levels.map((level) => level.description === undefined ? level.label : `${level.label}: ${level.description}`),
58
+ },
59
+ ]);
60
+ // Options are map keys, so `true` is sent as "true" and mapped back by `choiceValue`.
61
+ const keys = question.choices.map((choice) => String(choice.value));
62
+ if (new Set(keys).size !== keys.length)
63
+ return Effect.fail(ProviderShared.invalidRequest(`System One choice options are strings; "${question.name}" has a boolean and a string with the same text`));
64
+ return Effect.succeed([
65
+ question.name,
66
+ {
67
+ type: "choice",
68
+ instructions: question.instructions,
69
+ criteria: Object.fromEntries(question.choices.map((choice) => [String(choice.value), choice.description ?? null])),
70
+ },
71
+ ]);
72
+ }).pipe(Effect.map(Object.fromEntries));
73
+ const placeMedia = Effect.fnUntraced(function* (request, mediaInput) {
74
+ const parts = request.input;
75
+ const unsupported = (asset, accepted) => new AIError({
76
+ reason: new UnsupportedOperationError({
77
+ operation: "decision.media",
78
+ provider: request.model.provider,
79
+ route: request.model.route.id,
80
+ message: `${NAME} takes ${accepted} here; got ${asset.mediaType}`,
81
+ }),
82
+ });
83
+ const media = parts.flatMap((part) => (part.type === "media" ? [part.media] : []));
84
+ if (media.length === 0)
85
+ return { state: state(parts.map(plain)) };
86
+ if (mediaInput === "state")
87
+ return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) };
88
+ // Chat-style content in one user message: text and JSON as text parts, media as in `state`.
89
+ if (mediaInput === "state.messages")
90
+ return {
91
+ state: {
92
+ messages: [
93
+ {
94
+ role: "user",
95
+ content: yield* Effect.forEach(parts, (part) => part.type === "media"
96
+ ? stateItem(part, unsupported)
97
+ : Effect.succeed({ type: "text", text: part.type === "text" ? part.text : encodeJson(part.value) })),
98
+ },
99
+ ],
100
+ },
101
+ };
102
+ if (mediaInput === "root") {
103
+ const lists = { image: "images", audio: "audio", video: "videos" };
104
+ const unplaced = media.find((asset) => !Object.hasOwn(lists, asset.kind));
105
+ if (unplaced !== undefined)
106
+ return yield* unsupported(unplaced, "images, audio and video");
107
+ const inline = yield* Effect.forEach(media, (asset) => ProviderShared.requireInlineMedia(NAME, asset));
108
+ const fields = Object.fromEntries(Object.entries(lists).flatMap(([kind, field]) => {
109
+ const items = inline.filter((_, index) => media[index].kind === kind).map((item) => item.dataUrl);
110
+ return items.length === 0 ? [] : [[field, items]];
111
+ }));
112
+ return { state: state(parts.filter((part) => part.type !== "media").map(plain)), ...fields };
113
+ }
114
+ const unplaced = media.find((asset) => asset.kind !== "image");
115
+ if (unplaced !== undefined)
116
+ return yield* unsupported(unplaced, "images");
117
+ const inline = yield* Effect.forEach(media, (asset) => ProviderShared.requireInlineMedia(NAME, asset));
118
+ // Every occurrence of a reference string in the body is replaced with its image, so it must not be ordinary text.
119
+ const reference = (index) => `<image-${index + 1}>`;
120
+ const items = parts.reduce((acc, part) => part.type === "media"
121
+ ? { next: acc.next + 1, values: [...acc.values, reference(acc.next)] }
122
+ : { next: acc.next, values: [...acc.values, plain(part)] }, { next: 0, values: [] }).values;
123
+ return {
124
+ state: items,
125
+ assets: Object.fromEntries(inline.map((item, index) => [
126
+ reference(index),
127
+ { type: "image", format: item.mime.slice("image/".length), data_base64: item.base64 },
128
+ ])),
129
+ };
130
+ });
131
+ /** A lone text or JSON part is the state itself; several are a list. */
132
+ const state = (items) => (items.length === 1 ? items[0] : items);
133
+ const plain = (part) => {
134
+ if (part.type === "text")
135
+ return part.text;
136
+ if (part.type === "json")
137
+ return part.value;
138
+ return undefined;
139
+ };
140
+ const stateItem = (part, unsupported) => {
141
+ if (part.type !== "media")
142
+ return Effect.succeed(plain(part));
143
+ const asset = part.media;
144
+ if (asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video")
145
+ return Effect.fail(unsupported(asset, "images, audio and video"));
146
+ return ProviderShared.requireInlineMedia(NAME, asset).pipe(Effect.map((inline) => {
147
+ if (asset.kind === "image")
148
+ return { type: "image_url", image_url: { url: inline.dataUrl } };
149
+ if (asset.kind === "video")
150
+ return { type: "video_url", video_url: { url: inline.dataUrl } };
151
+ return { type: "input_audio", input_audio: { data: inline.base64, format: inline.mime.slice("audio/".length) } };
152
+ }));
153
+ };
154
+ /** Map System One's answers, keyed by question name, back to the request's question order. */
155
+ export const toResponse = (data, request, providerMetadataKey, invalid) => {
156
+ const names = request.questions.map((question) => question.name);
157
+ if (Object.keys(data.answers).length !== names.length || !names.every((name) => Object.hasOwn(data.answers, name)))
158
+ return Effect.fail(invalid("System One answers do not match the requested questions"));
159
+ return Effect.succeed(new DecisionResponse({
160
+ answers: request.questions.map((question) => toAnswer(question, data.answers[question.name])),
161
+ usage: data.usage === undefined
162
+ ? undefined
163
+ : new DecisionUsage({
164
+ inputTokens: data.usage.input_tokens,
165
+ outputTokens: data.usage.output_tokens,
166
+ totalTokens: ProviderShared.totalTokens(data.usage.input_tokens, data.usage.output_tokens, undefined),
167
+ cost: data.usage.cost,
168
+ }),
169
+ providerMetadata: {
170
+ [providerMetadataKey]: {
171
+ model: data.model,
172
+ ...(data.usage === undefined ? {} : { usage: data.usage }),
173
+ ...(data.id === undefined ? {} : { responseId: data.id }),
174
+ ...(data.provider === undefined ? {} : { provider: data.provider }),
175
+ ...data.provider_metadata?.[providerMetadataKey],
176
+ },
177
+ },
178
+ }));
179
+ };
180
+ const toAnswer = (question, answer) => {
181
+ if (answer.type === "noul")
182
+ return { name: question.name, type: "predicate", probability: answer.noul };
183
+ if (answer.type === "choice") {
184
+ const choices = question.type === "choice" ? question.choices : [];
185
+ const value = (key) => choices.find((choice) => String(choice.value) === key)?.value ?? key;
186
+ const rank = (key) => {
187
+ const index = choices.findIndex((choice) => String(choice.value) === key);
188
+ return index === -1 ? choices.length : index;
189
+ };
190
+ return {
191
+ name: question.name,
192
+ type: "choice",
193
+ choice: value(answer.choice),
194
+ probabilities: Object.entries(answer.probabilities)
195
+ .toSorted(([a], [b]) => rank(a) - rank(b))
196
+ .map(([key, probability]) => ({ value: value(key), probability })),
197
+ confidence: answer.confidence,
198
+ };
199
+ }
200
+ const levels = question.type === "score" ? question.levels : [];
201
+ return {
202
+ name: question.name,
203
+ type: "score",
204
+ score: answer.score,
205
+ probabilities: Object.entries(answer.probabilities)
206
+ .map(([key, probability]) => ({ value: Number(key), label: levels[Number(key)]?.label ?? key, probability }))
207
+ .toSorted((a, b) => a.value - b.value),
208
+ confidence: answer.confidence,
209
+ };
210
+ };
211
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "typesafe-ai" }).decodeJson(Response);
212
+ export const protocol = DecisionRoute.protocol({
213
+ id: ID,
214
+ name: NAME,
215
+ inlineMedia: true,
216
+ body: {
217
+ from: (request) => encodeBody(request, "assets").pipe(Effect.map((body) => ({ ...body, model: request.model.id }))),
218
+ },
219
+ response: {
220
+ decode: (response, context) => decodeDocument(response).pipe(Effect.flatMap((output) => toResponse(output.value, context.request, context.providerMetadataKey, output.invalid))),
221
+ },
222
+ });
223
+ /** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
224
+ export const route = DecisionRoute.make({
225
+ id: ID,
226
+ provider: "typesafe-ai",
227
+ protocol,
228
+ endpoint: Endpoint.path("/systemone", { baseURL: DEFAULT_BASE_URL }),
229
+ });
230
+ export const SystemOne = { Response, encodeBody, toResponse, protocol, route };
@@ -1,9 +1,9 @@
1
1
  import { Schema } from "effect";
2
- import type { CacheHint, LLMRequest } from "../../schema/index.js";
2
+ import { type CacheHint, type LLMRequest } from "../../schema/index.js";
3
3
  export declare const CachePointBlock: Schema.Struct<{
4
4
  readonly cachePoint: Schema.Struct<{
5
5
  readonly type: Schema.tag<"default">;
6
- readonly ttl: Schema.optional<Schema.Literals<readonly ["5m", "1h"]>>;
6
+ readonly ttl: Schema.optional<Schema.TemplateLiteral<readonly [Schema.Number, Schema.Literals<readonly ["ms", "s", "m", "h", "d"]>]>>;
7
7
  }>;
8
8
  }>;
9
9
  export type CachePointBlock = Schema.Schema.Type<typeof CachePointBlock>;
@@ -1,12 +1,13 @@
1
1
  import { Schema } from "effect";
2
- import { newBreakpoints, ttlBucket } from "./cache.js";
2
+ import { CacheTTL } from "../../schema/index.js";
3
+ import { newBreakpoints } from "./cache.js";
3
4
  // Bedrock cache markers are positional: emit a `cachePoint` block immediately
4
5
  // after the content the caller wants treated as a cacheable prefix. Bedrock
5
- // accepts optional `ttl: "5m" | "1h"` on cachePoint.
6
+ // accepts an optional `ttl` such as "5m" or "1h" on cachePoint.
6
7
  export const CachePointBlock = Schema.Struct({
7
8
  cachePoint: Schema.Struct({
8
9
  type: Schema.tag("default"),
9
- ttl: Schema.optional(Schema.Literals(["5m", "1h"])),
10
+ ttl: Schema.optional(CacheTTL),
10
11
  }),
11
12
  });
12
13
  const LEGACY_CLAUDE = ["anthropic.claude-instant", "anthropic.claude-v1", "anthropic.claude-v2", "anthropic.claude-3-"];
@@ -34,8 +35,6 @@ export const breakpoints = (model) => {
34
35
  ttl1h: !short,
35
36
  };
36
37
  };
37
- const DEFAULT_5M = { cachePoint: { type: "default" } };
38
- const DEFAULT_1H = { cachePoint: { type: "default", ttl: "1h" } };
39
38
  export const block = (breakpoints, cache) => {
40
39
  if (!breakpoints.supported)
41
40
  return undefined;
@@ -46,6 +45,8 @@ export const block = (breakpoints, cache) => {
46
45
  return undefined;
47
46
  }
48
47
  breakpoints.remaining -= 1;
49
- return breakpoints.ttl1h && ttlBucket(cache.ttlSeconds) === "1h" ? DEFAULT_1H : DEFAULT_5M;
48
+ // Older Claude releases cache for five minutes only, so a one-hour request falls back to the default.
49
+ const ttl = cache.ttl === "1h" && !breakpoints.ttl1h ? undefined : cache.ttl;
50
+ return { cachePoint: { type: "default", ...(ttl === undefined ? {} : { ttl }) } };
50
51
  };
51
52
  export * as BedrockCache from "./bedrock-cache.js";