@warlock.js/ai-openai 5.30.0 → 5.31.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 (44) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +3 -3
  3. package/cjs/index.cjs +416 -48
  4. package/cjs/index.cjs.map +1 -1
  5. package/esm/config.type.d.mts +5 -3
  6. package/esm/config.type.d.mts.map +1 -1
  7. package/esm/embedder.d.mts.map +1 -1
  8. package/esm/embedder.mjs.map +1 -1
  9. package/esm/index.d.mts +3 -1
  10. package/esm/index.mjs +2 -1
  11. package/esm/known-pricing.d.mts +35 -0
  12. package/esm/known-pricing.d.mts.map +1 -0
  13. package/esm/known-pricing.mjs +117 -0
  14. package/esm/known-pricing.mjs.map +1 -0
  15. package/esm/model.mjs +75 -23
  16. package/esm/model.mjs.map +1 -1
  17. package/esm/provider-options.d.mts +8 -0
  18. package/esm/provider-options.d.mts.map +1 -0
  19. package/esm/provider-options.mjs +49 -0
  20. package/esm/provider-options.mjs.map +1 -0
  21. package/esm/responses-model.mjs +116 -17
  22. package/esm/responses-model.mjs.map +1 -1
  23. package/esm/sdk.d.mts +3 -2
  24. package/esm/sdk.d.mts.map +1 -1
  25. package/esm/sdk.mjs +5 -3
  26. package/esm/sdk.mjs.map +1 -1
  27. package/esm/transcription.mjs.map +1 -1
  28. package/esm/utils/build-usage.mjs +14 -2
  29. package/esm/utils/build-usage.mjs.map +1 -1
  30. package/esm/utils/index.mjs +1 -1
  31. package/esm/utils/map-responses-status.mjs.map +1 -1
  32. package/esm/utils/prompt-cache-params.mjs +25 -6
  33. package/esm/utils/prompt-cache-params.mjs.map +1 -1
  34. package/esm/utils/reasoning-replay.mjs +23 -1
  35. package/esm/utils/reasoning-replay.mjs.map +1 -1
  36. package/esm/utils/structured-output.mjs.map +1 -1
  37. package/esm/utils/to-openai-messages.mjs.map +1 -1
  38. package/esm/utils/to-openai-tools.mjs.map +1 -1
  39. package/esm/utils/wrap-openai-error.mjs +6 -1
  40. package/esm/utils/wrap-openai-error.mjs.map +1 -1
  41. package/llms-full.txt +128 -37
  42. package/llms.txt +1 -1
  43. package/package.json +3 -3
  44. package/skills/setup-openai/SKILL.md +128 -37
@@ -1,14 +1,33 @@
1
1
  //#region ../../packages/ai-openai/src/utils/prompt-cache-params.ts
2
2
  /**
3
- * Build the OpenAI-only prompt-cache request fields from the model config.
4
- * Returns nothing for any provider label other than `"openai"`: wrapper
5
- * endpoints use the same transport but may reject these OpenAI-only fields.
3
+ * Provider labels whose OpenAI-compatible endpoint documents a
4
+ * `prompt_cache_key` request field:
5
+ *
6
+ * - `openai` — https://developers.openai.com/api/docs/guides/prompt-caching
7
+ * - `xai` — Chat Completions accepts `prompt_cache_key` ("plumbed to
8
+ * x-grok-conv-id"), https://docs.x.ai/openapi.json and
9
+ * https://docs.x.ai/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits
10
+ * - `mistral` — https://docs.mistral.ai/studio/conversations/advanced/prompt-caching
11
+ *
12
+ * Groq and DeepSeek cache automatically and document no request hint, so
13
+ * they receive nothing (checked 2026-10-17).
14
+ */
15
+ const PROMPT_CACHE_KEY_PROVIDERS = new Set([
16
+ "openai",
17
+ "xai",
18
+ "mistral"
19
+ ]);
20
+ /**
21
+ * Build the prompt-cache request fields from the model config.
22
+ * `prompt_cache_key` is sent for the providers that document it
23
+ * ({@link PROMPT_CACHE_KEY_PROVIDERS}); `prompt_cache_retention` is
24
+ * OpenAI-only. Any other provider label — including a custom label on a
25
+ * wrapper SDK — gets neither, since an unknown endpoint may reject them.
6
26
  */
7
27
  function buildPromptCacheParams(provider, config) {
8
- if (provider !== "openai") return {};
9
28
  return {
10
- ...config.promptCacheKey !== void 0 ? { prompt_cache_key: config.promptCacheKey } : {},
11
- ...config.promptCacheRetention !== void 0 ? { prompt_cache_retention: config.promptCacheRetention } : {}
29
+ ...PROMPT_CACHE_KEY_PROVIDERS.has(provider) && config.promptCacheKey !== void 0 ? { prompt_cache_key: config.promptCacheKey } : {},
30
+ ...provider === "openai" && config.promptCacheRetention !== void 0 ? { prompt_cache_retention: config.promptCacheRetention } : {}
12
31
  };
13
32
  }
14
33
 
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-cache-params.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/prompt-cache-params.ts"],"sourcesContent":["import type { OpenAIModelConfig } from \"../config.type\";\n\n/** The OpenAI-only prompt-cache request fields common to Chat Completions and Responses. */\nexport type PromptCacheParams = {\n prompt_cache_key?: string;\n prompt_cache_retention?: NonNullable<OpenAIModelConfig[\"promptCacheRetention\"]>;\n};\n\n/**\n * Build the OpenAI-only prompt-cache request fields from the model config.\n * Returns nothing for any provider label other than `\"openai\"`: wrapper\n * endpoints use the same transport but may reject these OpenAI-only fields.\n */\nexport function buildPromptCacheParams(\n provider: string,\n config: Pick<OpenAIModelConfig, \"promptCacheKey\" | \"promptCacheRetention\">,\n): PromptCacheParams {\n if (provider !== \"openai\") {\n return {};\n }\n\n return {\n ...(config.promptCacheKey !== undefined ? { prompt_cache_key: config.promptCacheKey } : {}),\n ...(config.promptCacheRetention !== undefined\n ? { prompt_cache_retention: config.promptCacheRetention }\n : {}),\n };\n}\n"],"mappings":";;;;;;AAaA,SAAgB,uBACd,UACA,QACmB;CACnB,IAAI,aAAa,UACf,OAAO,CAAC;CAGV,OAAO;EACL,GAAI,OAAO,mBAAmB,SAAY,EAAE,kBAAkB,OAAO,eAAe,IAAI,CAAC;EACzF,GAAI,OAAO,yBAAyB,SAChC,EAAE,wBAAwB,OAAO,qBAAqB,IACtD,CAAC;CACP;AACF"}
1
+ {"version":3,"file":"prompt-cache-params.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/prompt-cache-params.ts"],"sourcesContent":["import type { OpenAIModelConfig } from \"../config.type\";\n\n/** The prompt-cache request fields common to Chat Completions and Responses. */\nexport type PromptCacheParams = {\n prompt_cache_key?: string;\n prompt_cache_retention?: NonNullable<OpenAIModelConfig[\"promptCacheRetention\"]>;\n};\n\n/**\n * Provider labels whose OpenAI-compatible endpoint documents a\n * `prompt_cache_key` request field:\n *\n * - `openai` — https://developers.openai.com/api/docs/guides/prompt-caching\n * - `xai` — Chat Completions accepts `prompt_cache_key` (\"plumbed to\n * x-grok-conv-id\"), https://docs.x.ai/openapi.json and\n * https://docs.x.ai/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits\n * - `mistral` — https://docs.mistral.ai/studio/conversations/advanced/prompt-caching\n *\n * Groq and DeepSeek cache automatically and document no request hint, so\n * they receive nothing (checked 2026-10-17).\n */\nconst PROMPT_CACHE_KEY_PROVIDERS: ReadonlySet<string> = new Set([\"openai\", \"xai\", \"mistral\"]);\n\n/**\n * Build the prompt-cache request fields from the model config.\n * `prompt_cache_key` is sent for the providers that document it\n * ({@link PROMPT_CACHE_KEY_PROVIDERS}); `prompt_cache_retention` is\n * OpenAI-only. Any other provider label — including a custom label on a\n * wrapper SDK — gets neither, since an unknown endpoint may reject them.\n */\nexport function buildPromptCacheParams(\n provider: string,\n config: Pick<OpenAIModelConfig, \"promptCacheKey\" | \"promptCacheRetention\">,\n): PromptCacheParams {\n const sendsKey = PROMPT_CACHE_KEY_PROVIDERS.has(provider);\n\n return {\n ...(sendsKey && config.promptCacheKey !== undefined\n ? { prompt_cache_key: config.promptCacheKey }\n : {}),\n ...(provider === \"openai\" && config.promptCacheRetention !== undefined\n ? { prompt_cache_retention: config.promptCacheRetention }\n : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAM,6BAAkD,IAAI,IAAI;CAAC;CAAU;CAAO;AAAS,CAAC;;;;;;;;AAS5F,SAAgB,uBACd,UACA,QACmB;CAGnB,OAAO;EACL,GAHe,2BAA2B,IAAI,QAGnC,KAAK,OAAO,mBAAmB,SACtC,EAAE,kBAAkB,OAAO,eAAe,IAC1C,CAAC;EACL,GAAI,aAAa,YAAY,OAAO,yBAAyB,SACzD,EAAE,wBAAwB,OAAO,qBAAqB,IACtD,CAAC;CACP;AACF"}
@@ -14,6 +14,28 @@ const RESPONSES_METADATA_KEY = "openaiResponses";
14
14
  function pickReplayableReasoning(items) {
15
15
  return items.filter((item) => typeof item.encrypted_content === "string" && item.encrypted_content !== "");
16
16
  }
17
+ /** Output item types that may follow a replayed reasoning item. */
18
+ const REPLAY_SAFE_FOLLOWERS = new Set(["function_call", "message"]);
19
+ /**
20
+ * The reasoning items of a turn that are safe to replay, in order.
21
+ *
22
+ * The API pairs a reasoning item with the output item that followed it and
23
+ * rejects a replayed reasoning item whose follower is missing. Only
24
+ * `function_call` items are replayed, so a reasoning item that led into a
25
+ * hosted (server-run) tool call — `web_search_call`, `file_search_call`,
26
+ * `code_interpreter_call`, … from a provider-defined tool — is dropped
27
+ * rather than sent without its follower. Encrypted reasoning only improves
28
+ * continuity; dropping it never breaks the request.
29
+ */
30
+ function pickTurnReasoning(output) {
31
+ const picked = [];
32
+ output.forEach((item, index) => {
33
+ if (item.type !== "reasoning") return;
34
+ const follower = output.slice(index + 1).find((next) => next.type !== "reasoning");
35
+ if (follower === void 0 || REPLAY_SAFE_FOLLOWERS.has(follower.type)) picked.push(item);
36
+ });
37
+ return picked;
38
+ }
17
39
  /**
18
40
  * Attach the turn's reasoning items to the FIRST tool call only (parallel
19
41
  * calls do not each repeat the blobs). Returns the calls unchanged when
@@ -81,5 +103,5 @@ function isReplayMetadata(value) {
81
103
  }
82
104
 
83
105
  //#endregion
84
- export { RESPONSES_METADATA_KEY, attachReasoningReplay, pickReplayableReasoning, readReasoningReplay, toReplayReasoningItem };
106
+ export { RESPONSES_METADATA_KEY, attachReasoningReplay, pickReplayableReasoning, pickTurnReasoning, readReasoningReplay, toReplayReasoningItem };
85
107
  //# sourceMappingURL=reasoning-replay.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"reasoning-replay.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/reasoning-replay.ts"],"sourcesContent":["import type { ModelToolCallRequest } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/** A `reasoning` output item as the Responses API returns it. */\nexport type ResponsesReasoningItem = OpenAI.Responses.ResponseReasoningItem;\n\n/**\n * Key under `ModelToolCallRequest.providerMetadata` owned by the Responses\n * adapter. This name and the shape below are PERSISTED in users' conversation\n * memory, so they are part of the public contract: do not rename.\n */\nexport const RESPONSES_METADATA_KEY = \"openaiResponses\";\n\n/**\n * What the Responses adapter stores on the FIRST tool call of an assistant\n * turn so the next request can replay the model's reasoning (design\n * section 4, decisions 2 and 3).\n */\nexport type ResponsesReplayMetadata = {\n /** Model the items were produced by; replay is skipped when it differs. */\n model: string;\n /** Reasoning items of the turn, in the order the API emitted them. */\n reasoningItems: ResponsesReasoningItem[];\n};\n\n/**\n * Keep only the reasoning items that can actually be replayed. With\n * `store: false` the server keeps nothing, so an item without\n * `encrypted_content` has nothing to restore and replaying its bare `id`\n * would be rejected as an unknown item.\n */\nexport function pickReplayableReasoning(\n items: readonly ResponsesReasoningItem[],\n): ResponsesReasoningItem[] {\n return items.filter(\n (item) => typeof item.encrypted_content === \"string\" && item.encrypted_content !== \"\",\n );\n}\n\n/**\n * Attach the turn's reasoning items to the FIRST tool call only (parallel\n * calls do not each repeat the blobs). Returns the calls unchanged when\n * there is nothing to replay or no tool call to ride on (a text-only turn is\n * deliberately not replayed, decision 2). Does not mutate its input.\n */\nexport function attachReasoningReplay(\n toolCalls: readonly ModelToolCallRequest[],\n model: string,\n reasoningItems: readonly ResponsesReasoningItem[],\n): ModelToolCallRequest[] {\n const replayable = pickReplayableReasoning(reasoningItems);\n const [first, ...rest] = toolCalls;\n\n if (first === undefined || replayable.length === 0) {\n return [...toolCalls];\n }\n\n const metadata: ResponsesReplayMetadata = { model, reasoningItems: replayable };\n\n return [\n { ...first, providerMetadata: { ...first.providerMetadata, [RESPONSES_METADATA_KEY]: metadata } },\n ...rest,\n ];\n}\n\n/**\n * Read the stored reasoning items off an assistant turn's tool calls, for\n * replay on `model`. Returns `[]` when the key is absent or malformed, or\n * when the stored `model` differs from `model` (encrypted blobs are not\n * portable across models, design section 4). De-duplicates by item `id`.\n */\nexport function readReasoningReplay(\n toolCalls: readonly ModelToolCallRequest[],\n model: string,\n): ResponsesReasoningItem[] {\n const seen = new Set<string>();\n const items: ResponsesReasoningItem[] = [];\n\n for (const call of toolCalls) {\n const stored = call.providerMetadata?.[RESPONSES_METADATA_KEY];\n\n if (!isReplayMetadata(stored) || stored.model !== model) {\n continue;\n }\n\n for (const item of stored.reasoningItems) {\n if (item?.type !== \"reasoning\" || seen.has(item.id)) {\n continue;\n }\n\n seen.add(item.id);\n items.push(item);\n }\n }\n\n return items;\n}\n\n/**\n * Shape a stored reasoning item for the next request. Sends the four fields\n * a stateless replay needs (`type`, `id`, `summary`, `encrypted_content`) and\n * drops the response-only `status` and the optional raw `content`.\n *\n * UNVERIFIED: the SDK types accept the full item as input (`ResponseInputItem`\n * includes `ResponseReasoningItem`) and do not say which fields the API\n * refuses on replay with `store: false`. This is the conservative guess; a\n * live probe settles it.\n */\nexport function toReplayReasoningItem(item: ResponsesReasoningItem): ResponsesReasoningItem {\n return {\n type: \"reasoning\",\n id: item.id,\n summary: Array.isArray(item.summary) ? item.summary : [],\n encrypted_content: item.encrypted_content,\n };\n}\n\nfunction isReplayMetadata(value: unknown): value is ResponsesReplayMetadata {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Partial<ResponsesReplayMetadata>;\n\n return typeof candidate.model === \"string\" && Array.isArray(candidate.reasoningItems);\n}\n"],"mappings":";;;;;;AAWA,MAAa,yBAAyB;;;;;;;AAoBtC,SAAgB,wBACd,OAC0B;CAC1B,OAAO,MAAM,QACV,SAAS,OAAO,KAAK,sBAAsB,YAAY,KAAK,sBAAsB,EACrF;AACF;;;;;;;AAQA,SAAgB,sBACd,WACA,OACA,gBACwB;CACxB,MAAM,aAAa,wBAAwB,cAAc;CACzD,MAAM,CAAC,OAAO,GAAG,QAAQ;CAEzB,IAAI,UAAU,UAAa,WAAW,WAAW,GAC/C,OAAO,CAAC,GAAG,SAAS;CAGtB,MAAM,WAAoC;EAAE;EAAO,gBAAgB;CAAW;CAE9E,OAAO,CACL;EAAE,GAAG;EAAO,kBAAkB;GAAE,GAAG,MAAM;IAAmB,yBAAyB;EAAS;CAAE,GAChG,GAAG,IACL;AACF;;;;;;;AAQA,SAAgB,oBACd,WACA,OAC0B;CAC1B,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,QAAkC,CAAC;CAEzC,KAAK,MAAM,QAAQ,WAAW;EAC5B,MAAM,SAAS,KAAK,mBAAmB;EAEvC,IAAI,CAAC,iBAAiB,MAAM,KAAK,OAAO,UAAU,OAChD;EAGF,KAAK,MAAM,QAAQ,OAAO,gBAAgB;GACxC,IAAI,MAAM,SAAS,eAAe,KAAK,IAAI,KAAK,EAAE,GAChD;GAGF,KAAK,IAAI,KAAK,EAAE;GAChB,MAAM,KAAK,IAAI;EACjB;CACF;CAEA,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,sBAAsB,MAAsD;CAC1F,OAAO;EACL,MAAM;EACN,IAAI,KAAK;EACT,SAAS,MAAM,QAAQ,KAAK,OAAO,IAAI,KAAK,UAAU,CAAC;EACvD,mBAAmB,KAAK;CAC1B;AACF;AAEA,SAAS,iBAAiB,OAAkD;CAC1E,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAGT,MAAM,YAAY;CAElB,OAAO,OAAO,UAAU,UAAU,YAAY,MAAM,QAAQ,UAAU,cAAc;AACtF"}
1
+ {"version":3,"file":"reasoning-replay.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/reasoning-replay.ts"],"sourcesContent":["import type { ModelToolCallRequest } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/** A `reasoning` output item as the Responses API returns it. */\nexport type ResponsesReasoningItem = OpenAI.Responses.ResponseReasoningItem;\n\n/**\n * Key under `ModelToolCallRequest.providerMetadata` owned by the Responses\n * adapter. This name and the shape below are PERSISTED in users' conversation\n * memory, so they are part of the public contract: do not rename.\n */\nexport const RESPONSES_METADATA_KEY = \"openaiResponses\";\n\n/**\n * What the Responses adapter stores on the FIRST tool call of an assistant\n * turn so the next request can replay the model's reasoning (design\n * section 4, decisions 2 and 3).\n */\nexport type ResponsesReplayMetadata = {\n /** Model the items were produced by; replay is skipped when it differs. */\n model: string;\n /** Reasoning items of the turn, in the order the API emitted them. */\n reasoningItems: ResponsesReasoningItem[];\n};\n\n/**\n * Keep only the reasoning items that can actually be replayed. With\n * `store: false` the server keeps nothing, so an item without\n * `encrypted_content` has nothing to restore and replaying its bare `id`\n * would be rejected as an unknown item.\n */\nexport function pickReplayableReasoning(\n items: readonly ResponsesReasoningItem[],\n): ResponsesReasoningItem[] {\n return items.filter(\n (item) => typeof item.encrypted_content === \"string\" && item.encrypted_content !== \"\",\n );\n}\n\n/** Output item types that may follow a replayed reasoning item. */\nconst REPLAY_SAFE_FOLLOWERS: ReadonlySet<string> = new Set([\"function_call\", \"message\"]);\n\n/**\n * The reasoning items of a turn that are safe to replay, in order.\n *\n * The API pairs a reasoning item with the output item that followed it and\n * rejects a replayed reasoning item whose follower is missing. Only\n * `function_call` items are replayed, so a reasoning item that led into a\n * hosted (server-run) tool call — `web_search_call`, `file_search_call`,\n * `code_interpreter_call`, … from a provider-defined tool — is dropped\n * rather than sent without its follower. Encrypted reasoning only improves\n * continuity; dropping it never breaks the request.\n */\nexport function pickTurnReasoning(\n output: ReadonlyArray<{ type: string }>,\n): ResponsesReasoningItem[] {\n const picked: ResponsesReasoningItem[] = [];\n\n output.forEach((item, index) => {\n if (item.type !== \"reasoning\") {\n return;\n }\n\n const follower = output.slice(index + 1).find((next) => next.type !== \"reasoning\");\n\n if (follower === undefined || REPLAY_SAFE_FOLLOWERS.has(follower.type)) {\n picked.push(item as ResponsesReasoningItem);\n }\n });\n\n return picked;\n}\n\n/**\n * Attach the turn's reasoning items to the FIRST tool call only (parallel\n * calls do not each repeat the blobs). Returns the calls unchanged when\n * there is nothing to replay or no tool call to ride on (a text-only turn is\n * deliberately not replayed, decision 2). Does not mutate its input.\n */\nexport function attachReasoningReplay(\n toolCalls: readonly ModelToolCallRequest[],\n model: string,\n reasoningItems: readonly ResponsesReasoningItem[],\n): ModelToolCallRequest[] {\n const replayable = pickReplayableReasoning(reasoningItems);\n const [first, ...rest] = toolCalls;\n\n if (first === undefined || replayable.length === 0) {\n return [...toolCalls];\n }\n\n const metadata: ResponsesReplayMetadata = { model, reasoningItems: replayable };\n\n return [\n {\n ...first,\n providerMetadata: { ...first.providerMetadata, [RESPONSES_METADATA_KEY]: metadata },\n },\n ...rest,\n ];\n}\n\n/**\n * Read the stored reasoning items off an assistant turn's tool calls, for\n * replay on `model`. Returns `[]` when the key is absent or malformed, or\n * when the stored `model` differs from `model` (encrypted blobs are not\n * portable across models, design section 4). De-duplicates by item `id`.\n */\nexport function readReasoningReplay(\n toolCalls: readonly ModelToolCallRequest[],\n model: string,\n): ResponsesReasoningItem[] {\n const seen = new Set<string>();\n const items: ResponsesReasoningItem[] = [];\n\n for (const call of toolCalls) {\n const stored = call.providerMetadata?.[RESPONSES_METADATA_KEY];\n\n if (!isReplayMetadata(stored) || stored.model !== model) {\n continue;\n }\n\n for (const item of stored.reasoningItems) {\n if (item?.type !== \"reasoning\" || seen.has(item.id)) {\n continue;\n }\n\n seen.add(item.id);\n items.push(item);\n }\n }\n\n return items;\n}\n\n/**\n * Shape a stored reasoning item for the next request. Sends the four fields\n * a stateless replay needs (`type`, `id`, `summary`, `encrypted_content`) and\n * drops the response-only `status` and the optional raw `content`.\n *\n * UNVERIFIED: the SDK types accept the full item as input (`ResponseInputItem`\n * includes `ResponseReasoningItem`) and do not say which fields the API\n * refuses on replay with `store: false`. This is the conservative guess; a\n * live probe settles it.\n */\nexport function toReplayReasoningItem(item: ResponsesReasoningItem): ResponsesReasoningItem {\n return {\n type: \"reasoning\",\n id: item.id,\n summary: Array.isArray(item.summary) ? item.summary : [],\n encrypted_content: item.encrypted_content,\n };\n}\n\nfunction isReplayMetadata(value: unknown): value is ResponsesReplayMetadata {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Partial<ResponsesReplayMetadata>;\n\n return typeof candidate.model === \"string\" && Array.isArray(candidate.reasoningItems);\n}\n"],"mappings":";;;;;;AAWA,MAAa,yBAAyB;;;;;;;AAoBtC,SAAgB,wBACd,OAC0B;CAC1B,OAAO,MAAM,QACV,SAAS,OAAO,KAAK,sBAAsB,YAAY,KAAK,sBAAsB,EACrF;AACF;;AAGA,MAAM,wBAA6C,IAAI,IAAI,CAAC,iBAAiB,SAAS,CAAC;;;;;;;;;;;;AAavF,SAAgB,kBACd,QAC0B;CAC1B,MAAM,SAAmC,CAAC;CAE1C,OAAO,SAAS,MAAM,UAAU;EAC9B,IAAI,KAAK,SAAS,aAChB;EAGF,MAAM,WAAW,OAAO,MAAM,QAAQ,CAAC,CAAC,CAAC,MAAM,SAAS,KAAK,SAAS,WAAW;EAEjF,IAAI,aAAa,UAAa,sBAAsB,IAAI,SAAS,IAAI,GACnE,OAAO,KAAK,IAA8B;CAE9C,CAAC;CAED,OAAO;AACT;;;;;;;AAQA,SAAgB,sBACd,WACA,OACA,gBACwB;CACxB,MAAM,aAAa,wBAAwB,cAAc;CACzD,MAAM,CAAC,OAAO,GAAG,QAAQ;CAEzB,IAAI,UAAU,UAAa,WAAW,WAAW,GAC/C,OAAO,CAAC,GAAG,SAAS;CAGtB,MAAM,WAAoC;EAAE;EAAO,gBAAgB;CAAW;CAE9E,OAAO,CACL;EACE,GAAG;EACH,kBAAkB;GAAE,GAAG,MAAM;IAAmB,yBAAyB;EAAS;CACpF,GACA,GAAG,IACL;AACF;;;;;;;AAQA,SAAgB,oBACd,WACA,OAC0B;CAC1B,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,QAAkC,CAAC;CAEzC,KAAK,MAAM,QAAQ,WAAW;EAC5B,MAAM,SAAS,KAAK,mBAAmB;EAEvC,IAAI,CAAC,iBAAiB,MAAM,KAAK,OAAO,UAAU,OAChD;EAGF,KAAK,MAAM,QAAQ,OAAO,gBAAgB;GACxC,IAAI,MAAM,SAAS,eAAe,KAAK,IAAI,KAAK,EAAE,GAChD;GAGF,KAAK,IAAI,KAAK,EAAE;GAChB,MAAM,KAAK,IAAI;EACjB;CACF;CAEA,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,sBAAsB,MAAsD;CAC1F,OAAO;EACL,MAAM;EACN,IAAI,KAAK;EACT,SAAS,MAAM,QAAQ,KAAK,OAAO,IAAI,KAAK,UAAU,CAAC;EACvD,mBAAmB,KAAK;CAC1B;AACF;AAEA,SAAS,iBAAiB,OAAkD;CAC1E,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAGT,MAAM,YAAY;CAElB,OAAO,OAAO,UAAU,UAAU,YAAY,MAAM,QAAQ,UAAU,cAAc;AACtF"}
@@ -1 +1 @@
1
- {"version":3,"file":"structured-output.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/structured-output.ts"],"sourcesContent":["import type { OpenAIResponseFormat } from \"../config.type\";\n\n/**\n * How a `responseSchema` should reach the wire, decided once for both the\n * Chat Completions adapter (`response_format`) and the Responses adapter\n * (`text.format`). Only the wire location differs between the two.\n */\nexport type StructuredOutputPlan =\n | { mode: \"none\" }\n | { mode: \"json_object\" }\n | { mode: \"json_schema\"; schema: Record<string, unknown> };\n\n/**\n * Map an explicit `responseFormat` override to the default\n * `structuredOutput` capability. Loose wire modes (`\"json_object\"`,\n * `\"text\"`) don't enforce shape, so the agent needs to see the soft\n * schema hint in the system prompt — that only happens when the\n * capability is `false`. Default (no override) stays `true` to\n * preserve the prior assumption that OpenAI models support strict\n * structured output.\n */\nexport function inferStructuredOutput(\n responseFormat: OpenAIResponseFormat | undefined,\n): boolean {\n if (responseFormat === \"json_object\" || responseFormat === \"text\") {\n return false;\n }\n\n return true;\n}\n\n/**\n * Decide the structured-output mode for a call.\n *\n * When `override` (the `responseFormat` config) is set, it wins: `\"text\"`\n * emits nothing, `\"json_object\"` always picks the loose mode, and\n * `\"json_schema\"` picks strict mode (with the same strict-compatibility\n * safety check - a malformed schema still degrades to `json_object` rather\n * than 400). The override exists because some targets (older OpenAI models,\n * OpenRouter routes, Ollama OpenAI-compat) reject strict `json_schema`\n * outright.\n *\n * When the override is omitted, strict `json_schema` mode (token-level\n * enforcement) is used only when the schema is a proper root-object JSON\n * Schema whose every object lists all of its properties in `required`. For\n * anything else it falls back to loose `json_object` mode. Client-side\n * Standard Schema `validate()` still enforces the full shape.\n */\nexport function planStructuredOutput(\n responseSchema: Record<string, unknown> | undefined,\n override: OpenAIResponseFormat | undefined,\n): StructuredOutputPlan {\n if (!responseSchema || override === \"text\") {\n return { mode: \"none\" };\n }\n\n if (override === \"json_object\") {\n return { mode: \"json_object\" };\n }\n\n // Either auto-select (no override) or explicit `\"json_schema\"`. The\n // strict-compat check still applies in the explicit case - a malformed or\n // non-object schema would 400 before sampling, so degrade to `json_object`.\n if (isStrictCompatible(responseSchema)) {\n return { mode: \"json_schema\", schema: responseSchema };\n }\n\n return { mode: \"json_object\" };\n}\n\n/**\n * OpenAI strict `json_schema` mode requires the root to be a JSON Schema\n * object type (`{ type: \"object\", properties: ... }`). Anything else\n * (top-level arrays, primitives, unknown shapes) is rejected with a 400\n * before a token is sampled. Checked structurally here so the first call\n * doesn't crash on a malformed extraction.\n */\nexport function isStrictCompatible(schema: Record<string, unknown>): boolean {\n return (\n schema.type === \"object\" &&\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n isStrictSafeNode(schema)\n );\n}\n\n/**\n * Recursively check the one strict-mode rule schemas most often trip on:\n * every object must list ALL of its `properties` in `required` (OpenAI\n * strict has no notion of optional - optional fields must be expressed as\n * nullable, e.g. `type: [\"string\", \"null\"]`, and still appear in\n * `required`). A schema that violates this anywhere in the tree is NOT sent\n * in strict mode, so a hand-built or optional-bearing schema can't 400 the\n * call (\"'required' ... must include every key in properties\").\n */\nfunction isStrictSafeNode(node: unknown): boolean {\n if (!node || typeof node !== \"object\") {\n return true;\n }\n\n const record = node as Record<string, unknown>;\n\n if (record.type === \"object\" && record.properties && typeof record.properties === \"object\") {\n const properties = record.properties as Record<string, unknown>;\n const keys = Object.keys(properties);\n const required = Array.isArray(record.required) ? (record.required as unknown[]) : [];\n\n if (keys.some((key) => !required.includes(key))) {\n return false;\n }\n\n for (const key of keys) {\n if (!isStrictSafeNode(properties[key])) {\n return false;\n }\n }\n }\n\n if (record.items !== undefined && !isStrictSafeNode(record.items)) {\n return false;\n }\n\n for (const branch of [\"anyOf\", \"allOf\", \"oneOf\"] as const) {\n const value = record[branch];\n\n if (Array.isArray(value) && value.some((sub) => !isStrictSafeNode(sub))) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;AAqBA,SAAgB,sBACd,gBACS;CACT,IAAI,mBAAmB,iBAAiB,mBAAmB,QACzD,OAAO;CAGT,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBACd,gBACA,UACsB;CACtB,IAAI,CAAC,kBAAkB,aAAa,QAClC,OAAO,EAAE,MAAM,OAAO;CAGxB,IAAI,aAAa,eACf,OAAO,EAAE,MAAM,cAAc;CAM/B,IAAI,mBAAmB,cAAc,GACnC,OAAO;EAAE,MAAM;EAAe,QAAQ;CAAe;CAGvD,OAAO,EAAE,MAAM,cAAc;AAC/B;;;;;;;;AASA,SAAgB,mBAAmB,QAA0C;CAC3E,OACE,OAAO,SAAS,YAChB,OAAO,OAAO,eAAe,YAC7B,OAAO,eAAe,QACtB,iBAAiB,MAAM;AAE3B;;;;;;;;;;AAWA,SAAS,iBAAiB,MAAwB;CAChD,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B,OAAO;CAGT,MAAM,SAAS;CAEf,IAAI,OAAO,SAAS,YAAY,OAAO,cAAc,OAAO,OAAO,eAAe,UAAU;EAC1F,MAAM,aAAa,OAAO;EAC1B,MAAM,OAAO,OAAO,KAAK,UAAU;EACnC,MAAM,WAAW,MAAM,QAAQ,OAAO,QAAQ,IAAK,OAAO,WAAyB,CAAC;EAEpF,IAAI,KAAK,MAAM,QAAQ,CAAC,SAAS,SAAS,GAAG,CAAC,GAC5C,OAAO;EAGT,KAAK,MAAM,OAAO,MAChB,IAAI,CAAC,iBAAiB,WAAW,IAAI,GACnC,OAAO;CAGb;CAEA,IAAI,OAAO,UAAU,UAAa,CAAC,iBAAiB,OAAO,KAAK,GAC9D,OAAO;CAGT,KAAK,MAAM,UAAU;EAAC;EAAS;EAAS;CAAO,GAAY;EACzD,MAAM,QAAQ,OAAO;EAErB,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,QAAQ,CAAC,iBAAiB,GAAG,CAAC,GACpE,OAAO;CAEX;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"structured-output.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/structured-output.ts"],"sourcesContent":["import type { OpenAIResponseFormat } from \"../config.type\";\n\n/**\n * How a `responseSchema` should reach the wire, decided once for both the\n * Chat Completions adapter (`response_format`) and the Responses adapter\n * (`text.format`). Only the wire location differs between the two.\n */\nexport type StructuredOutputPlan =\n | { mode: \"none\" }\n | { mode: \"json_object\" }\n | { mode: \"json_schema\"; schema: Record<string, unknown> };\n\n/**\n * Map an explicit `responseFormat` override to the default\n * `structuredOutput` capability. Loose wire modes (`\"json_object\"`,\n * `\"text\"`) don't enforce shape, so the agent needs to see the soft\n * schema hint in the system prompt — that only happens when the\n * capability is `false`. Default (no override) stays `true` to\n * preserve the prior assumption that OpenAI models support strict\n * structured output.\n */\nexport function inferStructuredOutput(responseFormat: OpenAIResponseFormat | undefined): boolean {\n if (responseFormat === \"json_object\" || responseFormat === \"text\") {\n return false;\n }\n\n return true;\n}\n\n/**\n * Decide the structured-output mode for a call.\n *\n * When `override` (the `responseFormat` config) is set, it wins: `\"text\"`\n * emits nothing, `\"json_object\"` always picks the loose mode, and\n * `\"json_schema\"` picks strict mode (with the same strict-compatibility\n * safety check - a malformed schema still degrades to `json_object` rather\n * than 400). The override exists because some targets (older OpenAI models,\n * OpenRouter routes, Ollama OpenAI-compat) reject strict `json_schema`\n * outright.\n *\n * When the override is omitted, strict `json_schema` mode (token-level\n * enforcement) is used only when the schema is a proper root-object JSON\n * Schema whose every object lists all of its properties in `required`. For\n * anything else it falls back to loose `json_object` mode. Client-side\n * Standard Schema `validate()` still enforces the full shape.\n */\nexport function planStructuredOutput(\n responseSchema: Record<string, unknown> | undefined,\n override: OpenAIResponseFormat | undefined,\n): StructuredOutputPlan {\n if (!responseSchema || override === \"text\") {\n return { mode: \"none\" };\n }\n\n if (override === \"json_object\") {\n return { mode: \"json_object\" };\n }\n\n // Either auto-select (no override) or explicit `\"json_schema\"`. The\n // strict-compat check still applies in the explicit case - a malformed or\n // non-object schema would 400 before sampling, so degrade to `json_object`.\n if (isStrictCompatible(responseSchema)) {\n return { mode: \"json_schema\", schema: responseSchema };\n }\n\n return { mode: \"json_object\" };\n}\n\n/**\n * OpenAI strict `json_schema` mode requires the root to be a JSON Schema\n * object type (`{ type: \"object\", properties: ... }`). Anything else\n * (top-level arrays, primitives, unknown shapes) is rejected with a 400\n * before a token is sampled. Checked structurally here so the first call\n * doesn't crash on a malformed extraction.\n */\nexport function isStrictCompatible(schema: Record<string, unknown>): boolean {\n return (\n schema.type === \"object\" &&\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n isStrictSafeNode(schema)\n );\n}\n\n/**\n * Recursively check the one strict-mode rule schemas most often trip on:\n * every object must list ALL of its `properties` in `required` (OpenAI\n * strict has no notion of optional - optional fields must be expressed as\n * nullable, e.g. `type: [\"string\", \"null\"]`, and still appear in\n * `required`). A schema that violates this anywhere in the tree is NOT sent\n * in strict mode, so a hand-built or optional-bearing schema can't 400 the\n * call (\"'required' ... must include every key in properties\").\n */\nfunction isStrictSafeNode(node: unknown): boolean {\n if (!node || typeof node !== \"object\") {\n return true;\n }\n\n const record = node as Record<string, unknown>;\n\n if (record.type === \"object\" && record.properties && typeof record.properties === \"object\") {\n const properties = record.properties as Record<string, unknown>;\n const keys = Object.keys(properties);\n const required = Array.isArray(record.required) ? (record.required as unknown[]) : [];\n\n if (keys.some((key) => !required.includes(key))) {\n return false;\n }\n\n for (const key of keys) {\n if (!isStrictSafeNode(properties[key])) {\n return false;\n }\n }\n }\n\n if (record.items !== undefined && !isStrictSafeNode(record.items)) {\n return false;\n }\n\n for (const branch of [\"anyOf\", \"allOf\", \"oneOf\"] as const) {\n const value = record[branch];\n\n if (Array.isArray(value) && value.some((sub) => !isStrictSafeNode(sub))) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;AAqBA,SAAgB,sBAAsB,gBAA2D;CAC/F,IAAI,mBAAmB,iBAAiB,mBAAmB,QACzD,OAAO;CAGT,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,qBACd,gBACA,UACsB;CACtB,IAAI,CAAC,kBAAkB,aAAa,QAClC,OAAO,EAAE,MAAM,OAAO;CAGxB,IAAI,aAAa,eACf,OAAO,EAAE,MAAM,cAAc;CAM/B,IAAI,mBAAmB,cAAc,GACnC,OAAO;EAAE,MAAM;EAAe,QAAQ;CAAe;CAGvD,OAAO,EAAE,MAAM,cAAc;AAC/B;;;;;;;;AASA,SAAgB,mBAAmB,QAA0C;CAC3E,OACE,OAAO,SAAS,YAChB,OAAO,OAAO,eAAe,YAC7B,OAAO,eAAe,QACtB,iBAAiB,MAAM;AAE3B;;;;;;;;;;AAWA,SAAS,iBAAiB,MAAwB;CAChD,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B,OAAO;CAGT,MAAM,SAAS;CAEf,IAAI,OAAO,SAAS,YAAY,OAAO,cAAc,OAAO,OAAO,eAAe,UAAU;EAC1F,MAAM,aAAa,OAAO;EAC1B,MAAM,OAAO,OAAO,KAAK,UAAU;EACnC,MAAM,WAAW,MAAM,QAAQ,OAAO,QAAQ,IAAK,OAAO,WAAyB,CAAC;EAEpF,IAAI,KAAK,MAAM,QAAQ,CAAC,SAAS,SAAS,GAAG,CAAC,GAC5C,OAAO;EAGT,KAAK,MAAM,OAAO,MAChB,IAAI,CAAC,iBAAiB,WAAW,IAAI,GACnC,OAAO;CAGb;CAEA,IAAI,OAAO,UAAU,UAAa,CAAC,iBAAiB,OAAO,KAAK,GAC9D,OAAO;CAGT,KAAK,MAAM,UAAU;EAAC;EAAS;EAAS;CAAO,GAAY;EACzD,MAAM,QAAQ,OAAO;EAErB,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,QAAQ,CAAC,iBAAiB,GAAG,CAAC,GACpE,OAAO;CAEX;CAEA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"to-openai-messages.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/to-openai-messages.ts"],"sourcesContent":["import { InvalidRequestError, type ContentPart, type Message } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/**\n * Convert vendor-neutral Message[] to OpenAI's chat message shape.\n * Handles the `tool` role (requires `tool_call_id`) and assistant messages\n * that carry `toolCalls` from a prior model response.\n *\n * Multipart `content` (a `ContentPart[]`) is mapped into OpenAI's user-message\n * content-parts shape: text becomes `{ type: \"text\", text }`, images become\n * `{ type: \"image_url\", image_url: { url } }` — with base64 sources rendered\n * as `data:` URLs inline.\n *\n * @example\n * const openaiMessages = toOpenAIMessages([\n * { role: \"user\", content: \"Hi\" },\n * { role: \"tool\", toolCallId: \"call_1\", content: '{\"ok\":true}' },\n * ]);\n *\n * @example\n * toOpenAIMessages([\n * { role: \"user\", content: [\n * { type: \"text\", text: \"What is this?\" },\n * { type: \"image\", source: { url: \"https://example.com/cat.jpg\" } },\n * ]},\n * ]);\n */\nexport function toOpenAIMessages(\n messages: Message[],\n cacheBreakpoints: number = 0,\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n const mapped = messages.map((m) => {\n if (m.role === \"tool\") {\n return {\n role: \"tool\",\n content: stringifyContent(m.content),\n tool_call_id: m.toolCallId ?? \"\",\n } satisfies OpenAI.Chat.Completions.ChatCompletionToolMessageParam;\n }\n if (m.role === \"assistant\" && m.toolCalls && m.toolCalls.length > 0) {\n return {\n role: \"assistant\",\n content: stringifyContent(m.content),\n tool_calls: m.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: { name: tc.name, arguments: JSON.stringify(tc.input ?? {}) },\n })),\n } satisfies OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam;\n }\n\n if (m.role === \"user\" && Array.isArray(m.content)) {\n return {\n role: \"user\",\n content: m.content.map(toOpenAIContentPart),\n } satisfies OpenAI.Chat.Completions.ChatCompletionUserMessageParam;\n }\n\n return { role: m.role, content: stringifyContent(m.content) } as\n | OpenAI.Chat.Completions.ChatCompletionUserMessageParam\n | OpenAI.Chat.Completions.ChatCompletionSystemMessageParam\n | OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam;\n });\n\n return addPromptCacheBreakpoints(mapped, cacheBreakpoints);\n}\n\n/** Place explicit markers on the last requested user-content parts (maximum four). */\nfunction addPromptCacheBreakpoints(\n messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],\n requested: number,\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n let remaining = Math.min(4, Math.max(0, Math.floor(requested)));\n if (remaining === 0) return messages;\n\n const marked = [...messages];\n for (let index = marked.length - 1; index >= 0 && remaining > 0; index--) {\n const message = marked[index];\n if (message === undefined || message.role !== \"user\") continue;\n\n if (typeof message.content === \"string\") {\n marked[index] = {\n ...message,\n content: [\n { type: \"text\", text: message.content, prompt_cache_breakpoint: { mode: \"explicit\" } },\n ],\n };\n remaining--;\n continue;\n }\n\n const content = [...message.content];\n for (let partIndex = content.length - 1; partIndex >= 0 && remaining > 0; partIndex--) {\n const part = content[partIndex];\n if (part === undefined) continue;\n content[partIndex] = { ...part, prompt_cache_breakpoint: { mode: \"explicit\" } };\n remaining--;\n }\n marked[index] = { ...message, content };\n }\n\n return marked;\n}\n\n/**\n * Multipart content is only meaningful on user messages — for any other\n * role (system / assistant text / tool), collapse a `ContentPart[]` to\n * its concatenated text so OpenAI's wire format stays valid. Plain\n * strings pass through unchanged.\n */\nexport function stringifyContent(content: string | ContentPart[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n}\n\n/**\n * Map a resolved `ContentPart` to an OpenAI chat content part — one\n * branch per modality, each to its real wire shape:\n *\n * - `text` → `{ type: \"text\" }`.\n * - `image` → `{ type: \"image_url\" }` (remote URL, or a `data:` URL for\n * inlined base64 bytes).\n * - `pdf` → `{ type: \"file\", file: { file_data } }` (OpenAI document\n * input; base64 only — there is no remote-URL file source).\n * - `audio` → `{ type: \"input_audio\", input_audio: { data, format } }`\n * (base64 only; `wav` / `mp3` are the only formats OpenAI accepts).\n *\n * PDF and audio reach this point ONLY when the model declared the\n * matching capability (`openai.model({ name, pdf: true })` /\n * `{ audio: true }`) — the agent's modality gate throws upfront\n * otherwise, so capability and behavior stay in lockstep. A remote-URL\n * pdf/audio source raises a typed `InvalidRequestError` here rather\n * than a downstream provider fault.\n */\nfunction toOpenAIContentPart(part: ContentPart): OpenAI.Chat.Completions.ChatCompletionContentPart {\n if (part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n\n if (part.type === \"image\") {\n return { type: \"image_url\", image_url: { url: toImageUrl(part.source) } };\n }\n\n if (part.type === \"pdf\") {\n if (\"url\" in part.source) {\n throw new InvalidRequestError(\n \"OpenAI chat completions cannot fetch a remote-URL PDF; supply base64 document bytes instead.\",\n );\n }\n\n return {\n type: \"file\",\n file: {\n filename: \"document.pdf\",\n file_data: `data:${part.source.mediaType};base64,${part.source.base64}`,\n },\n };\n }\n\n // Audio — the remaining `ContentPart` variant.\n if (\"url\" in part.source) {\n throw new InvalidRequestError(\n \"OpenAI chat completions cannot fetch remote-URL audio; supply base64 audio bytes instead.\",\n );\n }\n\n return {\n type: \"input_audio\",\n input_audio: {\n data: part.source.base64,\n format: toOpenAIAudioFormat(part.source.mediaType),\n },\n };\n}\n\n/**\n * Render an image source as a URL: a remote URL passes through, inlined\n * base64 bytes become a `data:` URL. Shared with the Responses adapter.\n */\nexport function toImageUrl(\n source: Extract<ContentPart, { type: \"image\" }>[\"source\"],\n): string {\n return \"url\" in source ? source.url : `data:${source.mediaType};base64,${source.base64}`;\n}\n\n/**\n * Narrow a neutral audio media type to the two formats OpenAI's\n * `input_audio` accepts (`wav` / `mp3`). An unsupported type raises a\n * typed `InvalidRequestError` up front rather than a provider 400.\n */\nfunction toOpenAIAudioFormat(mediaType: string): \"wav\" | \"mp3\" {\n if (mediaType === \"audio/wav\" || mediaType === \"audio/x-wav\" || mediaType === \"audio/wave\") {\n return \"wav\";\n }\n\n if (mediaType === \"audio/mp3\" || mediaType === \"audio/mpeg\" || mediaType === \"audio/mpga\") {\n return \"mp3\";\n }\n\n throw new InvalidRequestError(\n `OpenAI input_audio supports only \"wav\" and \"mp3\"; got \"${mediaType}\".`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,iBACd,UACA,mBAA2B,GAC2B;CAkCtD,OAAO,0BAjCQ,SAAS,KAAK,MAAM;EACjC,IAAI,EAAE,SAAS,QACb,OAAO;GACL,MAAM;GACN,SAAS,iBAAiB,EAAE,OAAO;GACnC,cAAc,EAAE,cAAc;EAChC;EAEF,IAAI,EAAE,SAAS,eAAe,EAAE,aAAa,EAAE,UAAU,SAAS,GAChE,OAAO;GACL,MAAM;GACN,SAAS,iBAAiB,EAAE,OAAO;GACnC,YAAY,EAAE,UAAU,KAAK,QAAQ;IACnC,IAAI,GAAG;IACP,MAAM;IACN,UAAU;KAAE,MAAM,GAAG;KAAM,WAAW,KAAK,UAAU,GAAG,SAAS,CAAC,CAAC;IAAE;GACvE,EAAE;EACJ;EAGF,IAAI,EAAE,SAAS,UAAU,MAAM,Q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SAAS,oBAAoB,MAAsE;CACjG,IAAI,KAAK,SAAS,QAChB,OAAO;EAAE,MAAM;EAAQ,MAAM,KAAK;CAAK;CAGzC,IAAI,KAAK,SAAS,SAChB,OAAO;EAAE,MAAM;EAAa,WAAW,EAAE,KAAK,WAAW,KAAK,MAAM,EAAE;CAAE;CAG1E,IAAI,KAAK,SAAS,OAAO;EACvB,IAAI,SAAS,KAAK,QAChB,MAAM,IAAI,oBACR,8FACF;EAGF,OAAO;GACL,MAAM;GACN,MAAM;IACJ,UAAU;IACV,WAAW,QAAQ,KAAK,OAAO,UAAU,UAAU,KAAK,OAAO;GACjE;EACF;CACF;CAGA,IAAI,SAAS,KAAK,QAChB,MAAM,IAAI,oBACR,2FACF;CAGF,OAAO;EACL,MAAM;EACN,aAAa;GACX,MAAM,KAAK,OAAO;GAClB,QAAQ,oBAAoB,KAAK,OAAO,SAAS;EACnD;CACF;AACF;;;;;AAMA,SAAgB,WACd,QACQ;CACR,OAAO,SAAS,SAAS,OAAO,MAAM,QAAQ,OAAO,UAAU,UAAU,OAAO;AAClF;;;;;;AAOA,SAAS,oBAAoB,WAAkC;CAC7D,IAAI,cAAc,eAAe,cAAc,iBAAiB,cAAc,cAC5E,OAAO;CAGT,IAAI,cAAc,eAAe,cAAc,gBAAgB,cAAc,cAC3E,OAAO;CAGT,MAAM,IAAI,oBACR,0DAA0D,UAAU,GACtE;AACF"}
1
+ {"version":3,"file":"to-openai-messages.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/to-openai-messages.ts"],"sourcesContent":["import { InvalidRequestError, type ContentPart, type Message } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/**\n * Convert vendor-neutral Message[] to OpenAI's chat message shape.\n * Handles the `tool` role (requires `tool_call_id`) and assistant messages\n * that carry `toolCalls` from a prior model response.\n *\n * Multipart `content` (a `ContentPart[]`) is mapped into OpenAI's user-message\n * content-parts shape: text becomes `{ type: \"text\", text }`, images become\n * `{ type: \"image_url\", image_url: { url } }` — with base64 sources rendered\n * as `data:` URLs inline.\n *\n * @example\n * const openaiMessages = toOpenAIMessages([\n * { role: \"user\", content: \"Hi\" },\n * { role: \"tool\", toolCallId: \"call_1\", content: '{\"ok\":true}' },\n * ]);\n *\n * @example\n * toOpenAIMessages([\n * { role: \"user\", content: [\n * { type: \"text\", text: \"What is this?\" },\n * { type: \"image\", source: { url: \"https://example.com/cat.jpg\" } },\n * ]},\n * ]);\n */\nexport function toOpenAIMessages(\n messages: Message[],\n cacheBreakpoints: number = 0,\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n const mapped = messages.map((m) => {\n if (m.role === \"tool\") {\n return {\n role: \"tool\",\n content: stringifyContent(m.content),\n tool_call_id: m.toolCallId ?? \"\",\n } satisfies OpenAI.Chat.Completions.ChatCompletionToolMessageParam;\n }\n if (m.role === \"assistant\" && m.toolCalls && m.toolCalls.length > 0) {\n return {\n role: \"assistant\",\n content: stringifyContent(m.content),\n tool_calls: m.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: { name: tc.name, arguments: JSON.stringify(tc.input ?? {}) },\n })),\n } satisfies OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam;\n }\n\n if (m.role === \"user\" && Array.isArray(m.content)) {\n return {\n role: \"user\",\n content: m.content.map(toOpenAIContentPart),\n } satisfies OpenAI.Chat.Completions.ChatCompletionUserMessageParam;\n }\n\n return { role: m.role, content: stringifyContent(m.content) } as\n | OpenAI.Chat.Completions.ChatCompletionUserMessageParam\n | OpenAI.Chat.Completions.ChatCompletionSystemMessageParam\n | OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam;\n });\n\n return addPromptCacheBreakpoints(mapped, cacheBreakpoints);\n}\n\n/** Place explicit markers on the last requested user-content parts (maximum four). */\nfunction addPromptCacheBreakpoints(\n messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],\n requested: number,\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n let remaining = Math.min(4, Math.max(0, Math.floor(requested)));\n if (remaining === 0) return messages;\n\n const marked = [...messages];\n for (let index = marked.length - 1; index >= 0 && remaining > 0; index--) {\n const message = marked[index];\n if (message === undefined || message.role !== \"user\") continue;\n\n if (typeof message.content === \"string\") {\n marked[index] = {\n ...message,\n content: [\n { type: \"text\", text: message.content, prompt_cache_breakpoint: { mode: \"explicit\" } },\n ],\n };\n remaining--;\n continue;\n }\n\n const content = [...message.content];\n for (let partIndex = content.length - 1; partIndex >= 0 && remaining > 0; partIndex--) {\n const part = content[partIndex];\n if (part === undefined) continue;\n content[partIndex] = { ...part, prompt_cache_breakpoint: { mode: \"explicit\" } };\n remaining--;\n }\n marked[index] = { ...message, content };\n }\n\n return marked;\n}\n\n/**\n * Multipart content is only meaningful on user messages — for any other\n * role (system / assistant text / tool), collapse a `ContentPart[]` to\n * its concatenated text so OpenAI's wire format stays valid. Plain\n * strings pass through unchanged.\n */\nexport function stringifyContent(content: string | ContentPart[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n}\n\n/**\n * Map a resolved `ContentPart` to an OpenAI chat content part — one\n * branch per modality, each to its real wire shape:\n *\n * - `text` → `{ type: \"text\" }`.\n * - `image` → `{ type: \"image_url\" }` (remote URL, or a `data:` URL for\n * inlined base64 bytes).\n * - `pdf` → `{ type: \"file\", file: { file_data } }` (OpenAI document\n * input; base64 only — there is no remote-URL file source).\n * - `audio` → `{ type: \"input_audio\", input_audio: { data, format } }`\n * (base64 only; `wav` / `mp3` are the only formats OpenAI accepts).\n *\n * PDF and audio reach this point ONLY when the model declared the\n * matching capability (`openai.model({ name, pdf: true })` /\n * `{ audio: true }`) — the agent's modality gate throws upfront\n * otherwise, so capability and behavior stay in lockstep. A remote-URL\n * pdf/audio source raises a typed `InvalidRequestError` here rather\n * than a downstream provider fault.\n */\nfunction toOpenAIContentPart(part: ContentPart): OpenAI.Chat.Completions.ChatCompletionContentPart {\n if (part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n\n if (part.type === \"image\") {\n return { type: \"image_url\", image_url: { url: toImageUrl(part.source) } };\n }\n\n if (part.type === \"pdf\") {\n if (\"url\" in part.source) {\n throw new InvalidRequestError(\n \"OpenAI chat completions cannot fetch a remote-URL PDF; supply base64 document bytes instead.\",\n );\n }\n\n return {\n type: \"file\",\n file: {\n filename: \"document.pdf\",\n file_data: `data:${part.source.mediaType};base64,${part.source.base64}`,\n },\n };\n }\n\n // Audio — the remaining `ContentPart` variant.\n if (\"url\" in part.source) {\n throw new InvalidRequestError(\n \"OpenAI chat completions cannot fetch remote-URL audio; supply base64 audio bytes instead.\",\n );\n }\n\n return {\n type: \"input_audio\",\n input_audio: {\n data: part.source.base64,\n format: toOpenAIAudioFormat(part.source.mediaType),\n },\n };\n}\n\n/**\n * Render an image source as a URL: a remote URL passes through, inlined\n * base64 bytes become a `data:` URL. Shared with the Responses adapter.\n */\nexport function toImageUrl(source: Extract<ContentPart, { type: \"image\" }>[\"source\"]): string {\n return \"url\" in source ? source.url : `data:${source.mediaType};base64,${source.base64}`;\n}\n\n/**\n * Narrow a neutral audio media type to the two formats OpenAI's\n * `input_audio` accepts (`wav` / `mp3`). An unsupported type raises a\n * typed `InvalidRequestError` up front rather than a provider 400.\n */\nfunction toOpenAIAudioFormat(mediaType: string): \"wav\" | \"mp3\" {\n if (mediaType === \"audio/wav\" || mediaType === \"audio/x-wav\" || mediaType === \"audio/wave\") {\n return \"wav\";\n }\n\n if (mediaType === \"audio/mp3\" || mediaType === \"audio/mpeg\" || mediaType === \"audio/mpga\") {\n return \"mp3\";\n }\n\n throw new InvalidRequestError(\n `OpenAI input_audio supports only \"wav\" and \"mp3\"; got \"${mediaType}\".`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,iBACd,UACA,mBAA2B,GAC2B;CAkCtD,OAAO,0BAjCQ,SAAS,KAAK,MAAM;E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,cAC3E,OAAO;CAGT,MAAM,IAAI,oBACR,0DAA0D,UAAU,GACtE;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"to-openai-tools.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/to-openai-tools.ts"],"sourcesContent":["import { extractJsonSchema, type ToolConfig } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/**\n * Convert vendor-neutral ToolConfig[] to OpenAI's tools array.\n * Uses the shared `extractJsonSchema` helper; falls back to an empty-object\n * schema when extraction fails so the tool still registers with the provider.\n *\n * @example\n * const tools = toOpenAITools([weatherTool, calculatorTool]);\n * await client.chat.completions.create({ model, messages, tools });\n */\nexport function toOpenAITools(\n tools: ToolConfig<unknown, unknown>[] | undefined,\n): OpenAI.Chat.Completions.ChatCompletionTool[] | undefined {\n if (!tools || tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: toToolParameters(tool.input),\n },\n }));\n}\n\n/**\n * Resolve a tool's input schema to a JSON-Schema object. OpenAI's\n * function `parameters` expects an object root; anything else (or a\n * failed extraction) degrades to an empty-object schema so the tool\n * still registers and the model simply sees no parameters.\n */\nexport function toToolParameters(input: ToolConfig<unknown, unknown>[\"input\"]): Record<string, unknown> {\n const schema = extractJsonSchema(input);\n\n if (schema && schema.type === \"object\") {\n return schema;\n }\n\n return { type: \"object\", properties: {} };\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAgB,cACd,OAC0D;CAC1D,IAAI,CAAC,SAAS,MAAM,WAAW,GAC7B;CAGF,OAAO,MAAM,KAAK,UAAU;EAC1B,MAAM;EACN,UAAU;GACR,MAAM,KAAK;GACX,aAAa,KAAK;GAClB,YAAY,iBAAiB,KAAK,KAAK;EACzC;CACF,EAAE;AACJ;;;;;;;AAQA,SAAgB,iBAAiB,OAAuE;CACtG,MAAM,SAAS,kBAAkB,KAAK;CAEtC,IAAI,UAAU,OAAO,SAAS,UAC5B,OAAO;CAGT,OAAO;EAAE,MAAM;EAAU,YAAY,CAAC;CAAE;AAC1C"}
1
+ {"version":3,"file":"to-openai-tools.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/to-openai-tools.ts"],"sourcesContent":["import { extractJsonSchema, type ToolConfig } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/**\n * Convert vendor-neutral ToolConfig[] to OpenAI's tools array.\n * Uses the shared `extractJsonSchema` helper; falls back to an empty-object\n * schema when extraction fails so the tool still registers with the provider.\n *\n * @example\n * const tools = toOpenAITools([weatherTool, calculatorTool]);\n * await client.chat.completions.create({ model, messages, tools });\n */\nexport function toOpenAITools(\n tools: ToolConfig<unknown, unknown>[] | undefined,\n): OpenAI.Chat.Completions.ChatCompletionTool[] | undefined {\n if (!tools || tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: toToolParameters(tool.input),\n },\n }));\n}\n\n/**\n * Resolve a tool's input schema to a JSON-Schema object. OpenAI's\n * function `parameters` expects an object root; anything else (or a\n * failed extraction) degrades to an empty-object schema so the tool\n * still registers and the model simply sees no parameters.\n */\nexport function toToolParameters(\n input: ToolConfig<unknown, unknown>[\"input\"],\n): Record<string, unknown> {\n const schema = extractJsonSchema(input);\n\n if (schema && schema.type === \"object\") {\n return schema;\n }\n\n return { type: \"object\", properties: {} };\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAgB,cACd,OAC0D;CAC1D,IAAI,CAAC,SAAS,MAAM,WAAW,GAC7B;CAGF,OAAO,MAAM,KAAK,UAAU;EAC1B,MAAM;EACN,UAAU;GACR,MAAM,KAAK;GACX,aAAa,KAAK;GAClB,YAAY,iBAAiB,KAAK,KAAK;EACzC;CACF,EAAE;AACJ;;;;;;;AAQA,SAAgB,iBACd,OACyB;CACzB,MAAM,SAAS,kBAAkB,KAAK;CAEtC,IAAI,UAAU,OAAO,SAAS,UAC5B,OAAO;CAGT,OAAO;EAAE,MAAM;EAAU,YAAY,CAAC;CAAE;AAC1C"}
@@ -1,5 +1,5 @@
1
1
  import OpenAI from "openai";
2
- import { AIError, ContentFilterError, ContextLengthExceededError, InvalidRequestError, ProviderAuthError, ProviderError, ProviderRateLimitError, ProviderTimeoutError, QuotaExceededError } from "@warlock.js/ai";
2
+ import { AIError, ContentFilterError, ContextLengthExceededError, InvalidRequestError, ProviderAuthError, ProviderError, ProviderOverloadedError, ProviderRateLimitError, ProviderTimeoutError, QuotaExceededError } from "@warlock.js/ai";
3
3
 
4
4
  //#region ../../packages/ai-openai/src/utils/wrap-openai-error.ts
5
5
  /**
@@ -58,6 +58,11 @@ function wrapOpenAIError(thrown) {
58
58
  cause: thrown,
59
59
  context
60
60
  });
61
+ if (shape.code === "server_is_overloaded" || shape.status === 503) return new ProviderOverloadedError(message, {
62
+ cause: thrown,
63
+ context,
64
+ retryAfter: parseRetryAfter(shape.headers)
65
+ });
61
66
  return new ProviderError(message, {
62
67
  cause: thrown,
63
68
  context
@@ -1 +1 @@
1
- {"version":3,"file":"wrap-openai-error.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/wrap-openai-error.ts"],"sourcesContent":["import {\n AIError,\n ContentFilterError,\n ContextLengthExceededError,\n InvalidRequestError,\n ProviderAuthError,\n ProviderError,\n ProviderRateLimitError,\n ProviderTimeoutError,\n QuotaExceededError,\n} from \"@warlock.js/ai\";\nimport OpenAI from \"openai\";\n\n/**\n * Raw-error fields the wrapper reads off an OpenAI SDK error.\n *\n * `APIError` exposes `status`, `code`, `message`, `type`, `headers` —\n * we duck-type because wrapped retries, proxied errors, and custom\n * error subclasses sometimes lose the `instanceof` relationship.\n */\ntype OpenAIErrorShape = {\n status?: number;\n code?: string | null;\n message?: string;\n type?: string | null;\n /** The request parameter the provider rejected, e.g. `max_tokens`. */\n param?: string | null;\n headers?: Record<string, string> | undefined;\n name?: string;\n};\n\n/**\n * Wrap any thrown value caught inside the OpenAI adapter into the\n * appropriate `@warlock.js/ai` `AIError` subclass.\n *\n * **Dispatch strategy.** Prefers `APIError.code` when present (stable\n * machine identifier across SDK versions), falls back to `status` when\n * `code` is missing (common with proxied deployments that strip the\n * field). Name-based detection (`APIConnectionTimeoutError`) catches\n * transport-layer errors that never produced an HTTP response.\n *\n * `AIError` instances are returned unchanged — callers can pass the\n * error through `try/catch/throw wrap(e)` pipelines without accidental\n * double-wrapping.\n *\n * @example\n * try {\n * return await this.client.chat.completions.create(...);\n * } catch (thrown) {\n * throw wrapOpenAIError(thrown);\n * }\n */\nexport function wrapOpenAIError(thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n const shape = toShape(thrown);\n const context = buildContext(thrown, shape);\n const message = shape.message ?? (thrown instanceof Error ? thrown.message : String(thrown));\n\n if (isTimeout(thrown, shape)) {\n return new ProviderTimeoutError(message, { cause: thrown, context });\n }\n\n if (shape.status === 401 || shape.code === \"invalid_api_key\") {\n return new ProviderAuthError(message, { cause: thrown, context });\n }\n\n if (shape.code === \"insufficient_quota\") {\n return new QuotaExceededError(message, { cause: thrown, context });\n }\n\n if (shape.status === 429 || shape.code === \"rate_limit_exceeded\") {\n return new ProviderRateLimitError(message, {\n cause: thrown,\n context,\n retryAfter: parseRetryAfter(shape.headers),\n });\n }\n\n if (shape.code === \"context_length_exceeded\") {\n return new ContextLengthExceededError(message, { cause: thrown, context });\n }\n\n if (shape.code === \"content_filter\") {\n return new ContentFilterError(message, {\n cause: thrown,\n context,\n reason: message,\n });\n }\n\n if (typeof shape.status === \"number\" && shape.status >= 400 && shape.status < 500) {\n return new InvalidRequestError(message, { cause: thrown, context });\n }\n\n return new ProviderError(message, { cause: thrown, context });\n}\n\n/**\n * Read the raw error shape without depending on `instanceof APIError`\n * — some consumers wrap the SDK, and proxies sometimes strip the\n * prototype chain. Duck-typing on the visible fields is resilient to\n * both.\n */\nfunction toShape(thrown: unknown): OpenAIErrorShape {\n if (thrown instanceof OpenAI.APIError) {\n return {\n status: thrown.status,\n code: thrown.code,\n message: thrown.message,\n type: thrown.type,\n param: thrown.param,\n headers: thrown.headers as Record<string, string> | undefined,\n name: thrown.name,\n };\n }\n\n if (typeof thrown === \"object\" && thrown !== null) {\n const raw = thrown as Record<string, unknown>;\n\n return {\n status: typeof raw.status === \"number\" ? raw.status : undefined,\n code: typeof raw.code === \"string\" ? raw.code : undefined,\n message: typeof raw.message === \"string\" ? raw.message : undefined,\n type: typeof raw.type === \"string\" ? raw.type : undefined,\n param: typeof raw.param === \"string\" ? raw.param : undefined,\n headers:\n typeof raw.headers === \"object\" && raw.headers !== null\n ? (raw.headers as Record<string, string>)\n : undefined,\n name: typeof raw.name === \"string\" ? raw.name : undefined,\n };\n }\n\n return {};\n}\n\n/**\n * Decide whether the thrown value represents a timeout. OpenAI's SDK\n * throws `APIConnectionTimeoutError` for transport-level timeouts, and\n * Node surfaces `ETIMEDOUT` / `ECONNABORTED` on the lower socket\n * layer. Either signal counts.\n */\nfunction isTimeout(thrown: unknown, shape: OpenAIErrorShape): boolean {\n if (thrown instanceof OpenAI.APIConnectionTimeoutError) {\n return true;\n }\n\n if (shape.name === \"APIConnectionTimeoutError\") {\n return true;\n }\n\n if (shape.code === \"ETIMEDOUT\" || shape.code === \"ECONNABORTED\") {\n return true;\n }\n\n return false;\n}\n\n/**\n * Attach the raw diagnostic fields to `error.context` so consumers\n * have everything the provider surfaced without each subclass having\n * to redeclare them. Never includes `cause` — that lives on\n * `error.cause`.\n */\nfunction buildContext(\n thrown: unknown,\n shape: OpenAIErrorShape,\n): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n\n if (shape.status !== undefined) {\n context.status = shape.status;\n }\n\n if (shape.code) {\n context.code = shape.code;\n }\n\n if (shape.type) {\n context.type = shape.type;\n }\n\n if (shape.param) {\n context.param = shape.param;\n }\n\n const requestId = readRequestId(thrown);\n\n if (requestId) {\n context.requestId = requestId;\n }\n\n return context;\n}\n\n/**\n * The request id OpenAI returned. Current SDKs expose it as\n * `APIError.requestID`; older ones and hand-rolled errors use\n * `request_id` / `requestId`. Extract defensively.\n */\nfunction readRequestId(thrown: unknown): string | undefined {\n if (typeof thrown !== \"object\" || thrown === null) {\n return undefined;\n }\n\n const raw = thrown as Record<string, unknown>;\n\n if (typeof raw.request_id === \"string\") {\n return raw.request_id;\n }\n\n if (typeof raw.requestId === \"string\") {\n return raw.requestId;\n }\n\n if (typeof raw.requestID === \"string\") {\n return raw.requestID;\n }\n\n return undefined;\n}\n\n/**\n * Parse the `Retry-After` response header (seconds per HTTP spec)\n * into milliseconds so consumers can feed it straight to `setTimeout`.\n * Returns `undefined` when missing or unparseable.\n */\nfunction parseRetryAfter(headers: Record<string, string> | undefined): number | undefined {\n if (!headers) {\n return undefined;\n }\n\n const raw = headers[\"retry-after\"] ?? headers[\"Retry-After\"];\n\n if (!raw) {\n return undefined;\n }\n\n const seconds = Number(raw);\n\n if (!Number.isFinite(seconds) || seconds < 0) {\n return undefined;\n }\n\n return Math.round(seconds * 1000);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,gBAAgB,QAA0B;CACxD,IAAI,kBAAkB,SACpB,OAAO;CAGT,MAAM,QAAQ,QAAQ,MAAM;CAC5B,MAAM,UAAU,aAAa,QAAQ,KAAK;CAC1C,MAAM,UAAU,MAAM,YAAY,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM;CAE1F,IAAI,UAAU,QAAQ,KAAK,GACzB,OAAO,IAAI,qBAAqB,SAAS;EAAE,OAAO;EAAQ;CAAQ,CAAC;CAGrE,IAAI,MAAM,WAAW,OAAO,MAAM,SAAS,mBACzC,OAAO,IAAI,kBAAkB,SAAS;EAAE,OAAO;EAAQ;CAAQ,CAAC;CAGlE,IAAI,MAAM,SAAS,sBACjB,OAAO,IAAI,mBAAmB,SAAS;EAAE,OAAO;EAAQ;CAAQ,CAAC;CAGnE,IAAI,MAAM,WAAW,OAAO,MAAM,SAAS,uBACzC,OAAO,IAAI,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,6BACjB,OAAO;CAGT,IAAI,MAAM,SAAS,eAAe,MAAM,SAAS,gBAC/C,OAAO;CAGT,OAAO;AACT;;;;;;;AAQA,SAAS,aACP,QACA,OACyB;CACzB,MAAM,UAAmC,CAAC;CAE1C,IAAI,MAAM,WAAW,QACnB,QAAQ,SAAS,MAAM;CAGzB,IAAI,MAAM,MACR,QAAQ,OAAO,MAAM;CAGvB,IAAI,MAAM,MACR,QAAQ,OAAO,MAAM;CAGvB,IAAI,MAAM,OACR,QAAQ,QAAQ,MAAM;CAGxB,MAAM,YAAY,cAAc,MAAM;CAEtC,IAAI,WACF,QAAQ,YAAY;CAGtB,OAAO;AACT;;;;;;AAOA,SAAS,cAAc,QAAqC;CAC1D,IAAI,OAAO,WAAW,YAAY,WAAW,MAC3C;CAGF,MAAM,MAAM;CAEZ,IAAI,OAAO,IAAI,eAAe,UAC5B,OAAO,IAAI;CAGb,IAAI,OAAO,IAAI,cAAc,UAC3B,OAAO,IAAI;CAGb,IAAI,OAAO,IAAI,cAAc,UAC3B,OAAO,IAAI;AAIf;;;;;;AAOA,SAAS,gBAAgB,SAAiE;CACxF,IAAI,CAAC,SACH;CAGF,MAAM,MAAM,QAAQ,kBAAkB,QAAQ;CAE9C,IAAI,CAAC,KACH;CAGF,MAAM,UAAU,OAAO,GAAG;CAE1B,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,UAAU,GACzC;CAGF,OAAO,KAAK,MAAM,UAAU,GAAI;AAClC"}
1
+ {"version":3,"file":"wrap-openai-error.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/wrap-openai-error.ts"],"sourcesContent":["import {\n AIError,\n ContentFilterError,\n ContextLengthExceededError,\n InvalidRequestError,\n ProviderAuthError,\n ProviderError,\n ProviderOverloadedError,\n ProviderRateLimitError,\n ProviderTimeoutError,\n QuotaExceededError,\n} from \"@warlock.js/ai\";\nimport OpenAI from \"openai\";\n\n/**\n * Raw-error fields the wrapper reads off an OpenAI SDK error.\n *\n * `APIError` exposes `status`, `code`, `message`, `type`, `headers` —\n * we duck-type because wrapped retries, proxied errors, and custom\n * error subclasses sometimes lose the `instanceof` relationship.\n */\ntype OpenAIErrorShape = {\n status?: number;\n code?: string | null;\n message?: string;\n type?: string | null;\n /** The request parameter the provider rejected, e.g. `max_tokens`. */\n param?: string | null;\n headers?: Record<string, string> | undefined;\n name?: string;\n};\n\n/**\n * Wrap any thrown value caught inside the OpenAI adapter into the\n * appropriate `@warlock.js/ai` `AIError` subclass.\n *\n * **Dispatch strategy.** Prefers `APIError.code` when present (stable\n * machine identifier across SDK versions), falls back to `status` when\n * `code` is missing (common with proxied deployments that strip the\n * field). Name-based detection (`APIConnectionTimeoutError`) catches\n * transport-layer errors that never produced an HTTP response.\n *\n * `AIError` instances are returned unchanged — callers can pass the\n * error through `try/catch/throw wrap(e)` pipelines without accidental\n * double-wrapping.\n *\n * @example\n * try {\n * return await this.client.chat.completions.create(...);\n * } catch (thrown) {\n * throw wrapOpenAIError(thrown);\n * }\n */\nexport function wrapOpenAIError(thrown: unknown): AIError {\n if (thrown instanceof AIError) {\n return thrown;\n }\n\n const shape = toShape(thrown);\n const context = buildContext(thrown, shape);\n const message = shape.message ?? (thrown instanceof Error ? thrown.message : String(thrown));\n\n if (isTimeout(thrown, shape)) {\n return new ProviderTimeoutError(message, { cause: thrown, context });\n }\n\n if (shape.status === 401 || shape.code === \"invalid_api_key\") {\n return new ProviderAuthError(message, { cause: thrown, context });\n }\n\n if (shape.code === \"insufficient_quota\") {\n return new QuotaExceededError(message, { cause: thrown, context });\n }\n\n if (shape.status === 429 || shape.code === \"rate_limit_exceeded\") {\n return new ProviderRateLimitError(message, {\n cause: thrown,\n context,\n retryAfter: parseRetryAfter(shape.headers),\n });\n }\n\n if (shape.code === \"context_length_exceeded\") {\n return new ContextLengthExceededError(message, { cause: thrown, context });\n }\n\n if (shape.code === \"content_filter\") {\n return new ContentFilterError(message, {\n cause: thrown,\n context,\n reason: message,\n });\n }\n\n if (typeof shape.status === \"number\" && shape.status >= 400 && shape.status < 500) {\n return new InvalidRequestError(message, { cause: thrown, context });\n }\n\n // OpenAI: 503 `service_unavailable_error` / `server_is_overloaded`\n // (https://developers.openai.com/api/docs/guides/error-codes). The\n // OpenAI-compatible wrappers use 503 for the same condition (DeepSeek\n // documents 503 \"Server Overloaded\").\n if (shape.code === \"server_is_overloaded\" || shape.status === 503) {\n return new ProviderOverloadedError(message, {\n cause: thrown,\n context,\n retryAfter: parseRetryAfter(shape.headers),\n });\n }\n\n return new ProviderError(message, { cause: thrown, context });\n}\n\n/**\n * Read the raw error shape without depending on `instanceof APIError`\n * — some consumers wrap the SDK, and proxies sometimes strip the\n * prototype chain. Duck-typing on the visible fields is resilient to\n * both.\n */\nfunction toShape(thrown: unknown): OpenAIErrorShape {\n if (thrown instanceof OpenAI.APIError) {\n return {\n status: thrown.status,\n code: thrown.code,\n message: thrown.message,\n type: thrown.type,\n param: thrown.param,\n headers: thrown.headers as Record<string, string> | undefined,\n name: thrown.name,\n };\n }\n\n if (typeof thrown === \"object\" && thrown !== null) {\n const raw = thrown as Record<string, unknown>;\n\n return {\n status: typeof raw.status === \"number\" ? raw.status : undefined,\n code: typeof raw.code === \"string\" ? raw.code : undefined,\n message: typeof raw.message === \"string\" ? raw.message : undefined,\n type: typeof raw.type === \"string\" ? raw.type : undefined,\n param: typeof raw.param === \"string\" ? raw.param : undefined,\n headers:\n typeof raw.headers === \"object\" && raw.headers !== null\n ? (raw.headers as Record<string, string>)\n : undefined,\n name: typeof raw.name === \"string\" ? raw.name : undefined,\n };\n }\n\n return {};\n}\n\n/**\n * Decide whether the thrown value represents a timeout. OpenAI's SDK\n * throws `APIConnectionTimeoutError` for transport-level timeouts, and\n * Node surfaces `ETIMEDOUT` / `ECONNABORTED` on the lower socket\n * layer. Either signal counts.\n */\nfunction isTimeout(thrown: unknown, shape: OpenAIErrorShape): boolean {\n if (thrown instanceof OpenAI.APIConnectionTimeoutError) {\n return true;\n }\n\n if (shape.name === \"APIConnectionTimeoutError\") {\n return true;\n }\n\n if (shape.code === \"ETIMEDOUT\" || shape.code === \"ECONNABORTED\") {\n return true;\n }\n\n return false;\n}\n\n/**\n * Attach the raw diagnostic fields to `error.context` so consumers\n * have everything the provider surfaced without each subclass having\n * to redeclare them. Never includes `cause` — that lives on\n * `error.cause`.\n */\nfunction buildContext(thrown: unknown, shape: OpenAIErrorShape): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n\n if (shape.status !== undefined) {\n context.status = shape.status;\n }\n\n if (shape.code) {\n context.code = shape.code;\n }\n\n if (shape.type) {\n context.type = shape.type;\n }\n\n if (shape.param) {\n context.param = shape.param;\n }\n\n const requestId = readRequestId(thrown);\n\n if (requestId) {\n context.requestId = requestId;\n }\n\n return context;\n}\n\n/**\n * The request id OpenAI returned. Current SDKs expose it as\n * `APIError.requestID`; older ones and hand-rolled errors use\n * `request_id` / `requestId`. Extract defensively.\n */\nfunction readRequestId(thrown: unknown): string | undefined {\n if (typeof thrown !== \"object\" || thrown === null) {\n return undefined;\n }\n\n const raw = thrown as Record<string, unknown>;\n\n if (typeof raw.request_id === \"string\") {\n return raw.request_id;\n }\n\n if (typeof raw.requestId === \"string\") {\n return raw.requestId;\n }\n\n if (typeof raw.requestID === \"string\") {\n return raw.requestID;\n }\n\n return undefined;\n}\n\n/**\n * Parse the `Retry-After` response header (seconds per HTTP spec)\n * into milliseconds so consumers can feed it straight to `setTimeout`.\n * Returns `undefined` when missing or unparseable.\n */\nfunction parseRetryAfter(headers: Record<string, string> | undefined): number | undefined {\n if (!headers) {\n return undefined;\n }\n\n const raw = headers[\"retry-after\"] ?? headers[\"Retry-After\"];\n\n if (!raw) {\n return undefined;\n }\n\n const seconds = Number(raw);\n\n if (!Number.isFinite(seconds) || seconds < 0) {\n return undefined;\n }\n\n return Math.round(seconds * 1000);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgB,gBAAgB,QAA0B;CACxD,IAAI,kBAAkB,SACpB,OA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AAc,UAC3B,OAAO,IAAI;CAGb,IAAI,OAAO,IAAI,cAAc,UAC3B,OAAO,IAAI;AAIf;;;;;;AAOA,SAAS,gBAAgB,SAAiE;CACxF,IAAI,CAAC,SACH;CAGF,MAAM,MAAM,QAAQ,kBAAkB,QAAQ;CAE9C,IAAI,CAAC,KACH;CAGF,MAAM,UAAU,OAAO,GAAG;CAE1B,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,UAAU,GACzC;CAGF,OAAO,KAAK,MAAM,UAAU,GAAI;AAClC"}
package/llms-full.txt CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  ---
10
10
  name: setup-openai
11
- description: 'Wire @warlock.js/ai-openai — new OpenAISDK({apiKey, baseURL?, provider?, pricing?}) for OpenAI / Azure / OpenRouter, .model({name, vision?, reasoning?, structuredOutput?, responseFormat?, pdf?, audio?}) for ModelContract, .embedder({name, dimensions?}) for embeddings, .image({name, pricing?}) for gpt-image-*/dall-e-* image generation (via ai.image). PDF input maps to OpenAI file parts (opt-in pdf:true), audio input to input_audio (opt-in audio:true). Triggers: `OpenAISDK`, `.model`, `.embedder`, `.image`, `.embed`, `.embedMany`, `baseURL`, `pricing`, `responseSchema`, `responseFormat`, `reasoning_effort`, `reasoningTokens`, `cachedTokens`, `gpt-image`, `dall-e`, `ai.image`, `pdf input`, `input_audio`, o-series / gpt-5 reasoning, `api: "responses"`, Responses API, reasoning with tools, prompt caching; "wire openai into a warlock agent", "configure gpt-4o", "use o3 / gpt-5 reasoning effort", "route through openrouter or azure openai", "openai embeddings with warlock", "generate images with gpt-image / dall-e", "send a pdf / audio to gpt-4o"; typical import `import { OpenAISDK } from "@warlock.js/ai-openai"`. Skip: the ai.image verb surface — the `generate-images` topic of the `warlock-js-ai` skill; agent wiring — the `run-ai-agent` topic of the `warlock-js-ai` skill; adapter comparison — the `pick-ai-provider` topic of the `warlock-js-ai` skill; competing adapters `@warlock.js/ai-anthropic`, `@warlock.js/ai-bedrock`, `@warlock.js/ai-google`, `@warlock.js/ai-ollama`; raw `openai` SDK, Vercel `@ai-sdk/openai`.'
11
+ description: 'Wire @warlock.js/ai-openai — new OpenAISDK({apiKey, baseURL?, provider?, pricing?}) for OpenAI / Azure / OpenRouter, .model({name, vision?, reasoning?, structuredOutput?, responseFormat?, pdf?, audio?}) for ModelContract, .embedder({name, dimensions?}) for embeddings, .image({name, pricing?}) for gpt-image-*/dall-e-* image generation (via ai.image). PDF input maps to OpenAI file parts (opt-in pdf:true), audio input to input_audio (opt-in audio:true). Triggers: `providerOptions`, `OpenAICallOptions`, `countTokens`, `OpenAISDK`, `.model`, `.embedder`, `.image`, `.embed`, `.embedMany`, `baseURL`, `pricing`, `responseSchema`, `responseFormat`, `reasoning_effort`, `reasoningTokens`, `cachedTokens`, `cacheWriteTokens`, `inputIncludesCache`, `OPENAI_MODEL_PRICING`, `openAIPricingFor`, `ProviderOverloadedError`, `gpt-image`, `dall-e`, `ai.image`, `pdf input`, `input_audio`, o-series / gpt-5 reasoning, `api: "responses"`, Responses API, `ai.providerTool`, hosted `web_search`, `streamChunks`, `reasoning_content`, reasoning with tools, prompt caching; "wire openai into a warlock agent", "configure gpt-4o", "use o3 / gpt-5 reasoning effort", "route through openrouter or azure openai", "openai embeddings with warlock", "generate images with gpt-image / dall-e", "send a pdf / audio to gpt-4o"; typical import `import { OpenAISDK } from "@warlock.js/ai-openai"`. Skip: the ai.image verb surface — the `generate-images` topic of the `warlock-js-ai` skill; agent wiring — the `run-ai-agent` topic of the `warlock-js-ai` skill; adapter comparison — the `pick-ai-provider` topic of the `warlock-js-ai` skill; competing adapters `@warlock.js/ai-anthropic`, `@warlock.js/ai-bedrock`, `@warlock.js/ai-google`, `@warlock.js/ai-ollama`; raw `openai` SDK, Vercel `@ai-sdk/openai`.'
12
12
  ---
13
13
 
14
14
  # `@warlock.js/ai-openai`
@@ -39,23 +39,23 @@ const openrouter = new OpenAISDK({
39
39
  ## Producing a model
40
40
 
41
41
  ```ts
42
- openai.model({ name: "gpt-4o-mini" }) // common case
43
- openai.model({ name: "gpt-4o", temperature: 0.2 }) // sampling controls
44
- openai.model({ name: "fine-tuned-x", vision: true }) // explicit capability override
42
+ openai.model({ name: "gpt-4o-mini" }); // common case
43
+ openai.model({ name: "gpt-4o", temperature: 0.2 }); // sampling controls
44
+ openai.model({ name: "fine-tuned-x", vision: true }); // explicit capability override
45
45
  ```
46
46
 
47
47
  Returns a `ModelContract` you pass straight into `ai.agent({ model })`.
48
48
 
49
49
  ## Capabilities — what's auto-set
50
50
 
51
- | Flag | Default |
52
- | --- | --- |
53
- | `structuredOutput` | `true`, unless `responseFormat` is set to `"json_object"` or `"text"` (loose modes) — then `false`. |
54
- | `vision` | Inferred from model name. `true` for `gpt-4o*`, `gpt-4-turbo*`, `gpt-4.1*`, `o1*`, `o3*`, `chatgpt-4o*`; `false` otherwise. |
55
- | `reasoning` | Inferred from model name. `true` for the o-series (`o1*`, `o3*`, `o4*`) and the `gpt-5*` family; `false` otherwise. Drives whether `reasoning_effort` is forwarded. |
56
- | `promptCaching` | `true` for the direct OpenAI provider. It supports automatic cache hits plus explicit content-part write breakpoints; OpenAI-compatible wrapper providers leave the OpenAI-only fields off. |
57
- | `pdf` | `false` by default (opt-in `.model({ pdf: true })`). OpenAI accepts PDF `file` parts only on specific models (the `gpt-4o` family) — honest off until you set it. |
58
- | `audio` | `false` by default (opt-in `.model({ audio: true })`). Only the `gpt-4o-audio-preview` family accepts `input_audio`. |
51
+ | Flag | Default |
52
+ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
53
+ | `structuredOutput` | `true`, unless `responseFormat` is set to `"json_object"` or `"text"` (loose modes) — then `false`. |
54
+ | `vision` | Inferred from model name. `true` for `gpt-4o*`, `gpt-4-turbo*`, `gpt-4.1*`, `o1*`, `o3*`, `chatgpt-4o*`; `false` otherwise. |
55
+ | `reasoning` | Inferred from model name. `true` for the o-series (`o1*`, `o3*`, `o4*`) and the `gpt-5*` family; `false` otherwise. Drives whether `reasoning_effort` is forwarded. |
56
+ | `promptCaching` | `true` for the direct OpenAI provider. It supports automatic cache hits plus explicit content-part write breakpoints; wrappers send only `prompt_cache_key`, and only where the endpoint documents it (xAI, Mistral). |
57
+ | `pdf` | `false` by default (opt-in `.model({ pdf: true })`). OpenAI accepts PDF `file` parts only on specific models (the `gpt-4o` family) — honest off until you set it. |
58
+ | `audio` | `false` by default (opt-in `.model({ audio: true })`). Only the `gpt-4o-audio-preview` family accepts `input_audio`. |
59
59
 
60
60
  **Override `vision`, `structuredOutput`, `reasoning`, `pdf`, or `audio` explicitly** via `.model({ name, vision?, structuredOutput?, reasoning?, pdf?, audio? })` — an explicit value always wins over inference.
61
61
 
@@ -66,8 +66,8 @@ When the agent passes `responseSchema` (a JSON Schema object), the adapter conve
66
66
  Some targets reject strict `json_schema` (older OpenAI models, OpenRouter routes, Ollama OpenAI-compat). Override the wire mode per model with `responseFormat`:
67
67
 
68
68
  ```ts
69
- openai.model({ name: "legacy-model", responseFormat: "json_object" }) // valid JSON, no strict shape
70
- openai.model({ name: "some-route", responseFormat: "text" }) // no response_format on the wire
69
+ openai.model({ name: "legacy-model", responseFormat: "json_object" }); // valid JSON, no strict shape
70
+ openai.model({ name: "some-route", responseFormat: "text" }); // no response_format on the wire
71
71
  ```
72
72
 
73
73
  `"json_object"` and `"text"` also flip `structuredOutput` to `false`, so the agent re-injects the schema as a soft prompt hint. Pin `structuredOutput` explicitly to override that.
@@ -90,7 +90,7 @@ PDF and audio reach the wire only when the model declares the matching capabilit
90
90
 
91
91
  ```ts
92
92
  const gpt = openai.image({ name: "gpt-image-1", pricing: { input: 5, output: 40 } }); // token-metered
93
- const dalle = openai.image({ name: "dall-e-3", pricing: { perImage: 0.04 } }); // per-image
93
+ const dalle = openai.image({ name: "dall-e-3", pricing: { perImage: 0.04 } }); // per-image
94
94
 
95
95
  const { data } = await ai.image({ model: gpt, prompt: "a red bicycle", size: "1024x1024" });
96
96
  ```
@@ -105,6 +105,20 @@ const { data } = await ai.image({ model: gpt, prompt: "a red bicycle", size: "10
105
105
 
106
106
  Tool-call argument fragments arrive split across deltas; the adapter accumulates them per `tool_calls[n].index` and parses the assembled JSON once on completion, so streamed tool calls round-trip identically to non-streaming `complete()`. Accumulators that never received a function name are skipped.
107
107
 
108
+ Opt-in chunks (`options.streamChunks`, set by `agent.stream()`): Chat yields `{ type: "tool-args", callId, name, delta }` per argument fragment and `{ type: "reasoning", delta }` for a compatible vendor's `delta.reasoning_content` (DeepSeek) / `delta.reasoning` (Groq); Responses yields `reasoning` for `response.reasoning_summary_text.delta` / `response.reasoning_text.delta` (summaries need `body: { reasoning: { summary: "auto" } }`) and `tool-args` for `response.function_call_arguments.delta`. No `usage` chunk (usage arrives at the end).
109
+
110
+ ## Provider-defined tools
111
+
112
+ With `api: "responses"`, `ai.providerTool({ provider: "openai", definition })` appends hosted tools verbatim (`{ type: "web_search" }`, `file_search`, `code_interpreter`, `image_generation`, `mcp`). Hosted-call items are not replayed (`store: false`), and a reasoning item that led into one is dropped from the replay. Client-run built-ins (`shell_call`, `apply_patch_call`, `computer_call`, `custom_tool_call`, `local_shell_call`, `mcp_approval_request`) throw `InvalidRequestError`. On Chat Completions a provider tool is sent only when `provider` equals the model's provider label (e.g. Groq `{ type: "browser_search" }` with `provider: "groq"`).
113
+
114
+ ```ts
115
+ const model = openai.model({ name: "gpt-5.6", api: "responses" });
116
+ ai.agent({
117
+ model,
118
+ tools: [ai.providerTool({ provider: "openai", definition: { type: "web_search" } }), lookupOrder],
119
+ });
120
+ ```
121
+
108
122
  ## Embeddings
109
123
 
110
124
  ```ts
@@ -125,8 +139,8 @@ openai.embedder({ name: "text-embedding-3-large", dimensions: 256 });
125
139
  Reasoning models accept a discrete effort knob. The agent passes it through `ModelCallOptions.reasoning`:
126
140
 
127
141
  ```ts
128
- const model = openai.model({ name: "o3-mini" }); // reasoning auto-true
129
- await model.complete(messages, { reasoning: { effort: "high" } }); // → reasoning_effort: "high"
142
+ const model = openai.model({ name: "o3-mini" }); // reasoning auto-true
143
+ await model.complete(messages, { reasoning: { effort: "high" } }); // → reasoning_effort: "high"
130
144
  ```
131
145
 
132
146
  - `reasoning.effort` (`"low" | "medium" | "high" | "none"`) maps verbatim to OpenAI's `reasoning_effort` request param.
@@ -146,8 +160,8 @@ reasoning_effort to 'none'.
146
160
  Since there is no working alternative to `"none"` in that state, the adapter defaults to it automatically: whenever a call is made to a reasoning-capable model WITH `tools` AND the caller supplied no `reasoning.effort` at all, `reasoning_effort: "none"` is emitted for you — no opt-in required.
147
161
 
148
162
  ```ts
149
- const model = openai.model({ name: "gpt-5-mini" }); // reasoning auto-true
150
- await model.complete(messages, { tools }); // → reasoning_effort: "none", automatically
163
+ const model = openai.model({ name: "gpt-5-mini" }); // reasoning auto-true
164
+ await model.complete(messages, { tools }); // → reasoning_effort: "none", automatically
151
165
  ```
152
166
 
153
167
  An explicit `reasoning.effort` always overrides the default, in either direction — pass it yourself if you want a different value (and accept that tools may then be rejected, per the error above, since Chat Completions still can't do reasoning + tools together):
@@ -188,15 +202,18 @@ await model.complete(messages, { tools, reasoning: { effort: "high" } }); // rea
188
202
 
189
203
  `usage` on the result carries the neutral channel breakdown, populated from OpenAI's `usage` block:
190
204
 
191
- | `Usage` field | OpenAI source | Notes |
192
- | --- | --- | --- |
193
- | `input` / `output` / `total` | `prompt_tokens` / `completion_tokens` / `total_tokens` | always present (zeroed if OpenAI omits the block). |
194
- | `cachedTokens` | `prompt_tokens_details.cached_tokens` | subset of `input` served from OpenAI's automatic prompt cache. Emitted only when > 0. |
195
- | `reasoningTokens` | `completion_tokens_details.reasoning_tokens` | hidden reasoning channel on o-series / gpt-5 (already counted within `output`). Emitted only when > 0. |
205
+ | `Usage` field | OpenAI source | Notes |
206
+ | ---------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
207
+ | `input` / `output` / `total` | `prompt_tokens` / `completion_tokens` / `total_tokens` | always present (zeroed if OpenAI omits the block). |
208
+ | `inputIncludesCache` | — (always `true`) | `prompt_tokens` already contains the cached and cache-written tokens; cost bills them out of it once. |
209
+ | `cachedTokens` | `prompt_tokens_details.cached_tokens` | subset of `input` served from OpenAI's automatic prompt cache. Emitted only when > 0. |
210
+ | `cacheWriteTokens` | `prompt_tokens_details.cache_write_tokens` | subset of `input` written to the cache, on the models that charge for writes. Emitted only when > 0. |
211
+ | `reasoningTokens` | `completion_tokens_details.reasoning_tokens` | hidden reasoning channel on o-series / gpt-5 (already counted within `output`). Emitted only when > 0. |
212
+ | `cost` | computed | per-channel USD when the model is priced (see [Pricing](#pricing--built-in-list-prices-and-registry)). |
196
213
 
197
- Both `cachedTokens` and `reasoningTokens` are omitted (not set to `0`) when the provider reports zero, so non-reasoning / uncached calls keep the lean `{ input, output, total }` shape. Reported identically on `complete()` and the streaming `done` event.
214
+ The detail counters are omitted (not set to `0`) when the provider reports zero, so non-reasoning / uncached calls keep the lean `{ input, output, total, inputIncludesCache }` shape. Reported identically on `complete()`, the streaming `done` event and the Responses API (`input_tokens_details.cached_tokens` / `cache_write_tokens`). The OpenAI-compatible wrappers (DeepSeek, xAI, Groq, Mistral) report the same fields and the same inclusive semantics.
198
215
 
199
- ### Explicit prompt caching (direct OpenAI only)
216
+ ### Explicit prompt caching
200
217
 
201
218
  Chat Completions exposes OpenAI-specific cache controls on current SDK types. Configure a stable cache bucket and (when needed) its maximum retention policy per model:
202
219
 
@@ -210,39 +227,113 @@ const model = openai.model({
210
227
 
211
228
  `promptCacheKey` improves matching for related requests. `promptCacheRetention` is OpenAI's maximum policy (`"in_memory" | "24h"`). `cacheControl.breakpoints` maps to `prompt_cache_breakpoint: { mode: "explicit" }` on the final user content parts (up to OpenAI's four-request limit); use it when you need to pin a reusable prefix rather than rely only on OpenAI's implicit breakpoint.
212
229
 
213
- These fields are sent only when the SDK provider label is exactly `"openai"`. `DeepSeekSDK`, `GroqSDK`, `XaiSDK`, and `MistralSDK` label their wrapped endpoint differently, so their requests omit every OpenAI-only cache field even though they reuse this transport. Read-side `usage.cachedTokens` accounting remains available whenever the upstream reports it.
230
+ Which fields reach the wire depends on the SDK provider label:
231
+
232
+ | Provider label | `prompt_cache_key` | `prompt_cache_retention` / explicit breakpoints | Why |
233
+ | ---------------------- | ------------------ | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
234
+ | `"openai"` | sent | sent | https://developers.openai.com/api/docs/guides/prompt-caching |
235
+ | `"xai"` | sent | — | xAI Chat Completions accepts `prompt_cache_key` (routed as `x-grok-conv-id`) — https://docs.x.ai/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits |
236
+ | `"mistral"` | sent | — | https://docs.mistral.ai/studio/conversations/advanced/prompt-caching |
237
+ | `"groq"`, `"deepseek"` | — | — | both cache automatically and document no request hint |
238
+ | any custom label | — | — | an unknown endpoint may reject the fields |
239
+
240
+ (Checked 2026-10-17.) `XaiSDK` and `MistralSDK` keep their default labels unless you pass `provider`, so `xai.model({ name, promptCacheKey })` works out of the box. Read-side `usage.cachedTokens` accounting remains available whenever the upstream reports it.
214
241
 
215
242
  ## Token counting
216
243
 
217
244
  ```ts
218
- await openai.count("some text") // approximate (heuristic, not tiktoken)
245
+ await openai.count("some text"); // approximate (heuristic, not tiktoken)
219
246
  ```
220
247
 
221
248
  Good enough for budgeting; not for billing.
222
249
 
223
- ## Pricing — per-model registry
250
+ ## Pricing — built-in list prices and registry
224
251
 
225
- `pricing` is a **registry keyed by model name** — one entry per model, all rates in **USD per 1,000,000 tokens** (`ModelPricing`: `input`, `output`, optional `cachedInput` / `cachedOutput`).
252
+ All rates are **USD per 1,000,000 tokens** (`ModelPricing`: `input`, `output`, optional `cachedInput`, `cacheWrite`, `cacheWrite1h`, `reasoning`). Resolution at `model()` time: per-model `pricing` (`openai.model({ name, pricing })`) > SDK `pricing` registry > built-in `OPENAI_MODEL_PRICING` (only when the SDK provider label is `"openai"`, exact model id) > `undefined` (no cost computed).
226
253
 
227
254
  ```ts
255
+ import { ai, totalCost } from "@warlock.js/ai";
256
+ import { OPENAI_MODEL_PRICING, OpenAISDK, openAIPricingFor } from "@warlock.js/ai-openai";
257
+
228
258
  const openai = new OpenAISDK({
229
- apiKey,
259
+ apiKey: process.env.OPENAI_API_KEY ?? "",
230
260
  pricing: {
231
- // USD per 1M tokens.
232
- "gpt-4o-mini": { input: 0.15, output: 0.6, cachedInput: 0.075 },
233
- "gpt-4o": { input: 2.5, output: 10, cachedInput: 1.25 },
261
+ // Prompt-length-tiered models have no built-in rate — price them yourself.
262
+ "gpt-5.5": { input: 5, output: 30, cachedInput: 0.5 },
234
263
  },
235
264
  });
236
265
 
266
+ openai.model({ name: "gpt-4o-mini" }).pricing; // built-in: { input: 0.15, output: 0.6, cachedInput: 0.075 }
267
+ openAIPricingFor("gpt-4o-2024-05-13"); // undefined — dated snapshots can carry other prices
268
+ Object.keys(OPENAI_MODEL_PRICING); // the priced ids
269
+
237
270
  const { usage } = await ai.agent({ model: openai.model({ name: "gpt-4o-mini" }) }).execute("hi");
238
- usage.cost; // { input, output, cachedInput?, cachedOutput? } — per-channel USD breakdown of THIS run
271
+ console.log(usage.cost, totalCost(usage.cost)); // per-channel USD breakdown of THIS run, and its sum
272
+
273
+ // A direct call is costed too — no agent needed.
274
+ const side = await openai
275
+ .model({ name: "gpt-4.1-mini" })
276
+ .complete([{ role: "user", content: "Classify: …" }]);
277
+ console.log(totalCost(side.usage.cost));
239
278
  ```
240
279
 
241
- The registry is per-model; `usage.cost` is the per-channel breakdown the framework computes from `tokens × pricing[model]`. Resolution at `model()` time: per-model `pricing` (`openai.model({ name, pricing })`) > SDK registry > `undefined` (no cost computed). See the `pick-ai-provider` topic of the `warlock-js-ai` skill.
280
+ - **Source.** `OPENAI_MODEL_PRICING` comes from https://developers.openai.com/api/docs/pricing (the target of platform.openai.com/docs/pricing), Standard tier, fetched 2026-10-17. It covers the flat-priced models: `gpt-5.4-mini`, `gpt-5.4-nano`, `gpt-5.2`, `gpt-5.1`, `gpt-5`, `gpt-5-mini`, `gpt-5-nano`, `gpt-4.1` (+ `-mini` / `-nano`), `gpt-4o`, `gpt-4o-mini`, `o3`, `o4-mini`, `o3-mini`, `o1`. None of them charges for cache writes.
281
+ - **Deliberately unpriced:** models priced by prompt length (a higher rate above 272K input tokens — the gpt-6, gpt-5.6, gpt-5.5 and gpt-5.4 families and the `-pro` models), dated snapshot ids, promotional / Batch / Flex / Priority pricing, and the regional data-residency uplift. Wrapper SDKs (`provider` other than `"openai"`) never fall back to this table.
242
282
 
243
283
  ## Errors
244
284
 
245
- Raw OpenAI SDK errors are wrapped into the typed `@warlock.js/ai` `AIError` hierarchy via the adapter's error wrapper. Dispatch keys on `APIError.status + code` combined — see the `handle-ai-errors` topic of the `warlock-js-ai` skill.
285
+ Raw OpenAI SDK errors are wrapped into the typed `@warlock.js/ai` `AIError` hierarchy via the adapter's error wrapper. Dispatch keys on `APIError.status + code` combined — see the `handle-ai-errors` topic of the `warlock-js-ai` skill. HTTP 503 and code `server_is_overloaded` (https://developers.openai.com/api/docs/guides/error-codes) map to `ProviderOverloadedError` (`code: "PROVIDER_OVERLOADED"`, `retryable: true`, `retryAfter` from `retry-after`); the compatible wrappers use 503 for the same condition (DeepSeek documents it as "Server Overloaded"). Every wrapped error carries `status`, `retryable` and `billed` — `false` for 401 / 402 / 403, otherwise `"unknown"`, because OpenAI publishes no rule for failed requests.
286
+
287
+ ```ts
288
+ import { ai, ProviderOverloadedError } from "@warlock.js/ai";
289
+ import { OpenAISDK } from "@warlock.js/ai-openai";
290
+
291
+ const openai = new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY ?? "" });
292
+ const result = await ai.agent({ model: openai.model({ name: "gpt-4o-mini" }) }).execute("hi");
293
+
294
+ if (result.error instanceof ProviderOverloadedError) {
295
+ console.log(result.error.status, result.error.retryAfter); // back off, or fall back to another model
296
+ }
297
+ ```
298
+
299
+ ## Provider body options and input-token counts
300
+
301
+ Native body fields merge after neutral options. When both values are plain
302
+ objects, their immediate keys merge and caller-provided keys win; untouched
303
+ neutral fields remain. Arrays, scalars and `null` replace the field. This merge
304
+ is one level deep: a nested object explicitly supplied by the caller replaces
305
+ that nested value. When both objects have string `type` discriminators and the
306
+ caller changes the type, the whole object is replaced. For example, overriding
307
+ `response_format` from `json_schema` to `json_object` removes the old
308
+ `json_schema` fields; switching `tool_choice` variants removes old variant fields
309
+ as well. The rule also applies to OpenAI-compatible adapters using this helper.
310
+
311
+ `providerOptions.openai.body` adds native request fields to Chat Completions or
312
+ Responses, merged after the neutral options. For example:
313
+
314
+ ```ts
315
+ const options = { providerOptions: { openai: { body: { service_tier: "default" } } } };
316
+ await model.complete(messages, options);
317
+ ```
318
+
319
+ The key stays `openai` for compatible gateways with a custom provider label.
320
+ Other provider keys are ignored. `OpenAICallOptions` is exported. The body cannot
321
+ replace `model`, `messages`, `input`, `instructions`, `tools`, `stream`,
322
+ `stream_options`, `previous_response_id`, `conversation`, `store`, `include`, `functions`, `function_call`, `prompt` or `background`;
323
+ those fields protect the adapter's conversation, tools and stateless replay.
324
+
325
+ Models using `api: "responses"` expose native `countTokens(messages, options?)`
326
+ through `responses.inputTokens.count`: the same input, system instructions,
327
+ tools, reasoning, text format, tool choice, parallel-tool setting and truncation
328
+ used for generation are counted. The endpoint supports only input-shaping fields;
329
+ output caps and generation-only options are omitted. The Chat Completions model
330
+ has no `countTokens` method. `sdk.count(text)` remains a separate offline estimate.
331
+
332
+ ```ts
333
+ if (model.countTokens) {
334
+ const inputTokens = await model.countTokens(messages, options);
335
+ }
336
+ ```
246
337
 
247
338
  ## When NOT to use this skill
248
339
 
package/llms.txt CHANGED
@@ -6,4 +6,4 @@
6
6
 
7
7
  ## Skills
8
8
 
9
- - [setup-openai](@warlock.js/ai-openai/setup-openai/SKILL.md): Wire @warlock.js/ai-openai — new OpenAISDK({apiKey, baseURL?, provider?, pricing?}) for OpenAI / Azure / OpenRouter, .model({name, vision?, reasoning?, structuredOutput?, responseFormat?, pdf?, audio?}) for ModelContract, .embedder({name, dimensions?}) for embeddings, .image({name, pricing?}) for gpt-image-*/dall-e-* image generation (via ai.image). PDF input maps to OpenAI file parts (opt-in pdf:true), audio input to input_audio (opt-in audio:true). Triggers: `OpenAISDK`, `.model`, `.embedder`, `.image`, `.embed`, `.embedMany`, `baseURL`, `pricing`, `responseSchema`, `responseFormat`, `reasoning_effort`, `reasoningTokens`, `cachedTokens`, `gpt-image`, `dall-e`, `ai.image`, `pdf input`, `input_audio`, o-series / gpt-5 reasoning, `api: "responses"`, Responses API, reasoning with tools, prompt caching; "wire openai into a warlock agent", "configure gpt-4o", "use o3 / gpt-5 reasoning effort", "route through openrouter or azure openai", "openai embeddings with warlock", "generate images with gpt-image / dall-e", "send a pdf / audio to gpt-4o"; typical import `import { OpenAISDK } from "@warlock.js/ai-openai"`. Skip: the ai.image verb surface — the `generate-images` topic of the `warlock-js-ai` skill; agent wiring — the `run-ai-agent` topic of the `warlock-js-ai` skill; adapter comparison — the `pick-ai-provider` topic of the `warlock-js-ai` skill; competing adapters `@warlock.js/ai-anthropic`, `@warlock.js/ai-bedrock`, `@warlock.js/ai-google`, `@warlock.js/ai-ollama`; raw `openai` SDK, Vercel `@ai-sdk/openai`.
9
+ - [setup-openai](@warlock.js/ai-openai/setup-openai/SKILL.md): Wire @warlock.js/ai-openai — new OpenAISDK({apiKey, baseURL?, provider?, pricing?}) for OpenAI / Azure / OpenRouter, .model({name, vision?, reasoning?, structuredOutput?, responseFormat?, pdf?, audio?}) for ModelContract, .embedder({name, dimensions?}) for embeddings, .image({name, pricing?}) for gpt-image-*/dall-e-* image generation (via ai.image). PDF input maps to OpenAI file parts (opt-in pdf:true), audio input to input_audio (opt-in audio:true). Triggers: `providerOptions`, `OpenAICallOptions`, `countTokens`, `OpenAISDK`, `.model`, `.embedder`, `.image`, `.embed`, `.embedMany`, `baseURL`, `pricing`, `responseSchema`, `responseFormat`, `reasoning_effort`, `reasoningTokens`, `cachedTokens`, `cacheWriteTokens`, `inputIncludesCache`, `OPENAI_MODEL_PRICING`, `openAIPricingFor`, `ProviderOverloadedError`, `gpt-image`, `dall-e`, `ai.image`, `pdf input`, `input_audio`, o-series / gpt-5 reasoning, `api: "responses"`, Responses API, `ai.providerTool`, hosted `web_search`, `streamChunks`, `reasoning_content`, reasoning with tools, prompt caching; "wire openai into a warlock agent", "configure gpt-4o", "use o3 / gpt-5 reasoning effort", "route through openrouter or azure openai", "openai embeddings with warlock", "generate images with gpt-image / dall-e", "send a pdf / audio to gpt-4o"; typical import `import { OpenAISDK } from "@warlock.js/ai-openai"`. Skip: the ai.image verb surface — the `generate-images` topic of the `warlock-js-ai` skill; agent wiring — the `run-ai-agent` topic of the `warlock-js-ai` skill; adapter comparison — the `pick-ai-provider` topic of the `warlock-js-ai` skill; competing adapters `@warlock.js/ai-anthropic`, `@warlock.js/ai-bedrock`, `@warlock.js/ai-google`, `@warlock.js/ai-ollama`; raw `openai` SDK, Vercel `@ai-sdk/openai`.
package/package.json CHANGED
@@ -15,12 +15,12 @@
15
15
  },
16
16
  "dependencies": {
17
17
  "openai": "^7.23.0",
18
- "@warlock.js/logger": "5.30.0"
18
+ "@warlock.js/logger": "5.31.0"
19
19
  },
20
20
  "peerDependencies": {
21
- "@warlock.js/ai": "5.30.0"
21
+ "@warlock.js/ai": "5.31.0"
22
22
  },
23
- "version": "5.30.0",
23
+ "version": "5.31.0",
24
24
  "main": "./cjs/index.cjs",
25
25
  "module": "./esm/index.mjs",
26
26
  "types": "./esm/index.d.mts",