@opencode/ai 2.3.1 → 2.4.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 (87) hide show
  1. package/dist/decision.d.ts +4 -3
  2. package/dist/decision.js +3 -2
  3. package/dist/embedding.d.ts +4 -3
  4. package/dist/embedding.js +3 -2
  5. package/dist/experimental/cloudflare-run-extraction.js +1 -2
  6. package/dist/experimental/realtime.d.ts +12 -43
  7. package/dist/experimental/realtime.js +14 -30
  8. package/dist/experimental.d.ts +1 -1
  9. package/dist/image.js +1 -1
  10. package/dist/media-model.d.ts +5 -4
  11. package/dist/media-model.js +5 -4
  12. package/dist/media.js +4 -17
  13. package/dist/protocols/anthropic-messages.js +7 -11
  14. package/dist/protocols/bedrock-converse.js +6 -6
  15. package/dist/protocols/cohere-chat.js +3 -3
  16. package/dist/protocols/gemini.js +6 -10
  17. package/dist/protocols/google-interactions.d.ts +299 -6
  18. package/dist/protocols/google-interactions.js +251 -33
  19. package/dist/protocols/meta-messages.js +3 -3
  20. package/dist/protocols/minimax-video.js +7 -1
  21. package/dist/protocols/mistral-chat.d.ts +1 -0
  22. package/dist/protocols/mistral-chat.js +3 -3
  23. package/dist/protocols/open-responses-continuation.js +2 -0
  24. package/dist/protocols/open-responses.d.ts +162 -114
  25. package/dist/protocols/open-responses.js +12 -7
  26. package/dist/protocols/openai-chat.d.ts +1 -0
  27. package/dist/protocols/openai-chat.js +6 -5
  28. package/dist/protocols/openai-responses.js +2 -1
  29. package/dist/protocols/shared.d.ts +12 -1
  30. package/dist/protocols/shared.js +56 -9
  31. package/dist/protocols/utils/gateway-protocol.js +1 -0
  32. package/dist/protocols/utils/gemini-generate-content.d.ts +4 -0
  33. package/dist/protocols/utils/gemini-generate-content.js +5 -1
  34. package/dist/protocols/utils/responses-compaction.js +10 -4
  35. package/dist/protocols/xai-responses.d.ts +2 -1
  36. package/dist/protocols/xai-responses.js +4 -1
  37. package/dist/provider-error.js +3 -1
  38. package/dist/providers/alibaba.js +2 -3
  39. package/dist/providers/assemblyai.d.ts +2 -4
  40. package/dist/providers/azure.js +5 -11
  41. package/dist/providers/baseten.js +2 -3
  42. package/dist/providers/byteplus.d.ts +2 -4
  43. package/dist/providers/cartesia.d.ts +2 -4
  44. package/dist/providers/cloudflare-ai-gateway.js +3 -3
  45. package/dist/providers/cloudflare-workers-ai.js +2 -3
  46. package/dist/providers/cohere.js +2 -3
  47. package/dist/providers/deepgram.d.ts +2 -4
  48. package/dist/providers/deepinfra.js +2 -3
  49. package/dist/providers/digitalocean.js +3 -5
  50. package/dist/providers/elevenlabs.d.ts +2 -4
  51. package/dist/providers/fireworks.js +2 -3
  52. package/dist/providers/google-vertex-interactions.d.ts +12 -3
  53. package/dist/providers/google-vertex-interactions.js +1 -2
  54. package/dist/providers/google-vertex.js +6 -2
  55. package/dist/providers/google.d.ts +20 -3
  56. package/dist/providers/google.js +7 -4
  57. package/dist/providers/openai-compatible.js +3 -5
  58. package/dist/providers/openai.js +4 -10
  59. package/dist/providers/opencode.d.ts +2 -4
  60. package/dist/providers/opencode.js +2 -3
  61. package/dist/providers/openrouter.js +3 -5
  62. package/dist/providers/typesafe-ai.d.ts +2 -4
  63. package/dist/providers/typesafe-ai.js +2 -3
  64. package/dist/providers/vercel-ai-gateway.js +3 -5
  65. package/dist/providers/volcengine.d.ts +2 -4
  66. package/dist/route/decision.d.ts +4 -7
  67. package/dist/route/decision.js +8 -10
  68. package/dist/route/embedding.d.ts +4 -7
  69. package/dist/route/embedding.js +4 -7
  70. package/dist/route/executor-service.d.ts +20 -3
  71. package/dist/route/executor-service.js +72 -2
  72. package/dist/route/executor.d.ts +5 -5
  73. package/dist/route/executor.js +68 -73
  74. package/dist/route/media-protocol.d.ts +2 -1
  75. package/dist/route/media-protocol.js +2 -10
  76. package/dist/route/media.d.ts +6 -8
  77. package/dist/route/media.js +8 -8
  78. package/dist/route/protocol.d.ts +2 -0
  79. package/dist/route/protocol.js +4 -1
  80. package/dist/route/transport/http.d.ts +1 -2
  81. package/dist/route/transport/http.js +5 -28
  82. package/dist/schema/errors.js +2 -1
  83. package/dist/schema/options.d.ts +1 -1
  84. package/dist/speech.js +1 -1
  85. package/dist/transcription.js +1 -1
  86. package/dist/video.js +1 -1
  87. package/package.json +3 -3
@@ -1087,6 +1087,166 @@ export declare const lowerToolChoice: (protocolName: string, toolChoice: NonNull
1087
1087
  type: "custom" | "function";
1088
1088
  name: string;
1089
1089
  }, AIError, never>;
1090
+ export declare const lowerMessages: (request: LLMRequest<import("../schema/options.js").LanguageModel<{
1091
+ readonly [x: string]: unknown;
1092
+ }, import("../route.js").CompactionOperations | undefined>>, adapter: ProviderAdapter) => Effect.Effect<({
1093
+ readonly type: "configuration_update";
1094
+ readonly reasoning: {
1095
+ readonly effort: OpenResponsesOptions.ReasoningEffort;
1096
+ };
1097
+ } | {
1098
+ readonly type: "additional_tools";
1099
+ readonly role: "developer";
1100
+ readonly tools: readonly ({
1101
+ readonly type: "custom";
1102
+ readonly name: string;
1103
+ readonly description: string;
1104
+ readonly format: {
1105
+ readonly type: "text";
1106
+ } | {
1107
+ readonly type: "grammar";
1108
+ readonly syntax: "lark" | "regex";
1109
+ readonly definition: string;
1110
+ };
1111
+ } | {
1112
+ readonly type: "function";
1113
+ readonly name: string;
1114
+ readonly description: string;
1115
+ readonly parameters: {
1116
+ readonly [x: string]: unknown;
1117
+ };
1118
+ readonly strict?: boolean | undefined;
1119
+ } | {
1120
+ readonly [x: string]: unknown;
1121
+ readonly type: string;
1122
+ })[];
1123
+ } | {
1124
+ readonly type: "message";
1125
+ readonly role: "system";
1126
+ readonly content: string;
1127
+ } | {
1128
+ readonly type: "message";
1129
+ readonly role: "developer";
1130
+ readonly content: string;
1131
+ } | {
1132
+ readonly type: "custom_tool_call_output" | "function_call_output";
1133
+ readonly call_id: string;
1134
+ readonly output: string | readonly ({
1135
+ readonly type: "input_text";
1136
+ readonly text: string;
1137
+ } | {
1138
+ readonly type: "input_video";
1139
+ readonly video_url: string;
1140
+ } | {
1141
+ readonly type: "input_image";
1142
+ readonly image_url: string;
1143
+ readonly detail?: string | undefined;
1144
+ } | {
1145
+ readonly type: "input_file";
1146
+ readonly filename?: string | undefined;
1147
+ readonly detail?: string | undefined;
1148
+ readonly file_data?: string | undefined;
1149
+ readonly file_url?: string | undefined;
1150
+ })[];
1151
+ } | {
1152
+ readonly type: "reasoning";
1153
+ readonly id?: string | undefined;
1154
+ readonly summary: readonly {
1155
+ readonly type: "summary_text";
1156
+ readonly text: string;
1157
+ }[];
1158
+ readonly encrypted_content?: string | null | undefined;
1159
+ } | {
1160
+ readonly type: "compaction";
1161
+ readonly id?: string | null | undefined;
1162
+ readonly encrypted_content: string;
1163
+ } | {
1164
+ readonly type: "message";
1165
+ readonly role: "user";
1166
+ readonly content: readonly ({
1167
+ readonly type: "input_text";
1168
+ readonly text: string;
1169
+ } | {
1170
+ readonly type: "input_video";
1171
+ readonly video_url: string;
1172
+ } | {
1173
+ readonly type: "input_image";
1174
+ readonly image_url: string;
1175
+ readonly detail?: string | undefined;
1176
+ } | {
1177
+ readonly type: "input_file";
1178
+ readonly filename?: string | undefined;
1179
+ readonly detail?: string | undefined;
1180
+ readonly file_data?: string | undefined;
1181
+ readonly file_url?: string | undefined;
1182
+ })[];
1183
+ readonly id?: string | undefined;
1184
+ readonly status?: string | undefined;
1185
+ } | {
1186
+ readonly type: "message";
1187
+ readonly id?: string | undefined;
1188
+ readonly role: "assistant";
1189
+ readonly content: readonly {
1190
+ readonly type: "output_text";
1191
+ readonly text: string;
1192
+ }[];
1193
+ readonly phase?: "commentary" | "final_answer" | null | undefined;
1194
+ readonly status?: string | undefined;
1195
+ } | {
1196
+ readonly type: "function_call";
1197
+ readonly id?: string | undefined;
1198
+ readonly call_id: string;
1199
+ readonly name: string;
1200
+ readonly namespace?: string | undefined;
1201
+ readonly arguments: string;
1202
+ } | {
1203
+ readonly type: "custom_tool_call";
1204
+ readonly id?: string | undefined;
1205
+ readonly call_id: string;
1206
+ readonly name: string;
1207
+ readonly input: string;
1208
+ } | {
1209
+ readonly [x: string]: unknown;
1210
+ readonly type: "web_search_call";
1211
+ readonly id: string;
1212
+ readonly status?: string | undefined;
1213
+ readonly action?: {
1214
+ readonly [x: string]: unknown;
1215
+ } | null | undefined;
1216
+ } | {
1217
+ readonly [x: string]: unknown;
1218
+ readonly type: "file_search_call";
1219
+ readonly id: string;
1220
+ readonly status?: string | undefined;
1221
+ readonly queries?: readonly string[] | undefined;
1222
+ readonly results?: readonly {
1223
+ readonly [x: string]: unknown;
1224
+ }[] | null | undefined;
1225
+ } | {
1226
+ readonly [x: string]: unknown;
1227
+ readonly type: "code_interpreter_call";
1228
+ readonly id: string;
1229
+ readonly status?: string | undefined;
1230
+ readonly code?: string | null | undefined;
1231
+ readonly container_id?: string | null | undefined;
1232
+ readonly outputs?: readonly {
1233
+ readonly [x: string]: unknown;
1234
+ }[] | null | undefined;
1235
+ } | {
1236
+ readonly [x: string]: unknown;
1237
+ readonly type: "mcp_call";
1238
+ readonly id: string;
1239
+ readonly status?: string | undefined;
1240
+ readonly server_label?: string | undefined;
1241
+ readonly name?: string | undefined;
1242
+ readonly arguments?: string | undefined;
1243
+ readonly output?: string | null | undefined;
1244
+ readonly error?: unknown;
1245
+ } | {
1246
+ readonly [x: string]: unknown;
1247
+ readonly type: string;
1248
+ readonly id: string;
1249
+ })[], AIError, never>;
1090
1250
  export declare const lowerConversation: (request: LLMRequest<import("../schema/options.js").LanguageModel<{
1091
1251
  readonly [x: string]: unknown;
1092
1252
  }, import("../route.js").CompactionOperations | undefined>>, adapter: ProviderAdapter) => Effect.Effect<{
@@ -1207,49 +1367,11 @@ export declare const lowerConversation: (request: LLMRequest<import("../schema/o
1207
1367
  readonly call_id: string;
1208
1368
  readonly name: string;
1209
1369
  readonly input: string;
1210
- } | {
1211
- readonly [x: string]: unknown;
1212
- readonly type: "web_search_call";
1213
- readonly id: string;
1214
- readonly status?: string | undefined;
1215
- readonly action?: {
1216
- readonly [x: string]: unknown;
1217
- } | null | undefined;
1218
- } | {
1219
- readonly [x: string]: unknown;
1220
- readonly type: "file_search_call";
1221
- readonly id: string;
1222
- readonly status?: string | undefined;
1223
- readonly queries?: readonly string[] | undefined;
1224
- readonly results?: readonly {
1225
- readonly [x: string]: unknown;
1226
- }[] | null | undefined;
1227
- } | {
1228
- readonly [x: string]: unknown;
1229
- readonly type: "code_interpreter_call";
1230
- readonly id: string;
1231
- readonly status?: string | undefined;
1232
- readonly code?: string | null | undefined;
1233
- readonly container_id?: string | null | undefined;
1234
- readonly outputs?: readonly {
1235
- readonly [x: string]: unknown;
1236
- }[] | null | undefined;
1237
- } | {
1238
- readonly [x: string]: unknown;
1239
- readonly type: "mcp_call";
1240
- readonly id: string;
1241
- readonly status?: string | undefined;
1242
- readonly server_label?: string | undefined;
1243
- readonly name?: string | undefined;
1244
- readonly arguments?: string | undefined;
1245
- readonly output?: string | null | undefined;
1246
- readonly error?: unknown;
1247
1370
  } | {
1248
1371
  readonly [x: string]: unknown;
1249
1372
  readonly type: string;
1250
1373
  readonly id: string;
1251
1374
  })[];
1252
- instructions?: string | undefined;
1253
1375
  }, AIError, never>;
1254
1376
  export declare const lowerGeneration: (request: LLMRequest, options?: OpenResponsesOptions.Resolved) => {
1255
1377
  stream: true;
@@ -1290,6 +1412,7 @@ export declare const allowedToolChoice: (options: OpenResponsesOptions.Resolved,
1290
1412
  name: string;
1291
1413
  }[];
1292
1414
  } | undefined;
1415
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
1293
1416
  export declare const fromRequestWithAdapter: (request: LLMRequest<import("../schema/options.js").LanguageModel<{
1294
1417
  readonly [x: string]: unknown;
1295
1418
  }, import("../route.js").CompactionOperations | undefined>>, adapter: ProviderAdapter) => Effect.Effect<{
@@ -1410,49 +1533,11 @@ export declare const fromRequestWithAdapter: (request: LLMRequest<import("../sch
1410
1533
  readonly call_id: string;
1411
1534
  readonly name: string;
1412
1535
  readonly input: string;
1413
- } | {
1414
- readonly [x: string]: unknown;
1415
- readonly type: "web_search_call";
1416
- readonly id: string;
1417
- readonly status?: string | undefined;
1418
- readonly action?: {
1419
- readonly [x: string]: unknown;
1420
- } | null | undefined;
1421
- } | {
1422
- readonly [x: string]: unknown;
1423
- readonly type: "file_search_call";
1424
- readonly id: string;
1425
- readonly status?: string | undefined;
1426
- readonly queries?: readonly string[] | undefined;
1427
- readonly results?: readonly {
1428
- readonly [x: string]: unknown;
1429
- }[] | null | undefined;
1430
- } | {
1431
- readonly [x: string]: unknown;
1432
- readonly type: "code_interpreter_call";
1433
- readonly id: string;
1434
- readonly status?: string | undefined;
1435
- readonly code?: string | null | undefined;
1436
- readonly container_id?: string | null | undefined;
1437
- readonly outputs?: readonly {
1438
- readonly [x: string]: unknown;
1439
- }[] | null | undefined;
1440
- } | {
1441
- readonly [x: string]: unknown;
1442
- readonly type: "mcp_call";
1443
- readonly id: string;
1444
- readonly status?: string | undefined;
1445
- readonly server_label?: string | undefined;
1446
- readonly name?: string | undefined;
1447
- readonly arguments?: string | undefined;
1448
- readonly output?: string | null | undefined;
1449
- readonly error?: unknown;
1450
1536
  } | {
1451
1537
  readonly [x: string]: unknown;
1452
1538
  readonly type: string;
1453
1539
  readonly id: string;
1454
1540
  })[];
1455
- instructions?: string | undefined;
1456
1541
  stream: true;
1457
1542
  max_output_tokens: number | undefined;
1458
1543
  temperature: number | undefined;
@@ -1516,6 +1601,7 @@ export declare const fromRequestWithAdapter: (request: LLMRequest<import("../sch
1516
1601
  }[];
1517
1602
  } | undefined;
1518
1603
  }, AIError, never>;
1604
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
1519
1605
  export declare const fromRequest: (request: LLMRequest) => Effect.Effect<{
1520
1606
  model: string & import("effect/Brand").Brand<"AI.ModelID">;
1521
1607
  input: ({
@@ -1634,49 +1720,11 @@ export declare const fromRequest: (request: LLMRequest) => Effect.Effect<{
1634
1720
  readonly call_id: string;
1635
1721
  readonly name: string;
1636
1722
  readonly input: string;
1637
- } | {
1638
- readonly [x: string]: unknown;
1639
- readonly type: "web_search_call";
1640
- readonly id: string;
1641
- readonly status?: string | undefined;
1642
- readonly action?: {
1643
- readonly [x: string]: unknown;
1644
- } | null | undefined;
1645
- } | {
1646
- readonly [x: string]: unknown;
1647
- readonly type: "file_search_call";
1648
- readonly id: string;
1649
- readonly status?: string | undefined;
1650
- readonly queries?: readonly string[] | undefined;
1651
- readonly results?: readonly {
1652
- readonly [x: string]: unknown;
1653
- }[] | null | undefined;
1654
- } | {
1655
- readonly [x: string]: unknown;
1656
- readonly type: "code_interpreter_call";
1657
- readonly id: string;
1658
- readonly status?: string | undefined;
1659
- readonly code?: string | null | undefined;
1660
- readonly container_id?: string | null | undefined;
1661
- readonly outputs?: readonly {
1662
- readonly [x: string]: unknown;
1663
- }[] | null | undefined;
1664
- } | {
1665
- readonly [x: string]: unknown;
1666
- readonly type: "mcp_call";
1667
- readonly id: string;
1668
- readonly status?: string | undefined;
1669
- readonly server_label?: string | undefined;
1670
- readonly name?: string | undefined;
1671
- readonly arguments?: string | undefined;
1672
- readonly output?: string | null | undefined;
1673
- readonly error?: unknown;
1674
1723
  } | {
1675
1724
  readonly [x: string]: unknown;
1676
1725
  readonly type: string;
1677
1726
  readonly id: string;
1678
1727
  })[];
1679
- instructions?: string | undefined;
1680
1728
  stream: true;
1681
1729
  max_output_tokens: number | undefined;
1682
1730
  temperature: number | undefined;
@@ -450,7 +450,7 @@ const lowerToolResultOutput = Effect.fnUntraced(function* (part, request, adapte
450
450
  return yield* Effect.forEach(content, (item) => lowerToolResultContentItem(item, request, adapter));
451
451
  });
452
452
  const DEFAULT_EFFORT = "medium";
453
- const lowerMessages = Effect.fnUntraced(function* (request, adapter) {
453
+ export const lowerMessages = Effect.fnUntraced(function* (request, adapter) {
454
454
  const input = [];
455
455
  const providerMetadataKey = metadataKey(request.model);
456
456
  const custom = OpenAIFreeform.tools(request);
@@ -613,12 +613,15 @@ const lowerMessages = Effect.fnUntraced(function* (request, adapter) {
613
613
  }
614
614
  return input;
615
615
  });
616
+ // The system prompt leads `input` as a developer message: GPT-6.2 models never cache top-level `instructions`.
616
617
  export const lowerConversation = Effect.fnUntraced(function* (request, adapter) {
617
- const instructions = ProviderShared.joinText(request.system);
618
+ const system = ProviderShared.joinText(request.system);
618
619
  return {
619
620
  model: request.model.id,
620
- input: yield* lowerMessages(request, adapter),
621
- ...(instructions ? { instructions } : {}),
621
+ input: [
622
+ ...(system ? [{ type: "message", role: "developer", content: system }] : []),
623
+ ...(yield* lowerMessages(request, adapter)),
624
+ ],
622
625
  };
623
626
  });
624
627
  export const lowerGeneration = (request, options = OpenResponsesOptions.resolve(request)) => {
@@ -667,18 +670,20 @@ export const allowedToolChoice = (options, custom) => {
667
670
  tools: allowed.toolNames.map((name) => namedTool(name, custom)),
668
671
  };
669
672
  };
673
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
670
674
  export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAdapter")(function* (request, adapter) {
671
- const projected = ProviderShared.flattenToolRequest(request);
675
+ const definitions = ProviderShared.flattenTools(request.tools);
672
676
  const options = OpenResponsesOptions.resolve(request);
673
677
  const custom = OpenAIFreeform.tools(request);
674
678
  return {
675
- ...(yield* lowerConversation(projected.request, adapter)),
679
+ ...(yield* lowerConversation(request, adapter)),
676
680
  ...lowerGeneration(request, options),
677
- tools: projected.tools.length === 0 ? undefined : yield* lowerTools(projected.tools, adapter, custom),
681
+ tools: definitions.length === 0 ? undefined : yield* lowerTools(definitions, adapter, custom),
678
682
  tool_choice: allowedToolChoice(options, custom) ??
679
683
  (request.toolChoice ? yield* lowerToolChoice(adapter.name, request.toolChoice, custom) : undefined),
680
684
  };
681
685
  });
686
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
682
687
  export const fromRequest = (request) => fromRequestWithAdapter(request, BASE_ADAPTER);
683
688
  // =============================================================================
684
689
  // Stream Parsing
@@ -718,6 +718,7 @@ interface LoweringOptions {
718
718
  /** Project provider-specific fields from the exact source, even when other messages are dropped during lowering. */
719
719
  readonly assistant?: (source: AssistantMessage, message: OpenAIChatMessage) => OpenAIChatMessage;
720
720
  }
721
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
721
722
  export declare const fromRequest: (request: LLMRequest<import("../schema/options.js").LanguageModel<{
722
723
  readonly [x: string]: unknown;
723
724
  }, import("../route/client.js").CompactionOperations | undefined>>, options?: LoweringOptions | undefined) => Effect.Effect<{
@@ -676,13 +676,14 @@ const lowerOptions = (request, supportsStore, hasActiveTools) => {
676
676
  ...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}),
677
677
  };
678
678
  };
679
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
679
680
  export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (request, options = {}) {
680
681
  // `fromRequest` returns the provider body only. Endpoint, auth, framing,
681
682
  // validation, and HTTP execution are composed by `Route.make`.
682
683
  const reasoningField = request.model.compatibility?.reasoningField;
683
684
  if (reasoningField && RESERVED_REASONING_FIELDS.has(reasoningField))
684
685
  return yield* ProviderShared.invalidRequest(`OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`);
685
- const flattened = ProviderShared.flattenToolRequest(request);
686
+ const definitions = ProviderShared.flattenTools(request.tools);
686
687
  const provider = request.model.provider;
687
688
  const baseURL = request.model.route.endpoint.baseURL;
688
689
  const detectedMaxTokensField = detectMaxTokensField(provider, baseURL);
@@ -691,17 +692,17 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (reques
691
692
  const supportsStrictMode = request.model.capabilities?.tools?.strict ?? detectSupportsStrictMode(provider, baseURL);
692
693
  const zaiToolStream = request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id);
693
694
  const hasHistory = hasToolHistory(request.messages);
694
- const hasActiveTools = flattened.tools.length > 0;
695
+ const hasActiveTools = definitions.length > 0;
695
696
  const custom = OpenAIFreeform.tools(request);
696
697
  const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom };
697
698
  return {
698
699
  model: request.model.id,
699
- messages: yield* lowerMessages(flattened.request, lowering),
700
- tools: flattened.tools.length === 0
700
+ messages: yield* lowerMessages(request, lowering),
701
+ tools: definitions.length === 0
701
702
  ? hasHistory
702
703
  ? []
703
704
  : undefined
704
- : flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
705
+ : definitions.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
705
706
  tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice, custom) : undefined,
706
707
  stream: true,
707
708
  ...((request.model.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}),
@@ -248,7 +248,7 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request)
248
248
  lowerToolChanges: toolChangeLowering(layout.head.length > 0, custom),
249
249
  });
250
250
  return {
251
- ...conversation,
251
+ model: conversation.model,
252
252
  input: [...layout.head, ...conversation.input],
253
253
  ...generation,
254
254
  ...Cache.openAIRequestTTL(requestTTL(request)),
@@ -326,6 +326,7 @@ export const protocol = Protocol.make({
326
326
  }),
327
327
  supportsEffortUpdates,
328
328
  toolUpdates,
329
+ namespaces: true,
329
330
  });
330
331
  const endpoint = Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL });
331
332
  const auth = Auth.none;
@@ -184,9 +184,20 @@ export declare const unsupportedOperation: (input: {
184
184
  /**
185
185
  * Lower namespaces to flat definitions for protocols without a native
186
186
  * namespace construct. Leaf names join their namespace path with `_` because
187
- * `.` is not broadly accepted in provider tool names.
187
+ * `.` is not broadly accepted in provider tool names. A no-op on tools `flattenRequest` already flattened; adapters call
188
+ * it to type their tools.
188
189
  */
189
190
  export declare const flattenTools: (tools: ReadonlyArray<ToolEntry>, path?: ReadonlyArray<string>) => ToolDefinition[];
191
+ /**
192
+ * The request as a protocol without native namespaces sees it: tools, tool updates, past calls and a forced choice all
193
+ * use flattened names. `Protocol.make` applies it before `body.from` for such protocols, so adapters only see flat
194
+ * requests.
195
+ */
196
+ export declare const flattenRequest: (request: LLMRequest) => LLMRequest;
197
+ /**
198
+ * @deprecated Routes without native namespaces already receive flattened requests; use `flattenRequest`. Removed in
199
+ * the next minor.
200
+ */
190
201
  export declare const flattenToolRequest: (request: LLMRequest) => {
191
202
  tools: ToolDefinition[];
192
203
  request: LLMRequest<import("../schema/options.js").LanguageModel<{
@@ -2,9 +2,10 @@ import { Tool } from "@opencode/schema/tool";
2
2
  import { Effect, Option, Predicate, Schema, SchemaGetter, SchemaTransformation } from "effect";
3
3
  import { Headers, HttpClientRequest } from "effect/http";
4
4
  import { Media } from "../media.js";
5
- import { InvalidProviderOutputError, InvalidRequestError, UnsupportedOperationError, AIError, AssistantMessage, Message, ToolDefinition, ToolMessage, } from "../schema/index.js";
5
+ import { InvalidProviderOutputError, InvalidRequestError, UnsupportedOperationError, AIError, AssistantMessage, Message, SystemMessage, ToolChoice, ToolDefinition, ToolMessage, } from "../schema/index.js";
6
6
  import { Json, decodeJson, encodeJson } from "../utils/json.js";
7
7
  import { isRecord } from "../utils/record.js";
8
+ import { foldTools, toolsUpdate, withdrawnTools } from "../tool-updates.js";
8
9
  export { Json, decodeJson, encodeJson, isRecord };
9
10
  const isJson = Schema.is(Schema.Json);
10
11
  export const JsonObject = Schema.Record(Schema.String, Schema.Unknown);
@@ -269,7 +270,8 @@ export const unsupportedOperation = (input) => new AIError({
269
270
  /**
270
271
  * Lower namespaces to flat definitions for protocols without a native
271
272
  * namespace construct. Leaf names join their namespace path with `_` because
272
- * `.` is not broadly accepted in provider tool names.
273
+ * `.` is not broadly accepted in provider tool names. A no-op on tools `flattenRequest` already flattened; adapters call
274
+ * it to type their tools.
273
275
  */
274
276
  export const flattenTools = (tools, path = []) => {
275
277
  const flat = tools.flatMap((tool) => {
@@ -281,25 +283,70 @@ export const flattenTools = (tools, path = []) => {
281
283
  });
282
284
  return [...new Map(flat.map((tool) => [tool.name, tool])).values()];
283
285
  };
284
- export const flattenToolRequest = (request) => {
286
+ /**
287
+ * The request as a protocol without native namespaces sees it: tools, tool updates, past calls and a forced choice all
288
+ * use flattened names. `Protocol.make` applies it before `body.from` for such protocols, so adapters only see flat
289
+ * requests.
290
+ */
291
+ export const flattenRequest = (request) => {
292
+ const all = [...request.tools, ...request.messages.flatMap((message) => toolsUpdate(message)?.add ?? [])];
293
+ const declared = new Set(flattenTools(all).map((tool) => tool.name));
294
+ const flatten = (part) => flattenToolName(part, declared);
295
+ // A tool update that redefines a namespace drops the tools it leaves out, which only the namespace shows, so name
296
+ // them as explicit removals.
297
+ let tools = request.tools;
285
298
  const messages = request.messages.map((message) => {
299
+ if (message.role === "system" && message.tools !== undefined) {
300
+ const next = foldTools(tools, message.tools.add, message.tools.remove);
301
+ const remove = withdrawnTools(tools, next);
302
+ tools = next;
303
+ return new SystemMessage({ ...message, tools: { add: flattenTools(message.tools.add), remove } });
304
+ }
286
305
  if (message.role === "assistant") {
287
- const content = message.content.map((part) => part.type === "tool-call" || part.type === "tool-result" ? flattenToolName(part) : part);
306
+ const content = message.content.map((part) => part.type === "tool-call" || part.type === "tool-result" ? flatten(part) : part);
288
307
  return sameParts(content, message.content) ? message : new AssistantMessage({ ...message, content });
289
308
  }
290
309
  if (message.role !== "tool")
291
310
  return message;
292
- const content = message.content.map(flattenToolName);
311
+ const content = message.content.map(flatten);
293
312
  return sameParts(content, message.content) ? message : new ToolMessage({ ...message, content });
294
313
  });
295
314
  return {
315
+ ...request,
296
316
  tools: flattenTools(request.tools),
297
- request: messages.every((message, index) => message === request.messages[index])
298
- ? request
299
- : { ...request, messages },
317
+ messages,
318
+ toolChoice: flattenToolChoice(request.toolChoice, all, declared),
300
319
  };
301
320
  };
302
- const flattenToolName = (part) => part.namespace === undefined ? part : { ...part, name: `${part.namespace}_${part.name}`, namespace: undefined };
321
+ /**
322
+ * @deprecated Routes without native namespaces already receive flattened requests; use `flattenRequest`. Removed in
323
+ * the next minor.
324
+ */
325
+ export const flattenToolRequest = (request) => {
326
+ const flat = flattenRequest(request);
327
+ return { tools: flattenTools(flat.tools), request: flat };
328
+ };
329
+ // A forced choice names a namespaced tool by its path (`crm.lookup`); point it at the flattened definition.
330
+ const flattenToolChoice = (choice, tools, declared) => {
331
+ if (choice?.type !== "tool" || choice.name === undefined || declared.has(choice.name))
332
+ return choice;
333
+ const name = new Map(namespacedPaths(tools)).get(choice.name);
334
+ return name === undefined ? choice : new ToolChoice({ ...choice, name });
335
+ };
336
+ // Each namespaced tool's path and the name flattenTools gives it.
337
+ const namespacedPaths = (tools, path = []) => tools.flatMap((tool) => {
338
+ if (tool.type === "namespace")
339
+ return namespacedPaths(tool.tools, [...path, tool.name]);
340
+ return path.length === 0 ? [] : [[[...path, tool.name].join("."), [...path, tool.name].join("_")]];
341
+ });
342
+ const flattenToolName = (part, declared) => {
343
+ const flat = part.namespace === undefined ? part.name : `${part.namespace}_${part.name}`;
344
+ // Models sometimes call names no tool declares, such as a Code Mode path like `a.b.c`. Several providers (OpenAI
345
+ // Chat Completions, Bedrock Converse) reject those characters when the call is replayed, so replace them. A
346
+ // declared name is kept as is, so a provider that accepts it sees calls under the tool's own name.
347
+ const name = declared.has(flat) ? flat : flat.replace(/[^a-zA-Z0-9_-]/g, "_") || "_";
348
+ return name === part.name && part.namespace === undefined ? part : { ...part, name, namespace: undefined };
349
+ };
303
350
  const sameParts = (next, previous) => next.every((part, index) => part === previous[index]);
304
351
  export const matchToolChoice = (route, toolChoice, cases) => Effect.gen(function* () {
305
352
  if (toolChoice.type === "auto")
@@ -37,6 +37,7 @@ export function gatewayProtocol(protocol, input) {
37
37
  },
38
38
  supportsEffortUpdates: protocol.supportsEffortUpdates,
39
39
  toolUpdates: protocol.toolUpdates,
40
+ namespaces: protocol.namespaces,
40
41
  sanitizer: protocol.sanitizer,
41
42
  stream: {
42
43
  event: protocol.stream.event,
@@ -3,6 +3,10 @@ import type { Tool } from "@opencode/schema/tool";
3
3
  import { Media } from "../../media.js";
4
4
  import type { MediaProtocol } from "../../route/media-protocol.js";
5
5
  import { AIError, type MediaUsage, type ProviderMetadata } from "../../schema/index.js";
6
+ export declare const SafetySetting: Schema.Struct<{
7
+ readonly category: Schema.declare<import("../../schema/options.js").OpenString<"HARM_CATEGORY_CIVIC_INTEGRITY" | "HARM_CATEGORY_DANGEROUS_CONTENT" | "HARM_CATEGORY_HARASSMENT" | "HARM_CATEGORY_HATE_SPEECH" | "HARM_CATEGORY_SEXUALLY_EXPLICIT" | "HARM_CATEGORY_UNSPECIFIED">, import("../../schema/options.js").OpenString<"HARM_CATEGORY_CIVIC_INTEGRITY" | "HARM_CATEGORY_DANGEROUS_CONTENT" | "HARM_CATEGORY_HARASSMENT" | "HARM_CATEGORY_HATE_SPEECH" | "HARM_CATEGORY_SEXUALLY_EXPLICIT" | "HARM_CATEGORY_UNSPECIFIED">>;
8
+ readonly threshold: Schema.declare<import("../../schema/options.js").OpenString<"BLOCK_LOW_AND_ABOVE" | "BLOCK_MEDIUM_AND_ABOVE" | "BLOCK_NONE" | "BLOCK_ONLY_HIGH" | "HARM_BLOCK_THRESHOLD_UNSPECIFIED" | "OFF">, import("../../schema/options.js").OpenString<"BLOCK_LOW_AND_ABOVE" | "BLOCK_MEDIUM_AND_ABOVE" | "BLOCK_NONE" | "BLOCK_ONLY_HIGH" | "HARM_BLOCK_THRESHOLD_UNSPECIFIED" | "OFF">>;
9
+ }>;
6
10
  declare const UsageMetadata: Schema.Struct<{
7
11
  readonly promptTokenCount: Schema.optional<Schema.Number>;
8
12
  readonly candidatesTokenCount: Schema.optional<Schema.Number>;
@@ -2,9 +2,13 @@ import { Effect, Schema } from "effect";
2
2
  import { Media } from "../../media.js";
3
3
  import { Framing } from "../../route/framing.js";
4
4
  import { AIError, ContentPolicyError, ProviderID, tokenUsage, } from "../../schema/index.js";
5
- import { ProviderShared } from "../shared.js";
5
+ import { knownString, ProviderShared } from "../shared.js";
6
6
  import { MediaInput } from "./media-input.js";
7
7
  const PROVIDER = ProviderID.make("google");
8
+ export const SafetySetting = Schema.Struct({
9
+ category: knownString(),
10
+ threshold: knownString(),
11
+ });
8
12
  const UsageMetadata = Schema.Struct({
9
13
  promptTokenCount: Schema.optional(Schema.Number),
10
14
  candidatesTokenCount: Schema.optional(Schema.Number),
@@ -1,4 +1,4 @@
1
- import { Effect, Schema, Stream } from "effect";
1
+ import { Effect, Schema } from "effect";
2
2
  import { AIError, InvalidProviderOutputError, CompactionPart, CompactionResponse, Message, mergeJsonRecords, } from "../../schema/index.js";
3
3
  import { stripEffortUpdates } from "../../effort-updates.js";
4
4
  import { foldToolUpdates } from "../../tool-updates.js";
@@ -58,6 +58,8 @@ const Response = Schema.Struct({
58
58
  role: Schema.Literal("assistant"),
59
59
  content: Schema.Array(Text).check(Schema.isMinLength(1)),
60
60
  }),
61
+ // The system prompt sent as a developer message, echoed back; the next request leads with its own.
62
+ Schema.Struct({ ...MessageFields, role: Schema.Literal("developer"), content: Schema.Unknown }),
61
63
  ])),
62
64
  usage: Schema.optional(Schema.StructWithRest(OpenResponses.OpenResponsesUsage, [JsonObject])),
63
65
  });
@@ -67,6 +69,8 @@ export const make = (adapter, lowerTools) => Effect.fn("ResponsesCompaction.exec
67
69
  // top-level `tools`: after compacting a history whose tools were only in `additional_tools`, small models lost
68
70
  // track of them more often.
69
71
  const folded = foldToolUpdates(stripEffortUpdates(request));
72
+ // The system prompt leads `input` as a developer message, as every step's request does, so `/compact` reads the
73
+ // prefix those requests cached.
70
74
  const native = yield* OpenResponses.lowerConversation(folded, adapter);
71
75
  const generation = OpenResponses.lowerGeneration(request);
72
76
  const tools = folded.tools.length === 0 ? undefined : yield* lowerTools(folded);
@@ -92,13 +96,13 @@ export const make = (adapter, lowerTools) => Effect.fn("ResponsesCompaction.exec
92
96
  auth: route.auth,
93
97
  encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
94
98
  });
95
- const response = yield* RequestExecutor.withTls(executor.execute, request.http?.tls)(ProviderShared.jsonPost({
99
+ const response = yield* RequestExecutor.withTimeout(RequestExecutor.withTls(executor.execute, request.http?.tls), request.timeout)(ProviderShared.jsonPost({
96
100
  url: parts.url,
97
101
  body: parts.bodyText,
98
102
  headers: parts.headers,
99
103
  encoding: request.http?.encoding,
100
104
  }), RequestExecutor.withFetch(request.fetch, options?.http));
101
- const text = yield* RequestExecutor.responseStream(response).pipe(Stream.decodeText(), Stream.runFold(() => "", (text, chunk) => text + chunk));
105
+ const text = yield* RequestExecutor.responseText(response);
102
106
  const invalid = (message, cause) => new AIError({
103
107
  reason: new InvalidProviderOutputError({
104
108
  route: route.id,
@@ -112,7 +116,9 @@ export const make = (adapter, lowerTools) => Effect.fn("ResponsesCompaction.exec
112
116
  if (!result.output.some((item) => item.type === "compaction"))
113
117
  return yield* invalid("Compaction response did not contain a checkpoint");
114
118
  return new CompactionResponse({
115
- replacement: result.output.map((item) => toMessage(item, request.model)),
119
+ replacement: result.output
120
+ .filter((item) => item.type !== "message" || item.role !== "developer")
121
+ .map((item) => toMessage(item, request.model)),
116
122
  usage: OpenResponses.mapUsage(result.usage, OpenResponses.metadataKey(request.model)),
117
123
  });
118
124
  });