@opencode/ai 2.2.5 → 2.2.7

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 (306) hide show
  1. package/README.md +228 -72
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/cache-policy.d.ts +1 -1
  5. package/dist/cache-policy.js +16 -4
  6. package/dist/decision-client.d.ts +3 -3
  7. package/dist/decision.d.ts +30 -125
  8. package/dist/decision.js +27 -15
  9. package/dist/effect.d.ts +10 -15
  10. package/dist/effect.js +6 -6
  11. package/dist/effort-updates.d.ts +3 -3
  12. package/dist/effort-updates.js +2 -2
  13. package/dist/embedding-client.d.ts +21 -0
  14. package/dist/embedding-client.js +30 -0
  15. package/dist/embedding.d.ts +111 -0
  16. package/dist/embedding.js +75 -0
  17. package/dist/experimental/cloudflare-run-extraction.d.ts +7 -3
  18. package/dist/experimental/cloudflare-run-extraction.js +4 -1
  19. package/dist/experimental/extraction.d.ts +10 -40
  20. package/dist/experimental/extraction.js +14 -13
  21. package/dist/experimental.d.ts +8 -8
  22. package/dist/experimental.js +4 -4
  23. package/dist/generation.d.ts +0 -2
  24. package/dist/generation.js +2 -2
  25. package/dist/image-client.d.ts +13 -7
  26. package/dist/image-client.js +1 -1
  27. package/dist/image.d.ts +357 -465
  28. package/dist/image.js +17 -18
  29. package/dist/index.d.ts +35 -467
  30. package/dist/index.js +23 -17
  31. package/dist/llm.d.ts +65 -266
  32. package/dist/llm.js +101 -92
  33. package/dist/loop.d.ts +38 -0
  34. package/dist/loop.js +136 -0
  35. package/dist/media-model.d.ts +1 -1
  36. package/dist/media-model.js +8 -6
  37. package/dist/media.d.ts +9 -0
  38. package/dist/media.js +37 -2
  39. package/dist/protocols/alibaba-chat.d.ts +9 -1
  40. package/dist/protocols/alibaba-chat.js +3 -3
  41. package/dist/protocols/alibaba-images.d.ts +2 -2
  42. package/dist/protocols/alibaba-messages.js +3 -3
  43. package/dist/protocols/alibaba-responses.js +8 -20
  44. package/dist/protocols/anthropic-messages.d.ts +1 -1
  45. package/dist/protocols/anthropic-messages.js +57 -176
  46. package/dist/protocols/assemblyai-transcription.d.ts +2 -2
  47. package/dist/protocols/bedrock-converse.js +10 -16
  48. package/dist/protocols/cartesia-speech.d.ts +2 -2
  49. package/dist/protocols/cloudflare-workers-ai-images.d.ts +2 -2
  50. package/dist/protocols/cohere-chat.js +9 -12
  51. package/dist/protocols/deepgram-speech.d.ts +2 -2
  52. package/dist/protocols/deepgram-transcription.d.ts +2 -2
  53. package/dist/protocols/elevenlabs-speech.d.ts +2 -2
  54. package/dist/protocols/elevenlabs-transcription.d.ts +2 -2
  55. package/dist/protocols/gemini.d.ts +3 -0
  56. package/dist/protocols/gemini.js +54 -72
  57. package/dist/protocols/google-embed-content.d.ts +34 -0
  58. package/dist/protocols/google-embed-content.js +110 -0
  59. package/dist/protocols/google-images.d.ts +2 -2
  60. package/dist/protocols/google-interactions.d.ts +3 -4
  61. package/dist/protocols/google-interactions.js +44 -30
  62. package/dist/protocols/google-speech.d.ts +2 -2
  63. package/dist/protocols/google-transcription.d.ts +2 -2
  64. package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
  65. package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
  66. package/dist/protocols/google-video.d.ts +2 -2
  67. package/dist/protocols/index.d.ts +3 -0
  68. package/dist/protocols/index.js +3 -0
  69. package/dist/protocols/meta-images.d.ts +2 -2
  70. package/dist/protocols/meta-responses.js +26 -23
  71. package/dist/protocols/minimax-images.d.ts +2 -2
  72. package/dist/protocols/mistral-chat.js +7 -10
  73. package/dist/protocols/open-responses-channel.js +6 -19
  74. package/dist/protocols/open-responses-continuation.d.ts +1 -5
  75. package/dist/protocols/open-responses-continuation.js +1 -3
  76. package/dist/protocols/open-responses.d.ts +2 -22
  77. package/dist/protocols/open-responses.js +41 -23
  78. package/dist/protocols/openai-chat.d.ts +27 -23
  79. package/dist/protocols/openai-chat.js +62 -57
  80. package/dist/protocols/openai-compatible-chat.d.ts +2 -1
  81. package/dist/protocols/openai-compatible-responses.d.ts +2 -2
  82. package/dist/protocols/openai-compatible-responses.js +1 -1
  83. package/dist/protocols/openai-decisions.js +15 -2
  84. package/dist/protocols/openai-embeddings.d.ts +16 -0
  85. package/dist/protocols/openai-embeddings.js +76 -0
  86. package/dist/protocols/openai-images.d.ts +2 -2
  87. package/dist/protocols/openai-responses.js +10 -29
  88. package/dist/protocols/openai-speech.d.ts +2 -2
  89. package/dist/protocols/openai-transcription.d.ts +2 -2
  90. package/dist/protocols/runway-video.d.ts +2 -2
  91. package/dist/protocols/shared.d.ts +14 -7
  92. package/dist/protocols/shared.js +40 -15
  93. package/dist/protocols/system-one.d.ts +4 -4
  94. package/dist/protocols/system-one.js +8 -1
  95. package/dist/protocols/utils/bedrock-cache.js +2 -5
  96. package/dist/protocols/utils/bedrock-media.d.ts +0 -3
  97. package/dist/protocols/utils/cache.d.ts +3 -0
  98. package/dist/protocols/utils/cache.js +15 -2
  99. package/dist/protocols/utils/image-sizing.d.ts +1 -1
  100. package/dist/protocols/utils/responses-checkpoint.js +1 -1
  101. package/dist/protocols/utils/responses-compaction.d.ts +1 -1
  102. package/dist/protocols/utils/responses-compaction.js +6 -5
  103. package/dist/protocols/utils/responses-hosted-tools.d.ts +97 -1
  104. package/dist/protocols/utils/responses-hosted-tools.js +31 -0
  105. package/dist/protocols/utils/tool-stream.d.ts +5 -271
  106. package/dist/protocols/utils/tool-stream.js +3 -13
  107. package/dist/protocols/venice-chat.d.ts +7 -1
  108. package/dist/protocols/venice-chat.js +4 -4
  109. package/dist/protocols/xai-images.d.ts +2 -2
  110. package/dist/protocols/xai-responses.js +5 -25
  111. package/dist/protocols/xai-video.d.ts +2 -2
  112. package/dist/protocols/zai-chat.d.ts +9 -1
  113. package/dist/protocols/zai-chat.js +1 -1
  114. package/dist/protocols/zai-images.d.ts +2 -2
  115. package/dist/protocols/zai-messages.js +3 -3
  116. package/dist/provider-error.d.ts +0 -1
  117. package/dist/provider-error.js +7 -80
  118. package/dist/providers/alibaba/embeddings.d.ts +2 -0
  119. package/dist/providers/alibaba/embeddings.js +1 -0
  120. package/dist/providers/alibaba.d.ts +70 -4
  121. package/dist/providers/alibaba.js +20 -2
  122. package/dist/providers/amazon-bedrock-mantle.d.ts +7 -3
  123. package/dist/providers/amazon-bedrock-mantle.js +6 -3
  124. package/dist/providers/amazon-bedrock.d.ts +6 -7
  125. package/dist/providers/amazon-bedrock.js +1 -1
  126. package/dist/providers/anthropic-compatible.d.ts +7 -8
  127. package/dist/providers/anthropic-compatible.js +2 -5
  128. package/dist/providers/anthropic.d.ts +8 -9
  129. package/dist/providers/anthropic.js +2 -7
  130. package/dist/providers/assemblyai.d.ts +2 -2
  131. package/dist/providers/assemblyai.js +2 -7
  132. package/dist/providers/azure/embeddings.d.ts +2 -0
  133. package/dist/providers/azure/embeddings.js +1 -0
  134. package/dist/providers/azure/messages.d.ts +2 -0
  135. package/dist/providers/azure/messages.js +1 -0
  136. package/dist/providers/azure.d.ts +325 -7
  137. package/dist/providers/azure.js +40 -9
  138. package/dist/providers/baseten.d.ts +7 -5
  139. package/dist/providers/baseten.js +7 -21
  140. package/dist/providers/cartesia.d.ts +1 -1
  141. package/dist/providers/cerebras.d.ts +7 -5
  142. package/dist/providers/cerebras.js +4 -15
  143. package/dist/providers/cloudflare-ai-gateway.d.ts +23 -13
  144. package/dist/providers/cloudflare-ai-gateway.js +28 -40
  145. package/dist/providers/cloudflare-shared.d.ts +9 -0
  146. package/dist/providers/cloudflare-shared.js +25 -0
  147. package/dist/providers/cloudflare-workers-ai.d.ts +6 -4
  148. package/dist/providers/cloudflare-workers-ai.js +4 -20
  149. package/dist/providers/cohere/chat.js +2 -7
  150. package/dist/providers/cohere/embeddings.d.ts +2 -0
  151. package/dist/providers/cohere/embeddings.js +1 -0
  152. package/dist/providers/cohere.d.ts +14 -5
  153. package/dist/providers/cohere.js +23 -13
  154. package/dist/providers/deepgram.d.ts +2 -2
  155. package/dist/providers/deepgram.js +2 -7
  156. package/dist/providers/deepinfra/embeddings.d.ts +2 -0
  157. package/dist/providers/deepinfra/embeddings.js +1 -0
  158. package/dist/providers/deepinfra.d.ts +10 -5
  159. package/dist/providers/deepinfra.js +20 -14
  160. package/dist/providers/deepseek.d.ts +7 -5
  161. package/dist/providers/deepseek.js +3 -14
  162. package/dist/providers/digitalocean/embeddings.d.ts +2 -0
  163. package/dist/providers/digitalocean/embeddings.js +1 -0
  164. package/dist/providers/digitalocean.d.ts +18 -5
  165. package/dist/providers/digitalocean.js +28 -14
  166. package/dist/providers/elevenlabs.d.ts +2 -2
  167. package/dist/providers/elevenlabs.js +2 -7
  168. package/dist/providers/fireworks/embeddings.d.ts +2 -0
  169. package/dist/providers/fireworks/embeddings.js +1 -0
  170. package/dist/providers/fireworks.d.ts +10 -5
  171. package/dist/providers/fireworks.js +17 -14
  172. package/dist/providers/google/embeddings.d.ts +2 -0
  173. package/dist/providers/google/embeddings.js +1 -0
  174. package/dist/providers/google/interactions.d.ts +1 -1
  175. package/dist/providers/google/interactions.js +2 -7
  176. package/dist/providers/google-vertex/embeddings.d.ts +2 -0
  177. package/dist/providers/google-vertex/embeddings.js +1 -0
  178. package/dist/providers/google-vertex-chat.d.ts +4 -3
  179. package/dist/providers/google-vertex-chat.js +3 -29
  180. package/dist/providers/google-vertex-interactions.d.ts +3 -3
  181. package/dist/providers/google-vertex-messages.d.ts +3 -3
  182. package/dist/providers/google-vertex-messages.js +3 -29
  183. package/dist/providers/google-vertex-mistral.d.ts +3 -3
  184. package/dist/providers/google-vertex-mistral.js +3 -29
  185. package/dist/providers/google-vertex-responses.d.ts +3 -3
  186. package/dist/providers/google-vertex-responses.js +4 -30
  187. package/dist/providers/google-vertex-shared.d.ts +31 -0
  188. package/dist/providers/google-vertex-shared.js +25 -0
  189. package/dist/providers/google-vertex.d.ts +10 -3
  190. package/dist/providers/google-vertex.js +52 -0
  191. package/dist/providers/google.d.ts +21 -13
  192. package/dist/providers/google.js +23 -19
  193. package/dist/providers/groq.d.ts +10 -5
  194. package/dist/providers/groq.js +4 -15
  195. package/dist/providers/meta.d.ts +6 -5
  196. package/dist/providers/meta.js +10 -23
  197. package/dist/providers/minimax/chat.js +2 -7
  198. package/dist/providers/minimax/responses.js +2 -7
  199. package/dist/providers/minimax.d.ts +6 -5
  200. package/dist/providers/minimax.js +7 -22
  201. package/dist/providers/mistral.d.ts +10 -11
  202. package/dist/providers/mistral.js +3 -14
  203. package/dist/providers/moonshot/messages.js +2 -7
  204. package/dist/providers/moonshot/responses.js +2 -7
  205. package/dist/providers/moonshot.d.ts +6 -5
  206. package/dist/providers/moonshot.js +4 -16
  207. package/dist/providers/openai/embeddings.d.ts +2 -0
  208. package/dist/providers/openai/embeddings.js +1 -0
  209. package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
  210. package/dist/providers/openai-compatible/embeddings.js +1 -0
  211. package/dist/providers/openai-compatible-responses.d.ts +6 -7
  212. package/dist/providers/openai-compatible-responses.js +2 -8
  213. package/dist/providers/openai-compatible.d.ts +10 -7
  214. package/dist/providers/openai-compatible.js +17 -10
  215. package/dist/providers/openai.d.ts +11 -4
  216. package/dist/providers/openai.js +17 -3
  217. package/dist/providers/opencode.d.ts +4 -4
  218. package/dist/providers/opencode.js +6 -2
  219. package/dist/providers/openrouter/embeddings.d.ts +2 -0
  220. package/dist/providers/openrouter/embeddings.js +1 -0
  221. package/dist/providers/openrouter.d.ts +24 -5
  222. package/dist/providers/openrouter.js +31 -24
  223. package/dist/providers/runway.d.ts +1 -1
  224. package/dist/providers/settings.d.ts +40 -0
  225. package/dist/providers/settings.js +19 -0
  226. package/dist/providers/togetherai.d.ts +7 -5
  227. package/dist/providers/togetherai.js +5 -15
  228. package/dist/providers/typesafe-ai.d.ts +4 -4
  229. package/dist/providers/typesafe-ai.js +6 -2
  230. package/dist/providers/venice.d.ts +5 -4
  231. package/dist/providers/venice.js +6 -2
  232. package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
  233. package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
  234. package/dist/providers/vercel-ai-gateway.d.ts +9 -5
  235. package/dist/providers/vercel-ai-gateway.js +30 -29
  236. package/dist/providers/xai.d.ts +5 -4
  237. package/dist/providers/xai.js +4 -12
  238. package/dist/providers/zai-coding-plan/messages.js +2 -7
  239. package/dist/providers/zai-coding-plan/responses.js +2 -7
  240. package/dist/providers/zai-coding-plan.d.ts +6 -5
  241. package/dist/providers/zai-coding-plan.js +8 -15
  242. package/dist/providers/zai.d.ts +6 -5
  243. package/dist/providers/zai.js +10 -22
  244. package/dist/public.d.ts +14 -0
  245. package/dist/public.js +6 -0
  246. package/dist/route/auth-options.d.ts +9 -5
  247. package/dist/route/auth-options.js +10 -7
  248. package/dist/route/client.d.ts +50 -37
  249. package/dist/route/client.js +42 -53
  250. package/dist/route/decision.d.ts +8 -8
  251. package/dist/route/decision.js +3 -3
  252. package/dist/route/embedding.d.ts +61 -0
  253. package/dist/route/embedding.js +88 -0
  254. package/dist/route/executor.d.ts +5 -0
  255. package/dist/route/executor.js +10 -0
  256. package/dist/route/index.d.ts +5 -7
  257. package/dist/route/index.js +1 -1
  258. package/dist/route/media.d.ts +7 -11
  259. package/dist/route/media.js +22 -26
  260. package/dist/route/transport/http.js +6 -5
  261. package/dist/route/transport/websocket.js +7 -1
  262. package/dist/schema/errors.d.ts +16 -17
  263. package/dist/schema/errors.js +63 -12
  264. package/dist/schema/events.d.ts +2563 -2954
  265. package/dist/schema/events.js +54 -109
  266. package/dist/schema/messages.d.ts +194 -137
  267. package/dist/schema/messages.js +66 -83
  268. package/dist/schema/options.d.ts +112 -65
  269. package/dist/schema/options.js +52 -101
  270. package/dist/speech-client.d.ts +7 -7
  271. package/dist/speech.d.ts +306 -316
  272. package/dist/speech.js +16 -14
  273. package/dist/testing.d.ts +31 -175
  274. package/dist/testing.js +60 -5
  275. package/dist/tool-history.d.ts +1 -1
  276. package/dist/tool-history.js +3 -10
  277. package/dist/tool-runtime.d.ts +9 -2
  278. package/dist/tool-runtime.js +17 -31
  279. package/dist/tool.d.ts +39 -43
  280. package/dist/tool.js +16 -26
  281. package/dist/transcription-client.d.ts +7 -7
  282. package/dist/transcription.d.ts +314 -265
  283. package/dist/transcription.js +16 -14
  284. package/dist/utils/provider-codes.d.ts +3 -0
  285. package/dist/utils/provider-codes.js +41 -0
  286. package/dist/video-client.d.ts +7 -7
  287. package/dist/video-client.js +1 -1
  288. package/dist/video.d.ts +269 -287
  289. package/dist/video.js +16 -14
  290. package/package.json +309 -257
  291. package/dist/experimental/testing.d.ts +0 -3
  292. package/dist/experimental/testing.js +0 -3
  293. package/dist/testing/decision.d.ts +0 -16
  294. package/dist/testing/decision.js +0 -20
  295. package/dist/testing/image.d.ts +0 -14
  296. package/dist/testing/image.js +0 -12
  297. package/dist/testing/media.d.ts +0 -18
  298. package/dist/testing/media.js +0 -36
  299. package/dist/testing/script.d.ts +0 -28
  300. package/dist/testing/script.js +0 -60
  301. package/dist/testing/speech.d.ts +0 -14
  302. package/dist/testing/speech.js +0 -12
  303. package/dist/testing/transcription.d.ts +0 -14
  304. package/dist/testing/transcription.js +0 -12
  305. package/dist/testing/video.d.ts +0 -14
  306. package/dist/testing/video.js +0 -12
@@ -1,7 +1,7 @@
1
1
  import { MediaProtocol } from "../route/media-protocol.js";
2
2
  import { MediaRoute } from "../route/media.js";
3
3
  import { type OpenString } from "../schema/index.js";
4
- import { TranscriptionModel, type TranscriptionRequestFor, type TranscriptionSegment, type TranscriptionWord } from "../transcription.js";
4
+ import { TranscriptionModel, type TranscriptionRequest, type TranscriptionSegment, type TranscriptionWord } from "../transcription.js";
5
5
  import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
6
6
  export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
7
7
  /**
@@ -15,7 +15,7 @@ export type GoogleTranscriptionOptions = {
15
15
  readonly languageCodes?: ReadonlyArray<string>;
16
16
  };
17
17
  } & Record<string, unknown>;
18
- export type Request = TranscriptionRequestFor<GoogleTranscriptionOptions>;
18
+ export type Request = TranscriptionRequest<TranscriptionModel<GoogleTranscriptionOptions>>;
19
19
  interface State extends GeminiGenerateContent.Metadata {
20
20
  readonly text: string;
21
21
  readonly segments: Array<TranscriptionSegment>;
@@ -0,0 +1,18 @@
1
+ import { EmbeddingRoute } from "../route/embedding.js";
2
+ import type { TaskType } from "./google-embed-content.js";
3
+ /** `text-embedding-005` and `text-multilingual-embedding-002` take up to 250 instances per request. */
4
+ export declare const MAX_INSTANCES = 250;
5
+ /**
6
+ * The same option names as `embedContent`, so a model can move between the two APIs: `taskType` and `title` go on
7
+ * each instance (`task_type`, `title`), and `autoTruncate` and anything else go under `parameters`.
8
+ */
9
+ export interface OptionsInput {
10
+ readonly [key: string]: unknown;
11
+ readonly taskType?: TaskType;
12
+ readonly title?: string;
13
+ readonly autoTruncate?: boolean;
14
+ }
15
+ export declare const protocol: EmbeddingRoute.Protocol;
16
+ export declare const GoogleVertexPredictEmbeddings: {
17
+ readonly protocol: EmbeddingRoute.Protocol;
18
+ };
@@ -0,0 +1,74 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { EmbeddingResponse, EmbeddingUsage } from "../embedding.js";
3
+ import { EmbeddingRoute } from "../route/embedding.js";
4
+ import { MediaProtocol } from "../route/media-protocol.js";
5
+ import { AIError, UnsupportedOperationError, mergeJsonRecords } from "../schema/index.js";
6
+ const ID = "google-vertex-predict-embeddings";
7
+ const NAME = "Google Vertex text embeddings";
8
+ /** `text-embedding-005` and `text-multilingual-embedding-002` take up to 250 instances per request. */
9
+ export const MAX_INSTANCES = 250;
10
+ const Statistics = Schema.StructWithRest(Schema.Struct({ token_count: Schema.optional(Schema.Number), truncated: Schema.optional(Schema.Boolean) }), [Schema.Record(Schema.String, Schema.Unknown)]);
11
+ const Response = Schema.Struct({
12
+ predictions: Schema.Array(Schema.Struct({
13
+ embeddings: Schema.Struct({ values: Schema.Array(Schema.Number), statistics: Schema.optional(Statistics) }),
14
+ })),
15
+ metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
16
+ });
17
+ const TASK_TYPES = { query: "RETRIEVAL_QUERY", document: "RETRIEVAL_DOCUMENT" };
18
+ const fromRequest = Effect.fn("GoogleVertexPredictEmbeddings.fromRequest")(function* (request) {
19
+ const contents = request.values.filter((value) => typeof value === "string");
20
+ if (contents.length !== request.values.length)
21
+ return yield* new AIError({
22
+ reason: new UnsupportedOperationError({
23
+ operation: "embedding.media",
24
+ provider: request.model.provider,
25
+ route: request.model.route.id,
26
+ message: `${request.model.id} on Vertex :predict embeds text only; use gemini-embedding-2 for media values`,
27
+ }),
28
+ });
29
+ const { taskType, title, ...parameters } = request.providerOptions ?? {};
30
+ const instance = {
31
+ ...(taskType === undefined
32
+ ? request.inputType === undefined
33
+ ? {}
34
+ : { task_type: TASK_TYPES[request.inputType] }
35
+ : { task_type: taskType }),
36
+ ...(title === undefined ? {} : { title }),
37
+ };
38
+ const merged = {
39
+ ...(request.dimensions === undefined ? {} : { outputDimensionality: request.dimensions }),
40
+ ...parameters,
41
+ };
42
+ return (mergeJsonRecords({
43
+ instances: contents.map((content) => ({ content, ...instance })),
44
+ ...(Object.keys(merged).length === 0 ? {} : { parameters: merged }),
45
+ }, request.http?.body) ?? {});
46
+ });
47
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "google-vertex" }).decodeJson(Response);
48
+ export const protocol = EmbeddingRoute.protocol({
49
+ id: ID,
50
+ name: NAME,
51
+ body: { from: fromRequest },
52
+ response: {
53
+ decode: Effect.fn("GoogleVertexPredictEmbeddings.decodeResponse")(function* (response, context) {
54
+ const output = yield* decodeDocument(response);
55
+ const statistics = output.value.predictions.map((prediction) => prediction.embeddings.statistics ?? {});
56
+ const tokens = statistics.map((item) => item.token_count);
57
+ return new EmbeddingResponse({
58
+ embeddings: output.value.predictions.map((prediction) => prediction.embeddings.values),
59
+ usage: tokens.every((count) => count !== undefined)
60
+ ? new EmbeddingUsage({ inputTokens: tokens.reduce((sum, count) => sum + count, 0) })
61
+ : undefined,
62
+ providerMetadata: {
63
+ [context.providerMetadataKey]: {
64
+ statistics,
65
+ ...(output.value.metadata === undefined ? {} : { metadata: output.value.metadata }),
66
+ },
67
+ },
68
+ });
69
+ }),
70
+ },
71
+ });
72
+ export const GoogleVertexPredictEmbeddings = {
73
+ protocol,
74
+ };
@@ -2,13 +2,13 @@ import { Schema } from "effect";
2
2
  import { MediaProtocol } from "../route/media-protocol.js";
3
3
  import { MediaRoute } from "../route/media.js";
4
4
  import { type OpenString } from "../schema/index.js";
5
- import { VideoModel, VideoResponse, type VideoRequestFor } from "../video.js";
5
+ import { VideoModel, VideoResponse, type VideoRequest } from "../video.js";
6
6
  export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
7
7
  /** Provider-native `parameters`. Common fields (`aspect`, `resolution`, `durationSeconds`, `seed`) live on the request. */
8
8
  export type GoogleVideoOptions = {
9
9
  readonly personGeneration?: OpenString<"allow_all" | "allow_adult" | "dont_allow">;
10
10
  } & Record<string, unknown>;
11
- export type Request = VideoRequestFor<GoogleVideoOptions>;
11
+ export type Request = VideoRequest<VideoModel<GoogleVideoOptions>>;
12
12
  /** The long-running operation name, e.g. `models/veo-3.1-generate-preview/operations/abc123`. */
13
13
  export declare const Token: Schema.Struct<{
14
14
  readonly operation: Schema.String;
@@ -3,10 +3,13 @@ export * as BedrockConverse from "./bedrock-converse.js";
3
3
  export * as CloudflareRunDecisions from "./cloudflare-run-decisions.js";
4
4
  export * as CohereChat from "./cohere-chat.js";
5
5
  export * as Gemini from "./gemini.js";
6
+ export * as GoogleEmbedContent from "./google-embed-content.js";
6
7
  export * as GoogleInteractions from "./google-interactions.js";
8
+ export * as GoogleVertexPredictEmbeddings from "./google-vertex-predict-embeddings.js";
7
9
  export * as MistralChat from "./mistral-chat.js";
8
10
  export * as OpenAIChat from "./openai-chat.js";
9
11
  export * as OpenAIDecisions from "./openai-decisions.js";
12
+ export * as OpenAIEmbeddings from "./openai-embeddings.js";
10
13
  export * as OpenAIImages from "./openai-images.js";
11
14
  export * as OpenAICompatibleChat from "./openai-compatible-chat.js";
12
15
  export * as OpenAICompatibleResponses from "./openai-compatible-responses.js";
@@ -3,10 +3,13 @@ export * as BedrockConverse from "./bedrock-converse.js";
3
3
  export * as CloudflareRunDecisions from "./cloudflare-run-decisions.js";
4
4
  export * as CohereChat from "./cohere-chat.js";
5
5
  export * as Gemini from "./gemini.js";
6
+ export * as GoogleEmbedContent from "./google-embed-content.js";
6
7
  export * as GoogleInteractions from "./google-interactions.js";
8
+ export * as GoogleVertexPredictEmbeddings from "./google-vertex-predict-embeddings.js";
7
9
  export * as MistralChat from "./mistral-chat.js";
8
10
  export * as OpenAIChat from "./openai-chat.js";
9
11
  export * as OpenAIDecisions from "./openai-decisions.js";
12
+ export * as OpenAIEmbeddings from "./openai-embeddings.js";
10
13
  export * as OpenAIImages from "./openai-images.js";
11
14
  export * as OpenAICompatibleChat from "./openai-compatible-chat.js";
12
15
  export * as OpenAICompatibleResponses from "./openai-compatible-responses.js";
@@ -1,4 +1,4 @@
1
- import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
1
+ import { ImageModel, ImageResponse, type ImageRequest } from "../image.js";
2
2
  import { MediaProtocol } from "../route/media-protocol.js";
3
3
  import { MediaRoute } from "../route/media.js";
4
4
  import { type OpenString } from "../schema/index.js";
@@ -20,7 +20,7 @@ export type ImageOptions = {
20
20
  };
21
21
  readonly [key: string]: unknown;
22
22
  };
23
- export type Request = ImageRequestFor<ImageOptions>;
23
+ export type Request = ImageRequest<ImageModel<ImageOptions>>;
24
24
  export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
25
25
  export declare const model: (input: MediaRoute.ModelInput) => ImageModel<ImageOptions>;
26
26
  export * as MetaImages from "./meta-images.js";
@@ -1,7 +1,7 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { Base64 } from "effect/encoding";
3
3
  import { Protocol } from "../route/protocol.js";
4
- import { LLMEvent, LLMRequest, Message, ToolResultPart } from "../schema/index.js";
4
+ import { AssistantMessage, LLMEvent, ToolResultPart } from "../schema/index.js";
5
5
  import { OpenResponses } from "./open-responses.js";
6
6
  import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js";
7
7
  import { ResponsesHostedTools } from "./utils/responses-hosted-tools.js";
@@ -48,27 +48,30 @@ const adapter = {
48
48
  };
49
49
  const fromRequest = Effect.fn("MetaResponses.fromRequest")(function* (request) {
50
50
  const key = request.model.route.providerMetadataKey ?? String(request.model.provider);
51
- const body = yield* OpenResponses.fromRequestWithAdapter(LLMRequest.update(request, {
52
- messages: request.messages.map((message) => Message.make({
53
- ...message,
54
- content: message.content.map((part) => {
55
- if (part.type !== "tool-result" ||
56
- !part.providerExecuted ||
57
- part.name !== "image_generation" ||
58
- part.result.type !== "content" ||
59
- part.providerMetadata?.[key]?.itemId !== part.id)
60
- return part;
61
- // Meta's signed image ID carries edit state; replay the handle, not the image bytes as a user message.
62
- return ToolResultPart.make({
63
- ...part,
64
- result: {
65
- type: "json",
66
- value: { type: "image_generation_call", id: part.id, status: "completed", result: null },
67
- },
68
- });
69
- }),
70
- })),
71
- }), adapter);
51
+ const body = yield* OpenResponses.fromRequestWithAdapter({
52
+ ...request,
53
+ messages: request.messages.map((message) => message.role !== "assistant"
54
+ ? message
55
+ : new AssistantMessage({
56
+ ...message,
57
+ content: message.content.map((part) => {
58
+ if (part.type !== "tool-result" ||
59
+ !part.providerExecuted ||
60
+ part.name !== "image_generation" ||
61
+ part.result.type !== "content" ||
62
+ part.providerMetadata?.[key]?.itemId !== part.id)
63
+ return part;
64
+ // Meta's signed image ID carries edit state; replay the handle, not the image bytes as a user message.
65
+ return ToolResultPart.make({
66
+ ...part,
67
+ result: {
68
+ type: "json",
69
+ value: { type: "image_generation_call", id: part.id, status: "completed", result: null },
70
+ },
71
+ });
72
+ }),
73
+ })),
74
+ }, adapter);
72
75
  // Meta cannot see video nested in tool results; attach it after the complete result batch.
73
76
  const input = [];
74
77
  const videos = [];
@@ -99,7 +102,7 @@ const fromRequest = Effect.fn("MetaResponses.fromRequest")(function* (request) {
99
102
  // Hosted replay items have an open `type`, so a plain tag check does not narrow the union.
100
103
  const isFunctionCallOutput = (item) => item.type === "function_call_output" || item.type === "custom_tool_call_output";
101
104
  const HOSTED_TOOLS = {
102
- web_search_call: { name: "web_search", input: (item) => item.action ?? {} },
105
+ web_search_call: ResponsesHostedTools.common.web_search_call,
103
106
  image_generation_call: {
104
107
  name: "image_generation",
105
108
  input: () => ({}),
@@ -1,4 +1,4 @@
1
- import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
1
+ import { ImageModel, ImageResponse, type ImageRequest } from "../image.js";
2
2
  import { MediaProtocol } from "../route/media-protocol.js";
3
3
  import { MediaRoute } from "../route/media.js";
4
4
  import { type OpenString } from "../schema/index.js";
@@ -16,7 +16,7 @@ export type MiniMaxImageOptions = {
16
16
  readonly width?: number;
17
17
  readonly height?: number;
18
18
  } & Record<string, unknown>;
19
- export type Request = ImageRequestFor<MiniMaxImageOptions>;
19
+ export type Request = ImageRequest<ImageModel<MiniMaxImageOptions>>;
20
20
  export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
21
21
  export declare const model: (input: MediaRoute.ModelInput) => ImageModel<MiniMaxImageOptions>;
22
22
  export declare const MiniMaxImages: {
@@ -165,7 +165,6 @@ const lowerUser = Effect.fnUntraced(function* (message) {
165
165
  content.push(yield* lowerMedia(part));
166
166
  continue;
167
167
  }
168
- return yield* ProviderShared.unsupportedContent("Mistral Chat", "user", ["text", "media"]);
169
168
  }
170
169
  if (content.every((part) => part.type === "text"))
171
170
  return { role: "user", content: content.map((part) => part.text).join("") };
@@ -210,8 +209,6 @@ const lowerAssistant = Effect.fnUntraced(function* (message, normalizeID) {
210
209
  const lowerToolResults = Effect.fnUntraced(function* (message, normalizeID) {
211
210
  const output = [];
212
211
  for (const part of message.content) {
213
- if (part.type !== "tool-result")
214
- return yield* ProviderShared.unsupportedContent("Mistral Chat", "tool", ["tool-result"]);
215
212
  if (part.result.type !== "content") {
216
213
  output.push({
217
214
  role: "tool",
@@ -305,13 +302,13 @@ export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (reque
305
302
  tools: flattened.tools.length > 0 ? flattened.tools.map(lowerTool) : undefined,
306
303
  tool_choice: toolChoice,
307
304
  stream: true,
308
- max_tokens: request.generation?.maxTokens,
309
- random_seed: request.generation?.seed,
310
- temperature: request.generation?.temperature,
311
- top_p: request.generation?.topP,
312
- frequency_penalty: request.generation?.frequencyPenalty,
313
- presence_penalty: request.generation?.presencePenalty,
314
- stop: request.generation?.stop,
305
+ max_tokens: request.maxTokens,
306
+ random_seed: request.seed,
307
+ temperature: request.temperature,
308
+ top_p: request.topP,
309
+ frequency_penalty: request.frequencyPenalty,
310
+ presence_penalty: request.presencePenalty,
311
+ stop: request.stop,
315
312
  prompt_cache_key: ProviderShared.sendsPromptCacheKey(request)
316
313
  ? (options.promptCacheKey ?? request.promptCacheKey)
317
314
  : undefined,
@@ -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") {
@@ -1566,7 +1566,7 @@ export declare const fromRequest: (request: LLMRequest) => Effect.Effect<{
1566
1566
  }[];
1567
1567
  } | undefined;
1568
1568
  }, AIError, never>;
1569
- export declare const mapUsage: (usage: OpenResponsesUsage | null | undefined, providerMetadataKey: string) => Usage | undefined;
1569
+ export declare const mapUsage: (usage: OpenResponsesUsage | null | undefined, providerMetadataKey: string, ...frames: ReadonlyArray<unknown>) => Usage | undefined;
1570
1570
  export declare const metadataKey: (model: LLMRequest["model"]) => string;
1571
1571
  export declare const providerMetadata: (state: ParserState, metadata: Record<string, unknown>) => ProviderMetadata;
1572
1572
  export type StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>];
@@ -1728,18 +1728,6 @@ export declare const step: (state: ParserState, event: NormalizedEvent) => AIErr
1728
1728
  readonly [x: string]: unknown;
1729
1729
  };
1730
1730
  } | undefined;
1731
- } | {
1732
- readonly type: "tool-error";
1733
- readonly id: string;
1734
- readonly name: string;
1735
- readonly namespace?: string | undefined;
1736
- readonly message: string;
1737
- readonly error?: unknown;
1738
- readonly providerMetadata?: {
1739
- readonly [x: string]: {
1740
- readonly [x: string]: unknown;
1741
- };
1742
- } | undefined;
1743
1731
  } | {
1744
1732
  readonly type: "step-finish";
1745
1733
  readonly index: number;
@@ -1764,6 +1752,7 @@ export declare const step: (state: ParserState, event: NormalizedEvent) => AIErr
1764
1752
  readonly explanation?: string | undefined;
1765
1753
  };
1766
1754
  readonly usage?: Usage | undefined;
1755
+ readonly message?: import("../schema/messages.js").AssistantMessage | undefined;
1767
1756
  readonly providerMetadata?: {
1768
1757
  readonly [x: string]: {
1769
1758
  readonly [x: string]: unknown;
@@ -1777,15 +1766,6 @@ export declare const step: (state: ParserState, event: NormalizedEvent) => AIErr
1777
1766
  readonly [x: string]: unknown;
1778
1767
  };
1779
1768
  } | undefined;
1780
- } | {
1781
- readonly type: "provider-error";
1782
- readonly message: string;
1783
- readonly classification?: "context-overflow" | "payload-too-large" | undefined;
1784
- readonly providerMetadata?: {
1785
- readonly [x: string]: {
1786
- readonly [x: string]: unknown;
1787
- };
1788
- } | undefined;
1789
1769
  } | ({
1790
1770
  readonly type: "compaction";
1791
1771
  readonly provider: string & import("effect/Brand").Brand<"AI.ProviderID">;
@@ -423,9 +423,7 @@ const lowerMedia = Effect.fnUntraced(function* (part, request, adapter) {
423
423
  const lowerUserContent = Effect.fnUntraced(function* (part, request, adapter) {
424
424
  if (part.type === "text")
425
425
  return { type: "input_text", text: part.text };
426
- if (part.type === "media")
427
- return yield* lowerMedia(part, request, adapter);
428
- return yield* ProviderShared.unsupportedContent(adapter.name, "user", ["text", "media"]);
426
+ return yield* lowerMedia(part, request, adapter);
429
427
  });
430
428
  // Tool results may carry structured text, images, and files. Keep media as provider-native
431
429
  // content instead of JSON-stringifying base64 into a prompt string.
@@ -450,7 +448,9 @@ const lowerMessages = Effect.fnUntraced(function* (request, adapter) {
450
448
  const custom = OpenAIFreeform.tools(request);
451
449
  const customTool = (part) => part.namespace === undefined ? custom.get(part.name) : undefined;
452
450
  for (const message of request.messages) {
453
- const rawMetadata = message.providerMetadata?.[providerMetadataKey];
451
+ const rawMetadata = message.role === "user" || message.role === "assistant"
452
+ ? message.providerMetadata?.[providerMetadataKey]
453
+ : undefined;
454
454
  const metadata = rawMetadata === undefined ? undefined : yield* decodeMessageMetadata(rawMetadata);
455
455
  if (message.role === "system") {
456
456
  const update = effortUpdate(message);
@@ -588,8 +588,6 @@ const lowerMessages = Effect.fnUntraced(function* (request, adapter) {
588
588
  continue;
589
589
  }
590
590
  for (const part of message.content) {
591
- if (!ProviderShared.supportsContent(part, ["tool-result"]))
592
- return yield* ProviderShared.unsupportedContent(adapter.name, "tool", ["tool-result"]);
593
591
  input.push({
594
592
  type: customTool(part) ? "custom_tool_call_output" : "function_call_output",
595
593
  call_id: part.id,
@@ -608,16 +606,15 @@ export const lowerConversation = Effect.fnUntraced(function* (request, adapter)
608
606
  };
609
607
  });
610
608
  export const lowerGeneration = (request, options = OpenResponsesOptions.resolve(request)) => {
611
- const generation = request.generation;
612
609
  const cacheKey = ProviderShared.promptCacheKey(request);
613
610
  const parallelToolCalls = resolveParallelToolCalls(request, options);
614
611
  return {
615
612
  stream: true,
616
- max_output_tokens: generation?.maxTokens,
617
- temperature: generation?.temperature,
618
- top_p: generation?.topP,
619
- presence_penalty: generation?.presencePenalty,
620
- frequency_penalty: generation?.frequencyPenalty,
613
+ max_output_tokens: request.maxTokens,
614
+ temperature: request.temperature,
615
+ top_p: request.topP,
616
+ presence_penalty: request.presencePenalty,
617
+ frequency_penalty: request.frequencyPenalty,
621
618
  ...(options.store !== undefined ? { store: options.store } : {}),
622
619
  ...(options.metadata ? { metadata: options.metadata } : {}),
623
620
  ...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}),
@@ -674,7 +671,7 @@ export const fromRequest = (request) => fromRequestWithAdapter(request, BASE_ADA
674
671
  // cached-read and cache-write subsets, and `output_tokens` (inclusive total)
675
672
  // with a `reasoning_tokens` subset. Pass the totals through and derive the
676
673
  // non-cached breakdown.
677
- export const mapUsage = (usage, providerMetadataKey) => {
674
+ export const mapUsage = (usage, providerMetadataKey, ...frames) => {
678
675
  if (!usage)
679
676
  return undefined;
680
677
  const cached = usage.input_tokens_details?.cached_tokens;
@@ -689,10 +686,29 @@ export const mapUsage = (usage, providerMetadataKey) => {
689
686
  cacheWriteInputTokens: cacheWrite,
690
687
  reasoningTokens: reasoning,
691
688
  totalTokens: ProviderShared.totalTokens(usage.input_tokens, usage.output_tokens, usage.total_tokens),
692
- ...ProviderShared.reportedBilling(usage),
689
+ ...ProviderShared.reportedBilling(usage, ...frames),
693
690
  providerMetadata: { [providerMetadataKey]: usage },
694
691
  });
695
692
  };
693
+ // GitHub Copilot lists the filters that ran; the blocking one names its rule in `content_filter_raw`.
694
+ const decodeContentFilters = Schema.decodeUnknownOption(Schema.Array(Schema.Struct({
695
+ source_type: Schema.optional(Schema.String),
696
+ blocked: Schema.optional(Schema.Boolean),
697
+ content_filter_raw: Schema.optional(Schema.Array(Schema.Struct({
698
+ action: Schema.optional(Schema.String),
699
+ label: Schema.optional(Schema.String),
700
+ result: Schema.optional(Schema.Unknown),
701
+ }))),
702
+ content_filter_results: Schema.optional(Schema.Unknown),
703
+ })));
704
+ const contentFilterCategory = (raw) => {
705
+ const blocked = Option.getOrElse(decodeContentFilters(raw), () => []).filter((filter) => filter.blocked);
706
+ const filter = blocked.find((item) => item.source_type === "completion") ?? blocked[0];
707
+ if (!filter)
708
+ return undefined;
709
+ return (filter.content_filter_raw?.find((rule) => rule.action === "BLOCK" && rule.result === true)?.label ??
710
+ ProviderShared.contentFilterCategory(filter.content_filter_results));
711
+ };
696
712
  const mapFinishReason = (event, hasFunctionCall) => {
697
713
  const reason = event.response?.incomplete_details?.reason;
698
714
  if (reason === undefined) {
@@ -752,12 +768,13 @@ const ITEM_ID_PREFIX = {
752
768
  custom_tool_call: "ctc",
753
769
  compaction: "cmp",
754
770
  };
755
- // An item without an id adopts the id already open in its output slot,
756
- // otherwise it gets a locally minted one.
771
+ // An item adopts the id already open in its output slot, since GitHub Copilot
772
+ // sends a different id on every event, including the item's own done event.
773
+ // Otherwise it keeps its id or gets a locally minted one.
757
774
  const resolveItem = (state, item, index) => ({
758
775
  ...item,
759
- id: item.id ??
760
- (index === undefined ? undefined : state.outputItems[index]) ??
776
+ id: (index === undefined ? undefined : state.outputItems[index]) ??
777
+ item.id ??
761
778
  `${ITEM_ID_PREFIX[item.type] ?? "item"}_${crypto.randomUUID().replaceAll("-", "")}`,
762
779
  });
763
780
  // Registered output slots are authoritative for `item_id` routing, and items
@@ -1036,9 +1053,7 @@ const onOutputItemDone = Effect.fnUntraced(function* (state, item) {
1036
1053
  namespace: item.namespace,
1037
1054
  providerMetadata: metadata,
1038
1055
  });
1039
- const result = input === undefined
1040
- ? yield* ToolStream.finish(state.id, tools, item.id)
1041
- : yield* ToolStream.finishWithInput(state.id, tools, item.id, input);
1056
+ const result = yield* ToolStream.finish(state.id, tools, item.id, input);
1042
1057
  const events = [];
1043
1058
  const finished = [...(closed?.events ?? []), ...(result.events ?? [])];
1044
1059
  // A done-only call never streamed a start event, so open its lifecycle here.
@@ -1133,12 +1148,15 @@ const onResponseFinish = Effect.fnUntraced(function* (state, event) {
1133
1148
  };
1134
1149
  events.push(...pending.events);
1135
1150
  }
1151
+ const normalized = mapFinishReason(event, current.hasFunctionCall);
1136
1152
  const lifecycle = Lifecycle.finish(current.lifecycle, events, {
1137
1153
  reason: {
1138
- normalized: mapFinishReason(event, current.hasFunctionCall),
1154
+ normalized,
1139
1155
  raw: event.response?.incomplete_details?.reason,
1156
+ ...(normalized === "content-filter" ? { category: contentFilterCategory(event.response?.content_filters) } : {}),
1140
1157
  },
1141
- usage: mapUsage(event.response?.usage, current.providerMetadataKey),
1158
+ // Copilot reports its billing on the terminal event, beside `response`.
1159
+ usage: mapUsage(event.response?.usage, current.providerMetadataKey, event, event.response),
1142
1160
  providerMetadata: event.response?.id || event.response?.service_tier
1143
1161
  ? providerMetadata(current, {
1144
1162
  responseId: event.response.id,