@openclaw/ai 2026.7.2-beta.4 → 2026.7.2-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/{anthropic-CrUDIBpM.mjs → anthropic-CQVj3le6.mjs} +53 -19
  2. package/dist/{anthropic-BoTnz8cv.d.mts → anthropic-SrGtwsJu.d.mts} +27 -1
  3. package/dist/{api-registry-BMphkFf1.d.mts → api-registry-DlMgPR39.d.mts} +1 -1
  4. package/dist/{azure-openai-responses-CbrpVeEv.mjs → azure-openai-responses-DIYgsqFM.mjs} +3 -4
  5. package/dist/error-coercion-DgxlWC0n.mjs +15 -0
  6. package/dist/{event-stream-Douf9dob.d.mts → event-stream-YjaPW20U.d.mts} +1 -1
  7. package/dist/event-stream.d.mts +1 -1
  8. package/dist/{tool-schema-json-projection-BwNu3nDi.mjs → github-copilot-headers-BCoBNmL7.mjs} +48 -1
  9. package/dist/{google-Cs62KA7t.mjs → google-f-A8xrae.mjs} +2 -2
  10. package/dist/{google-shared-CMLI-tCZ.mjs → google-shared-J6qvYINH.mjs} +5 -4
  11. package/dist/{google-vertex-B4SD3U0f.mjs → google-vertex-D3yMVXIY.mjs} +2 -2
  12. package/dist/{host-WvWBo4h8.d.mts → host-B9GUmcra.d.mts} +2 -2
  13. package/dist/index.d.mts +7 -7
  14. package/dist/index.mjs +2 -2
  15. package/dist/internal/anthropic.d.mts +15 -11
  16. package/dist/internal/anthropic.mjs +4 -4
  17. package/dist/internal/openai.d.mts +2 -1
  18. package/dist/internal/openai.mjs +4 -6
  19. package/dist/internal/runtime.d.mts +8 -32
  20. package/dist/internal/runtime.mjs +2 -3
  21. package/dist/internal/shared.d.mts +13 -8
  22. package/dist/internal/shared.mjs +2 -2
  23. package/dist/{mistral-D5Ps7Led.mjs → mistral-CKV-TOQj.mjs} +4 -3
  24. package/dist/number-coercion-DvG7SNMg.mjs +129 -0
  25. package/dist/{openai-CoGicoDt.d.mts → openai-BPor_3WI.d.mts} +35 -9
  26. package/dist/{openai-responses-shared-CzCurmY1.mjs → openai-D3PD6PE-.mjs} +1771 -745
  27. package/dist/{openai-chatgpt-responses-h0o5yV8Y.mjs → openai-chatgpt-responses-CedIj0hk.mjs} +19 -20
  28. package/dist/{openai-completions-exO8NFQf.mjs → openai-completions-CiSutyu0.mjs} +366 -227
  29. package/dist/openai-prompt-cache-2uo_1OR1.d.mts +7 -0
  30. package/dist/openai-prompt-cache-mZTCdRPo.mjs +12 -0
  31. package/dist/prompt-cache-stability-Cwcjv_fx.d.mts +13 -0
  32. package/dist/{provider-error-C4VvV_3t.mjs → provider-error-apVOZI6G.mjs} +8 -2
  33. package/dist/providers.d.mts +3 -2
  34. package/dist/providers.mjs +10 -9
  35. package/dist/{system-prompt-cache-boundary-CbHeV4_l.mjs → shared-CdjNZd35.mjs} +117 -9
  36. package/dist/{src-CXno1H5g.mjs → src-QkygScBs.mjs} +23 -4
  37. package/dist/stream-first-event-timeout-C3OgBjIk.mjs +12294 -0
  38. package/dist/stream-first-event-timeout-DvDeSucC.d.mts +29 -0
  39. package/dist/transport-stream-shared-BbMELSI4.mjs +297 -0
  40. package/dist/transports.d.mts +105 -102
  41. package/dist/transports.mjs +334 -1966
  42. package/dist/{types-AFwwWium.d.mts → types-bzp5k29J.d.mts} +7 -0
  43. package/dist/types.d.mts +5 -5
  44. package/dist/types.mjs +2 -2
  45. package/dist/{validation-sxvxC8J-.d.mts → validation-B-j7cOYp.d.mts} +1 -1
  46. package/dist/validation.d.mts +1 -1
  47. package/package.json +1 -2
  48. package/dist/azure-openai-responses-client-compat-C7K7QfUE.mjs +0 -62
  49. package/dist/github-copilot-headers-BsH5cqGj.mjs +0 -48
  50. package/dist/model-utils-1GiZ2_rr.mjs +0 -64
  51. package/dist/openai-responses-BHpmtUKo.mjs +0 -136
  52. package/dist/openai-tool-projection-ITOU9bG1.mjs +0 -200
  53. package/dist/reasoning-tag-text-partitioner-BlVe67g6.mjs +0 -400
  54. package/dist/stream-first-event-timeout-DP4xEyBY.mjs +0 -150
  55. package/npm-shrinkwrap.json +0 -638
@@ -45,6 +45,11 @@ interface ProviderResponse {
45
45
  interface StreamOptions {
46
46
  temperature?: number;
47
47
  maxTokens?: number;
48
+ /**
49
+ * Optional JSON Schema for the generated response. Providers that support
50
+ * constrained decoding map it to their native request shape; others ignore it.
51
+ */
52
+ responseFormat?: Record<string, unknown>;
48
53
  /**
49
54
  * Stop sequences forwarded to providers that support them. Providers map this
50
55
  * to their native request field, such as OpenAI `stop` or Anthropic
@@ -427,6 +432,8 @@ interface OpenAICompletionsCompat {
427
432
  zaiToolStream?: boolean;
428
433
  /** Whether the provider supports the `strict` field in tool definitions. Default: true. */
429
434
  supportsStrictMode?: boolean;
435
+ /** Whether the provider supports JSON Schema through `response_format`. Default: false for unknown compatible endpoints. */
436
+ supportsJsonSchemaResponseFormat?: boolean;
430
437
  /** Cache control convention for prompt caching. "anthropic" applies Anthropic-style `cache_control` markers to the system prompt, last tool definition, and last user/assistant text content. */
431
438
  cacheControlFormat?: "anthropic";
432
439
  /** Whether to send known session-affinity headers (`session_id`, `x-client-request-id`, `x-session-affinity`) from `options.sessionId` when caching is enabled. Default: false. */
package/dist/types.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { a as resolveClaudeFable5ModelIdentity, c as resolveClaudeNativeThinkingLevelMap, d as supportsClaudeNativeMaxEffort, f as supportsClaudeNativeXhighEffort, i as requiresClaudeMandatoryAdaptiveThinking, l as resolveClaudeSonnet5ModelIdentity, n as CLAUDE_SONNET_5_THINKING_PROFILE, o as resolveClaudeModelIdentity, r as requiresClaudeDefaultSampling, s as resolveClaudeMythos5ModelIdentity, t as CLAUDE_FABLE_5_THINKING_PROFILE, u as supportsClaudeAdaptiveThinking } from "./anthropic-BoTnz8cv.mjs";
1
+ import { a as requiresClaudeMandatoryAdaptiveThinking, c as resolveClaudeMythos5ModelIdentity, d as resolveClaudeSonnet5ModelIdentity, f as supportsClaude1MContext, g as supportsClaudeNativeXhighEffort, h as supportsClaudeNativeMaxEffort, i as requiresClaudeDefaultSampling, l as resolveClaudeNativeThinkingLevelMap, m as supportsClaudeFastMode, n as CLAUDE_OPUS_5_THINKING_PROFILE, o as resolveClaudeFable5ModelIdentity, p as supportsClaudeAdaptiveThinking, r as CLAUDE_SONNET_5_THINKING_PROFILE, s as resolveClaudeModelIdentity, t as CLAUDE_FABLE_5_THINKING_PROFILE, u as resolveClaudeOpus5ModelIdentity } from "./anthropic-SrGtwsJu.mjs";
2
2
  import { a as extractDiagnosticError, i as createAssistantMessageDiagnostic, n as DiagnosticErrorInfo, o as formatThrownValue, r as appendAssistantMessageDiagnostic, t as AssistantMessageDiagnostic } from "./diagnostics-BaTA9eVl.mjs";
3
- import { $ as VercelGatewayRouting, A as OpenRouterRouting, B as TextContent, C as KnownImagesProvider, D as ModelThinkingLevel, E as Model, F as SimpleStreamOptions, G as ThinkingLevelMap, H as ThinkingBudgets, I as StopReason, J as ToolResultMessage, K as Tool, L as StreamFn, M as ProviderImagesOptions, N as ProviderResponse, O as OpenAICompletionsCompat, P as ProviderStreamOptions, Q as ValidateToolArgumentsFn, R as StreamFunction, S as KnownImagesApi, T as Message, U as ThinkingContent, V as TextSignatureV1, W as ThinkingLevel, X as Usage, Y as Transport, Z as UserMessage, _ as ImagesOptions, a as AssistantMessageEvent, b as ImagesStopReason, c as CacheRetention, d as ImageContent, f as ImagesApi, g as ImagesModel, h as ImagesInputContent, i as AssistantMessage, j as Provider, k as OpenAIResponsesCompat, l as CompleteSimpleFn, m as ImagesFunction, n as Api, o as AssistantMessageEventStreamContract, p as ImagesContext, q as ToolCall, r as AssistantImages, s as AssistantMessageEventStreamLike, t as AnthropicMessagesCompat, u as Context, v as ImagesOutputContent, w as MaybePromise, x as KnownApi, y as ImagesProvider, z as StreamOptions } from "./types-AFwwWium.mjs";
4
- import { n as EventStream, r as createAssistantMessageEventStream, t as AssistantMessageEventStream } from "./event-stream-Douf9dob.mjs";
5
- import { n as validateToolCall, t as validateToolArguments } from "./validation-sxvxC8J-.mjs";
6
- export { AnthropicMessagesCompat, Api, AssistantImages, AssistantMessage, AssistantMessageDiagnostic, AssistantMessageEvent, AssistantMessageEventStream, AssistantMessageEventStreamContract, AssistantMessageEventStreamLike, CLAUDE_FABLE_5_THINKING_PROFILE, CLAUDE_SONNET_5_THINKING_PROFILE, CacheRetention, CompleteSimpleFn, Context, DiagnosticErrorInfo, EventStream, ImageContent, ImagesApi, ImagesContext, ImagesFunction, ImagesInputContent, ImagesModel, ImagesOptions, ImagesOutputContent, ImagesProvider, ImagesStopReason, KnownApi, KnownImagesApi, KnownImagesProvider, MaybePromise, Message, Model, ModelThinkingLevel, OpenAICompletionsCompat, OpenAIResponsesCompat, OpenRouterRouting, Provider, ProviderImagesOptions, ProviderResponse, ProviderStreamOptions, SimpleStreamOptions, StopReason, StreamFn, StreamFunction, StreamOptions, TextContent, TextSignatureV1, ThinkingBudgets, ThinkingContent, ThinkingLevel, ThinkingLevelMap, Tool, ToolCall, ToolResultMessage, Transport, Usage, UserMessage, ValidateToolArgumentsFn, VercelGatewayRouting, appendAssistantMessageDiagnostic, createAssistantMessageDiagnostic, createAssistantMessageEventStream, extractDiagnosticError, formatThrownValue, requiresClaudeDefaultSampling, requiresClaudeMandatoryAdaptiveThinking, resolveClaudeFable5ModelIdentity, resolveClaudeModelIdentity, resolveClaudeMythos5ModelIdentity, resolveClaudeNativeThinkingLevelMap, resolveClaudeSonnet5ModelIdentity, supportsClaudeAdaptiveThinking, supportsClaudeNativeMaxEffort, supportsClaudeNativeXhighEffort, validateToolArguments, validateToolCall };
3
+ import { $ as VercelGatewayRouting, A as OpenRouterRouting, B as TextContent, C as KnownImagesProvider, D as ModelThinkingLevel, E as Model, F as SimpleStreamOptions, G as ThinkingLevelMap, H as ThinkingBudgets, I as StopReason, J as ToolResultMessage, K as Tool, L as StreamFn, M as ProviderImagesOptions, N as ProviderResponse, O as OpenAICompletionsCompat, P as ProviderStreamOptions, Q as ValidateToolArgumentsFn, R as StreamFunction, S as KnownImagesApi, T as Message, U as ThinkingContent, V as TextSignatureV1, W as ThinkingLevel, X as Usage, Y as Transport, Z as UserMessage, _ as ImagesOptions, a as AssistantMessageEvent, b as ImagesStopReason, c as CacheRetention, d as ImageContent, f as ImagesApi, g as ImagesModel, h as ImagesInputContent, i as AssistantMessage, j as Provider, k as OpenAIResponsesCompat, l as CompleteSimpleFn, m as ImagesFunction, n as Api, o as AssistantMessageEventStreamContract, p as ImagesContext, q as ToolCall, r as AssistantImages, s as AssistantMessageEventStreamLike, t as AnthropicMessagesCompat, u as Context, v as ImagesOutputContent, w as MaybePromise, x as KnownApi, y as ImagesProvider, z as StreamOptions } from "./types-bzp5k29J.mjs";
4
+ import { n as EventStream, r as createAssistantMessageEventStream, t as AssistantMessageEventStream } from "./event-stream-YjaPW20U.mjs";
5
+ import { n as validateToolCall, t as validateToolArguments } from "./validation-B-j7cOYp.mjs";
6
+ export { AnthropicMessagesCompat, Api, AssistantImages, AssistantMessage, AssistantMessageDiagnostic, AssistantMessageEvent, AssistantMessageEventStream, AssistantMessageEventStreamContract, AssistantMessageEventStreamLike, CLAUDE_FABLE_5_THINKING_PROFILE, CLAUDE_OPUS_5_THINKING_PROFILE, CLAUDE_SONNET_5_THINKING_PROFILE, CacheRetention, CompleteSimpleFn, Context, DiagnosticErrorInfo, EventStream, ImageContent, ImagesApi, ImagesContext, ImagesFunction, ImagesInputContent, ImagesModel, ImagesOptions, ImagesOutputContent, ImagesProvider, ImagesStopReason, KnownApi, KnownImagesApi, KnownImagesProvider, MaybePromise, Message, Model, ModelThinkingLevel, OpenAICompletionsCompat, OpenAIResponsesCompat, OpenRouterRouting, Provider, ProviderImagesOptions, ProviderResponse, ProviderStreamOptions, SimpleStreamOptions, StopReason, StreamFn, StreamFunction, StreamOptions, TextContent, TextSignatureV1, ThinkingBudgets, ThinkingContent, ThinkingLevel, ThinkingLevelMap, Tool, ToolCall, ToolResultMessage, Transport, Usage, UserMessage, ValidateToolArgumentsFn, VercelGatewayRouting, appendAssistantMessageDiagnostic, createAssistantMessageDiagnostic, createAssistantMessageEventStream, extractDiagnosticError, formatThrownValue, requiresClaudeDefaultSampling, requiresClaudeMandatoryAdaptiveThinking, resolveClaudeFable5ModelIdentity, resolveClaudeModelIdentity, resolveClaudeMythos5ModelIdentity, resolveClaudeNativeThinkingLevelMap, resolveClaudeOpus5ModelIdentity, resolveClaudeSonnet5ModelIdentity, supportsClaude1MContext, supportsClaudeAdaptiveThinking, supportsClaudeFastMode, supportsClaudeNativeMaxEffort, supportsClaudeNativeXhighEffort, validateToolArguments, validateToolCall };
package/dist/types.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { a as resolveClaudeFable5ModelIdentity, c as resolveClaudeNativeThinkingLevelMap, d as supportsClaudeNativeMaxEffort, f as supportsClaudeNativeXhighEffort, i as requiresClaudeMandatoryAdaptiveThinking, l as resolveClaudeSonnet5ModelIdentity, n as CLAUDE_SONNET_5_THINKING_PROFILE, o as resolveClaudeModelIdentity, r as requiresClaudeDefaultSampling, s as resolveClaudeMythos5ModelIdentity, t as CLAUDE_FABLE_5_THINKING_PROFILE, u as supportsClaudeAdaptiveThinking } from "./src-CXno1H5g.mjs";
1
+ import { a as requiresClaudeMandatoryAdaptiveThinking, c as resolveClaudeMythos5ModelIdentity, d as resolveClaudeSonnet5ModelIdentity, f as supportsClaude1MContext, g as supportsClaudeNativeXhighEffort, h as supportsClaudeNativeMaxEffort, i as requiresClaudeDefaultSampling, l as resolveClaudeNativeThinkingLevelMap, m as supportsClaudeFastMode, n as CLAUDE_OPUS_5_THINKING_PROFILE, o as resolveClaudeFable5ModelIdentity, p as supportsClaudeAdaptiveThinking, r as CLAUDE_SONNET_5_THINKING_PROFILE, s as resolveClaudeModelIdentity, t as CLAUDE_FABLE_5_THINKING_PROFILE, u as resolveClaudeOpus5ModelIdentity } from "./src-QkygScBs.mjs";
2
2
  import { i as formatThrownValue, n as createAssistantMessageDiagnostic, r as extractDiagnosticError, t as appendAssistantMessageDiagnostic } from "./diagnostics-COpOtRwq.mjs";
3
3
  import { n as EventStream, r as createAssistantMessageEventStream, t as AssistantMessageEventStream } from "./event-stream-D8n2uFee.mjs";
4
4
  import { n as validateToolCall, t as validateToolArguments } from "./validation-DAa_yFOM.mjs";
5
- export { AssistantMessageEventStream, CLAUDE_FABLE_5_THINKING_PROFILE, CLAUDE_SONNET_5_THINKING_PROFILE, EventStream, appendAssistantMessageDiagnostic, createAssistantMessageDiagnostic, createAssistantMessageEventStream, extractDiagnosticError, formatThrownValue, requiresClaudeDefaultSampling, requiresClaudeMandatoryAdaptiveThinking, resolveClaudeFable5ModelIdentity, resolveClaudeModelIdentity, resolveClaudeMythos5ModelIdentity, resolveClaudeNativeThinkingLevelMap, resolveClaudeSonnet5ModelIdentity, supportsClaudeAdaptiveThinking, supportsClaudeNativeMaxEffort, supportsClaudeNativeXhighEffort, validateToolArguments, validateToolCall };
5
+ export { AssistantMessageEventStream, CLAUDE_FABLE_5_THINKING_PROFILE, CLAUDE_OPUS_5_THINKING_PROFILE, CLAUDE_SONNET_5_THINKING_PROFILE, EventStream, appendAssistantMessageDiagnostic, createAssistantMessageDiagnostic, createAssistantMessageEventStream, extractDiagnosticError, formatThrownValue, requiresClaudeDefaultSampling, requiresClaudeMandatoryAdaptiveThinking, resolveClaudeFable5ModelIdentity, resolveClaudeModelIdentity, resolveClaudeMythos5ModelIdentity, resolveClaudeNativeThinkingLevelMap, resolveClaudeOpus5ModelIdentity, resolveClaudeSonnet5ModelIdentity, supportsClaude1MContext, supportsClaudeAdaptiveThinking, supportsClaudeFastMode, supportsClaudeNativeMaxEffort, supportsClaudeNativeXhighEffort, validateToolArguments, validateToolCall };
@@ -1,4 +1,4 @@
1
- import { K as Tool, q as ToolCall } from "./types-AFwwWium.mjs";
1
+ import { K as Tool, q as ToolCall } from "./types-bzp5k29J.mjs";
2
2
 
3
3
  //#region packages/llm-core/src/validation.d.ts
4
4
  /** Finds the target tool and validates/coerces a model-emitted tool call. */
@@ -1,2 +1,2 @@
1
- import { n as validateToolCall, t as validateToolArguments } from "./validation-sxvxC8J-.mjs";
1
+ import { n as validateToolCall, t as validateToolArguments } from "./validation-B-j7cOYp.mjs";
2
2
  export { validateToolArguments, validateToolCall };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/ai",
3
- "version": "2026.7.2-beta.4",
3
+ "version": "2026.7.2-beta.5",
4
4
  "description": "Reusable model provider adapters and streaming runtime from OpenClaw",
5
5
  "keywords": [
6
6
  "ai",
@@ -24,7 +24,6 @@
24
24
  },
25
25
  "files": [
26
26
  "dist",
27
- "npm-shrinkwrap.json",
28
27
  "LICENSE",
29
28
  "README.md"
30
29
  ],
@@ -1,62 +0,0 @@
1
- //#region packages/ai/src/providers/azure-deployment-map.ts
2
- /** Parses AZURE_OPENAI_DEPLOYMENT_MAP-style model=deployment entries. */
3
- function parseAzureDeploymentNameMap(value) {
4
- const map = /* @__PURE__ */ new Map();
5
- if (!value) return map;
6
- for (const entry of value.split(",")) {
7
- const trimmed = entry.trim();
8
- if (!trimmed) continue;
9
- const separator = trimmed.indexOf("=");
10
- if (separator <= 0) continue;
11
- const modelId = trimmed.slice(0, separator).trim();
12
- const deploymentName = trimmed.slice(separator + 1).trim();
13
- if (!modelId || !deploymentName) continue;
14
- map.set(modelId, deploymentName);
15
- }
16
- return map;
17
- }
18
- let cachedDeploymentLookup;
19
- function getDeploymentLookup(source) {
20
- const cached = cachedDeploymentLookup;
21
- if (cached && cached.source === source) return cached;
22
- const exact = parseAzureDeploymentNameMap(source);
23
- const folded = /* @__PURE__ */ new Map();
24
- for (const [modelId, deploymentName] of exact) folded.set(modelId.toLowerCase(), deploymentName);
25
- cachedDeploymentLookup = {
26
- source,
27
- exact,
28
- folded
29
- };
30
- return cachedDeploymentLookup;
31
- }
32
- /**
33
- * Resolves the Azure deployment name for a model id, falling back to the model id.
34
- *
35
- * An exact-case match always wins, so configs that intentionally distinguish keys by
36
- * case keep their exact mappings; a case-insensitive match is only used as a fallback
37
- * (e.g. `GPT-4o` against a `gpt-4o=...` map) to avoid 404s from casing differences.
38
- */
39
- function resolveAzureDeploymentNameFromMap(params) {
40
- const { exact, folded } = getDeploymentLookup(params.deploymentMap);
41
- return exact.get(params.modelId) ?? folded.get(params.modelId.toLowerCase()) ?? params.modelId;
42
- }
43
- //#endregion
44
- //#region packages/ai/src/providers/azure-openai-responses-client-compat.ts
45
- function isTraditionalAzureOpenAIHost(hostname) {
46
- return hostname.endsWith(".openai.azure.com") || hostname.endsWith(".cognitiveservices.azure.com");
47
- }
48
- function isOpenAICompatibleAzureResponsesBaseUrl(baseUrl) {
49
- let url;
50
- try {
51
- url = new URL(baseUrl);
52
- } catch {
53
- return false;
54
- }
55
- if (isTraditionalAzureOpenAIHost(url.hostname)) return false;
56
- const hostname = url.hostname.toLowerCase();
57
- if (!(hostname.endsWith(".services.ai.azure.com") || hostname.endsWith(".api.cognitive.microsoft.com"))) return false;
58
- const normalizedPath = url.pathname.replace(/\/+$/, "");
59
- return normalizedPath === "/openai/v1" || normalizedPath.endsWith("/openai/v1");
60
- }
61
- //#endregion
62
- export { resolveAzureDeploymentNameFromMap as i, isTraditionalAzureOpenAIHost as n, parseAzureDeploymentNameMap as r, isOpenAICompatibleAzureResponsesBaseUrl as t };
@@ -1,48 +0,0 @@
1
- //#region packages/ai/src/providers/cache-retention.ts
2
- /**
3
- * Resolve cache retention preference.
4
- * Defaults to "short" and uses OPENCLAW_CACHE_RETENTION for backward compatibility.
5
- */
6
- function resolveCacheRetention(cacheRetention) {
7
- if (cacheRetention) return cacheRetention;
8
- if (typeof process !== "undefined" && process.env.OPENCLAW_CACHE_RETENTION === "long") return "long";
9
- return "short";
10
- }
11
- //#endregion
12
- //#region packages/ai/src/providers/cloudflare.ts
13
- function isCloudflareProvider(provider) {
14
- return provider === "cloudflare-workers-ai" || provider === "cloudflare-ai-gateway";
15
- }
16
- /** Substitute `{VAR}` placeholders in a Cloudflare baseUrl from process.env. */
17
- function resolveCloudflareBaseUrl(model) {
18
- const url = model.baseUrl;
19
- if (!url.includes("{")) return url;
20
- return url.replace(/\{([A-Z_][A-Z0-9_]*)\}/g, (_match, name) => {
21
- const value = process.env[name];
22
- if (!value) throw new Error(`${name} is required for provider ${model.provider} but is not set.`);
23
- return value;
24
- });
25
- }
26
- //#endregion
27
- //#region packages/ai/src/providers/github-copilot-headers.ts
28
- function inferCopilotInitiator(messages) {
29
- const last = messages[messages.length - 1];
30
- return last && last.role !== "user" ? "agent" : "user";
31
- }
32
- function hasCopilotVisionInput(messages) {
33
- return messages.some((msg) => {
34
- if (msg.role === "user" && Array.isArray(msg.content)) return msg.content.some((c) => c.type === "image");
35
- if (msg.role === "toolResult" && Array.isArray(msg.content)) return msg.content.some((c) => c.type === "image");
36
- return false;
37
- });
38
- }
39
- function buildCopilotDynamicHeaders(params) {
40
- const headers = {
41
- "X-Initiator": inferCopilotInitiator(params.messages),
42
- "Openai-Intent": "conversation-edits"
43
- };
44
- if (params.hasImages) headers["Copilot-Vision-Request"] = "true";
45
- return headers;
46
- }
47
- //#endregion
48
- export { resolveCacheRetention as a, resolveCloudflareBaseUrl as i, hasCopilotVisionInput as n, isCloudflareProvider as r, buildCopilotDynamicHeaders as t };
@@ -1,64 +0,0 @@
1
- import { c as resolveClaudeNativeThinkingLevelMap, i as requiresClaudeMandatoryAdaptiveThinking } from "./src-CXno1H5g.mjs";
2
- //#region packages/ai/src/model-utils.ts
3
- /** Calculates and stores model cost fields from token usage and per-million pricing. */
4
- function calculateCost(model, usage) {
5
- const cacheWrite1h = Math.min(usage.cacheWrite, Math.max(0, usage.cacheWrite1h ?? 0));
6
- const cacheWrite5m = usage.cacheWrite - cacheWrite1h;
7
- usage.cost.input = model.cost.input / 1e6 * usage.input;
8
- usage.cost.output = model.cost.output / 1e6 * usage.output;
9
- usage.cost.cacheRead = model.cost.cacheRead / 1e6 * usage.cacheRead;
10
- usage.cost.cacheWrite = (model.cost.cacheWrite * cacheWrite5m + model.cost.input * 2 * cacheWrite1h) / 1e6;
11
- usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
12
- return usage.cost;
13
- }
14
- /** Replaces the catalog estimate when the provider reports an authoritative billed total. */
15
- function applyProviderReportedUsageCost(usage, reportedCost) {
16
- if (typeof reportedCost !== "number" || !Number.isFinite(reportedCost) || reportedCost < 0) return;
17
- usage.cost.total = reportedCost;
18
- usage.cost.totalOrigin = "provider-billed";
19
- }
20
- const EXTENDED_THINKING_LEVELS = [
21
- "off",
22
- "minimal",
23
- "low",
24
- "medium",
25
- "high",
26
- "xhigh",
27
- "max"
28
- ];
29
- function resolveThinkingLevelMap(model) {
30
- return model.api === "anthropic-messages" ? resolveClaudeNativeThinkingLevelMap(model) ?? model.thinkingLevelMap : model.thinkingLevelMap;
31
- }
32
- /** Returns thinking levels exposed by a reasoning-capable model. */
33
- function getSupportedThinkingLevels(model) {
34
- const mandatoryAdaptiveContract = model.api === "anthropic-messages" && requiresClaudeMandatoryAdaptiveThinking(model);
35
- if (!model.reasoning && !mandatoryAdaptiveContract) return ["off"];
36
- const thinkingLevelMap = resolveThinkingLevelMap(model);
37
- return EXTENDED_THINKING_LEVELS.filter((level) => {
38
- const mapped = thinkingLevelMap?.[level];
39
- if (mapped === null) return false;
40
- if (level === "xhigh" || level === "max") return mapped !== void 0;
41
- return true;
42
- });
43
- }
44
- /** Clamps a requested thinking level to the closest supported level for a model. */
45
- function clampThinkingLevel(model, level) {
46
- const availableLevels = getSupportedThinkingLevels(model);
47
- if (availableLevels.includes(level)) return level;
48
- const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);
49
- if (requestedIndex === -1) return availableLevels[0] ?? "off";
50
- const thinkingLevelMap = resolveThinkingLevelMap(model);
51
- if ((level === "xhigh" || level === "max") && thinkingLevelMap?.[level] === null) {
52
- for (const candidate of EXTENDED_THINKING_LEVELS.slice(0, requestedIndex).toReversed()) if (availableLevels.includes(candidate)) return candidate;
53
- }
54
- for (const candidate of EXTENDED_THINKING_LEVELS.slice(requestedIndex)) if (availableLevels.includes(candidate)) return candidate;
55
- for (const candidate of EXTENDED_THINKING_LEVELS.slice(0, requestedIndex).toReversed()) if (availableLevels.includes(candidate)) return candidate;
56
- return availableLevels[0] ?? "off";
57
- }
58
- /** Compares model identity by provider and id. */
59
- function modelsAreEqual(a, b) {
60
- if (!a || !b) return false;
61
- return a.id === b.id && a.provider === b.provider;
62
- }
63
- //#endregion
64
- export { modelsAreEqual as a, getSupportedThinkingLevels as i, calculateCost as n, clampThinkingLevel as r, applyProviderReportedUsageCost as t };
@@ -1,136 +0,0 @@
1
- import { n as getEnvApiKey, r as __exportAll } from "./env-api-keys-DrgeBuva.mjs";
2
- import { t as AssistantMessageEventStream } from "./event-stream-D8n2uFee.mjs";
3
- import { n as getAiTransportHost } from "./host-XYGZcgO8.mjs";
4
- import { D as buildBaseOptions } from "./system-prompt-cache-boundary-CbHeV4_l.mjs";
5
- import { a as resolveCacheRetention, i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, r as isCloudflareProvider, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-BsH5cqGj.mjs";
6
- import { L as supportsOpenAITemperature, a as resolveResponsesReasoningEffort, n as convertResponsesMessages, o as runResponsesStreamLifecycle, r as createResponsesAssistantOutput, t as applyCommonResponsesParams } from "./openai-responses-shared-CzCurmY1.mjs";
7
- import { a as clampOpenAIPromptCacheKey } from "./openai-tool-projection-ITOU9bG1.mjs";
8
- import OpenAI from "openai";
9
- //#region packages/ai/src/providers/openai-responses.ts
10
- var openai_responses_exports = /* @__PURE__ */ __exportAll({
11
- streamOpenAIResponses: () => streamOpenAIResponses,
12
- streamSimpleOpenAIResponses: () => streamSimpleOpenAIResponses
13
- });
14
- const OPENAI_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "opencode"]);
15
- function getCompat(model) {
16
- return {
17
- sendSessionIdHeader: model.compat?.sendSessionIdHeader ?? true,
18
- supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true
19
- };
20
- }
21
- function getPromptCacheRetention(compat, cacheRetention) {
22
- return cacheRetention === "long" && compat.supportsLongCacheRetention ? "24h" : void 0;
23
- }
24
- function formatOpenAIResponsesError(error) {
25
- if (error instanceof Error) {
26
- const status = error.status;
27
- const statusCode = typeof status === "number" ? status : void 0;
28
- if (statusCode !== void 0) return `OpenAI API error (${statusCode}): ${error.message}`;
29
- return error.message;
30
- }
31
- try {
32
- return JSON.stringify(error);
33
- } catch {
34
- return String(error);
35
- }
36
- }
37
- /**
38
- * Generate function for OpenAI Responses API
39
- */
40
- const streamOpenAIResponses = (model, context, options) => {
41
- const stream = new AssistantMessageEventStream();
42
- runResponsesStreamLifecycle({
43
- stream,
44
- model,
45
- output: createResponsesAssistantOutput(model),
46
- options,
47
- createClient: () => {
48
- const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
49
- const cacheSessionId = resolveCacheRetention(options?.cacheRetention) === "none" ? void 0 : options?.sessionId;
50
- return createClient(model, context, apiKey, options?.headers, cacheSessionId);
51
- },
52
- buildParams: () => buildParams(model, context, options),
53
- processStreamOptions: {
54
- serviceTier: options?.serviceTier,
55
- applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model)
56
- },
57
- formatError: formatOpenAIResponsesError
58
- });
59
- return stream;
60
- };
61
- const streamSimpleOpenAIResponses = (model, context, options) => {
62
- const apiKey = options?.apiKey || getEnvApiKey(model.provider);
63
- if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
64
- const base = buildBaseOptions(model, options, apiKey);
65
- return streamOpenAIResponses(model, context, {
66
- ...base,
67
- reasoningEffort: resolveResponsesReasoningEffort(model, options?.reasoning),
68
- replayResponsesItemIds: options?.replayResponsesItemIds
69
- });
70
- };
71
- function createClient(model, context, apiKey, optionsHeaders, sessionId) {
72
- if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
73
- const compat = getCompat(model);
74
- const headers = { ...model.headers };
75
- if (model.provider === "github-copilot") {
76
- const hasImages = hasCopilotVisionInput(context.messages);
77
- const copilotHeaders = buildCopilotDynamicHeaders({
78
- messages: context.messages,
79
- hasImages
80
- });
81
- Object.assign(headers, copilotHeaders);
82
- }
83
- if (sessionId) {
84
- if (compat.sendSessionIdHeader) headers.session_id = sessionId;
85
- headers["x-client-request-id"] = sessionId;
86
- }
87
- if (optionsHeaders) Object.assign(headers, optionsHeaders);
88
- const defaultHeaders = model.provider === "cloudflare-ai-gateway" ? {
89
- ...headers,
90
- Authorization: headers.Authorization ?? null,
91
- "cf-aig-authorization": `Bearer ${apiKey}`
92
- } : headers;
93
- return new OpenAI({
94
- apiKey,
95
- baseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,
96
- dangerouslyAllowBrowser: true,
97
- defaultHeaders,
98
- fetch: getAiTransportHost().buildModelFetch(model)
99
- });
100
- }
101
- function buildParams(model, context, options) {
102
- const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, { replayResponsesItemIds: options?.replayResponsesItemIds ?? false });
103
- const cacheRetention = resolveCacheRetention(options?.cacheRetention);
104
- const compat = getCompat(model);
105
- const params = {
106
- model: model.id,
107
- input: messages,
108
- stream: true,
109
- prompt_cache_key: cacheRetention === "none" ? void 0 : clampOpenAIPromptCacheKey(options?.promptCacheKey ?? options?.sessionId),
110
- prompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),
111
- store: false
112
- };
113
- if (options?.maxTokens) params.max_output_tokens = options?.maxTokens;
114
- if (options?.temperature !== void 0 && supportsOpenAITemperature(model)) params.temperature = options?.temperature;
115
- if (options?.serviceTier !== void 0) params.service_tier = options.serviceTier;
116
- applyCommonResponsesParams(params, model, context, options, { setDefaultReasoningOff: model.provider !== "github-copilot" });
117
- return params;
118
- }
119
- function getServiceTierCostMultiplier(model, serviceTier) {
120
- switch (serviceTier) {
121
- case "flex": return .5;
122
- case "priority": return model.id === "gpt-5.5" ? 2.5 : 2;
123
- default: return 1;
124
- }
125
- }
126
- function applyServiceTierPricing(usage, serviceTier, model) {
127
- const multiplier = getServiceTierCostMultiplier(model, serviceTier);
128
- if (multiplier === 1) return;
129
- usage.cost.input *= multiplier;
130
- usage.cost.output *= multiplier;
131
- usage.cost.cacheRead *= multiplier;
132
- usage.cost.cacheWrite *= multiplier;
133
- usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
134
- }
135
- //#endregion
136
- export { streamOpenAIResponses as n, streamSimpleOpenAIResponses as r, openai_responses_exports as t };
@@ -1,200 +0,0 @@
1
- import { T as isRecord } from "./system-prompt-cache-boundary-CbHeV4_l.mjs";
2
- import { t as projectRuntimeToolInputSchema } from "./tool-schema-json-projection-BwNu3nDi.mjs";
3
- //#region packages/ai/src/providers/openai-prompt-cache.ts
4
- /** Maximum prompt cache key length accepted by OpenAI-compatible request metadata. */
5
- const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
6
- /** Truncates a prompt cache key by Unicode code point count. */
7
- function clampOpenAIPromptCacheKey(key) {
8
- if (key === void 0) return;
9
- const chars = Array.from(key);
10
- if (chars.length <= 64) return key;
11
- return chars.slice(0, 64).join("");
12
- }
13
- //#endregion
14
- //#region packages/ai/src/providers/openai-tool-projection.ts
15
- function unreadableToolDiagnostic(toolIndex) {
16
- return {
17
- toolIndex,
18
- violations: [`tool[${toolIndex}] is unreadable`]
19
- };
20
- }
21
- /** Snapshots direct/custom tool descriptors before OpenAI payload construction. */
22
- function projectOpenAITools(tools) {
23
- let inputToolCount;
24
- try {
25
- inputToolCount = tools.length;
26
- } catch {
27
- return {
28
- inputToolCount: 0,
29
- tools: [],
30
- diagnostics: [unreadableToolDiagnostic(0)]
31
- };
32
- }
33
- const projectedTools = [];
34
- const diagnostics = [];
35
- for (let toolIndex = 0; toolIndex < inputToolCount; toolIndex += 1) {
36
- let tool;
37
- try {
38
- const candidate = tools[toolIndex];
39
- if (!candidate) {
40
- diagnostics.push(unreadableToolDiagnostic(toolIndex));
41
- continue;
42
- }
43
- tool = candidate;
44
- } catch {
45
- diagnostics.push(unreadableToolDiagnostic(toolIndex));
46
- continue;
47
- }
48
- let name;
49
- try {
50
- name = tool.name;
51
- } catch {
52
- diagnostics.push({
53
- toolIndex,
54
- violations: [`tool[${toolIndex}].name is unreadable`]
55
- });
56
- continue;
57
- }
58
- if (typeof name !== "string" || !name) {
59
- diagnostics.push({
60
- toolIndex,
61
- violations: [`tool[${toolIndex}].name is empty`]
62
- });
63
- continue;
64
- }
65
- let parameters;
66
- try {
67
- parameters = tool.parameters;
68
- } catch {
69
- diagnostics.push({
70
- toolIndex,
71
- toolName: name,
72
- violations: [`${name}.parameters is unreadable`]
73
- });
74
- continue;
75
- }
76
- const schemaProjection = projectRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`);
77
- if (!isRecord(schemaProjection.schema) || schemaProjection.violations.length > 0) {
78
- diagnostics.push({
79
- toolIndex,
80
- toolName: name,
81
- violations: schemaProjection.violations.length > 0 ? schemaProjection.violations : [`${name}.parameters must be a JSON object schema`]
82
- });
83
- continue;
84
- }
85
- let descriptionValue;
86
- try {
87
- descriptionValue = tool.description;
88
- } catch {}
89
- const description = typeof descriptionValue === "string" ? descriptionValue : void 0;
90
- projectedTools.push({
91
- toolIndex,
92
- name,
93
- ...description !== void 0 ? { description } : {},
94
- parameters: schemaProjection.schema
95
- });
96
- }
97
- return {
98
- inputToolCount,
99
- tools: projectedTools,
100
- diagnostics
101
- };
102
- }
103
- function requireProjectedFunction(name, projection, choiceLabel) {
104
- if (!projection.tools.some((tool) => tool.name === name)) throw new Error(`${choiceLabel} requested unavailable tool "${name}" after schema conversion`);
105
- }
106
- /** Keeps Responses tool choices aligned with surviving function schemas. */
107
- function reconcileOpenAIResponsesToolChoice(choice, projection) {
108
- if (choice === "auto") return projection.tools.length > 0 ? choice : void 0;
109
- if (choice === "required") {
110
- if (projection.tools.length === 0) throw new Error("OpenAI Responses tool_choice requires a tool, but no tools survived schema conversion");
111
- return choice;
112
- }
113
- if (choice === "none" || !isRecord(choice)) return choice;
114
- const choiceType = choice.type;
115
- if (choiceType === "function") {
116
- const functionName = choice.name;
117
- if (typeof functionName !== "string") return choice;
118
- requireProjectedFunction(functionName, projection, "OpenAI Responses tool_choice");
119
- return {
120
- type: "function",
121
- name: functionName
122
- };
123
- }
124
- if (choiceType !== "allowed_tools") return choice;
125
- const mode = choice.mode;
126
- const tools = choice.tools;
127
- if (mode !== "auto" && mode !== "required" || !Array.isArray(tools)) return choice;
128
- const normalizedAllowedTools = [];
129
- for (const tool of tools) {
130
- if (!isRecord(tool) || tool.type !== "function") {
131
- normalizedAllowedTools.push(tool);
132
- continue;
133
- }
134
- const functionName = tool.name;
135
- if (typeof functionName === "string" && projection.tools.some((projectedTool) => projectedTool.name === functionName)) normalizedAllowedTools.push({
136
- type: "function",
137
- name: functionName
138
- });
139
- }
140
- if (normalizedAllowedTools.length === 0) {
141
- if (mode === "auto") return "none";
142
- throw new Error("OpenAI Responses tool_choice requires a tool, but no allowed tools survived schema conversion");
143
- }
144
- return {
145
- type: "allowed_tools",
146
- mode,
147
- tools: normalizedAllowedTools
148
- };
149
- }
150
- /** Keeps Chat Completions tool choices aligned with surviving function schemas. */
151
- function reconcileOpenAICompletionsToolChoice(choice, projection) {
152
- if (choice === "auto") return projection.tools.length > 0 ? choice : void 0;
153
- if (choice === "required") {
154
- if (projection.tools.length === 0) throw new Error("OpenAI Chat Completions tool_choice requires a tool, but no tools survived schema conversion");
155
- return choice;
156
- }
157
- if (choice === "none" || !isRecord(choice)) return choice;
158
- const choiceType = choice.type;
159
- if (choiceType === "custom") throw new Error("OpenAI Chat Completions custom tool_choice is unsupported because this adapter emits function tools only");
160
- if (choiceType === "function") {
161
- const functionChoice = choice.function;
162
- if (!isRecord(functionChoice)) return choice;
163
- const functionName = functionChoice.name;
164
- if (typeof functionName !== "string") return choice;
165
- requireProjectedFunction(functionName, projection, "OpenAI Chat Completions tool_choice");
166
- return {
167
- type: "function",
168
- function: { name: functionName }
169
- };
170
- }
171
- if (choiceType !== "allowed_tools") return choice;
172
- const allowedConfig = choice.allowed_tools;
173
- if (!isRecord(allowedConfig)) return choice;
174
- const mode = allowedConfig.mode;
175
- const tools = allowedConfig.tools;
176
- if (mode !== "auto" && mode !== "required" || !Array.isArray(tools)) return choice;
177
- const normalizedAllowedTools = [];
178
- for (const tool of tools) {
179
- if (!isRecord(tool) || tool.type !== "function") continue;
180
- const functionChoice = tool.function;
181
- const functionName = isRecord(functionChoice) ? functionChoice.name : void 0;
182
- if (typeof functionName === "string" && projection.tools.some((projectedTool) => projectedTool.name === functionName)) normalizedAllowedTools.push({
183
- type: "function",
184
- function: { name: functionName }
185
- });
186
- }
187
- if (normalizedAllowedTools.length === 0) {
188
- if (mode === "auto") return "none";
189
- throw new Error("OpenAI Chat Completions tool_choice requires a tool, but no allowed tools survived schema conversion");
190
- }
191
- return {
192
- type: "allowed_tools",
193
- allowed_tools: {
194
- mode,
195
- tools: normalizedAllowedTools
196
- }
197
- };
198
- }
199
- //#endregion
200
- export { clampOpenAIPromptCacheKey as a, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH as i, reconcileOpenAICompletionsToolChoice as n, reconcileOpenAIResponsesToolChoice as r, projectOpenAITools as t };