@openclaw/ai 2026.8.1-beta.3 → 2026.8.1

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 (89) hide show
  1. package/dist/{anthropic-B8KwTtlb.mjs → anthropic-Djj7L1rx.mjs} +21 -21
  2. package/dist/{anthropic-compaction-replay-4Zx7-aCr.mjs → anthropic-compaction-replay-CY4tkD4V.mjs} +33 -34
  3. package/dist/{anthropic-payload-policy-CSx7MoKH.d.mts → anthropic-payload-policy-i_5_inWe.d.mts} +3 -2
  4. package/dist/{api-registry-DFxSnFqG.d.mts → api-registry-C9-wZd_W.d.mts} +2 -1
  5. package/dist/{azure-openai-responses-Aa4mVcYG.mjs → azure-openai-responses-Bj3czHNa.mjs} +4 -4
  6. package/dist/{number-coercion-H9qHik3g.mjs → base64-CEFBpSkN.mjs} +73 -1
  7. package/dist/diagnostics.d.mts +2 -3
  8. package/dist/diagnostics.mjs +1 -1
  9. package/dist/{env-api-keys-DrgeBuva.mjs → env-api-keys-bktO00EJ.mjs} +2 -15
  10. package/dist/event-stream-C988TSLe.d.mts +1 -0
  11. package/dist/{event-stream-D91-ohD_.d.mts → event-stream-UhnxHuqt.d.mts} +1 -2
  12. package/dist/event-stream.d.mts +2 -1
  13. package/dist/{google-yDRnipeq.mjs → google-0Ca6TYbw.mjs} +4 -4
  14. package/dist/{google-shared-M1dl64nz.mjs → google-shared-DVfL9COU.mjs} +14 -7
  15. package/dist/{google-vertex-DCJHM_a5.mjs → google-vertex-5dAMxprN.mjs} +4 -4
  16. package/dist/{host-DF_yxOsA.mjs → host-D51fmkH6.mjs} +4 -8
  17. package/dist/{host-DJq_FGcz.d.mts → host-DoPJJ1KD.d.mts} +3 -3
  18. package/dist/index-N3zr6__t.d.mts +105 -0
  19. package/dist/index.d.mts +9 -10
  20. package/dist/index.mjs +2 -3
  21. package/dist/internal/anthropic.d.mts +51 -49
  22. package/dist/internal/anthropic.mjs +5 -5
  23. package/dist/internal/openai-responses-payload-policy.d.mts +3 -3
  24. package/dist/internal/openai-responses-payload-policy.mjs +2 -3
  25. package/dist/internal/openai.d.mts +65 -63
  26. package/dist/internal/openai.mjs +10 -9
  27. package/dist/internal/retry-after.d.mts +2 -3
  28. package/dist/internal/runtime.d.mts +51 -40
  29. package/dist/internal/runtime.mjs +9 -9
  30. package/dist/internal/shared.d.mts +25 -25
  31. package/dist/internal/shared.mjs +3 -3
  32. package/dist/{json-parse-CDnesDM_.mjs → json-parse-BuAJEbdW.mjs} +18 -2
  33. package/dist/{mistral-D6hRXI7A.mjs → mistral-BCnrI-kV.mjs} +22 -25
  34. package/dist/{openai-chatgpt-responses-C339VIfT.mjs → openai-chatgpt-responses-CGBGWSqr.mjs} +31 -14
  35. package/dist/openai-completions-BaTuwID7.mjs +401 -0
  36. package/dist/{openai-completions-compat-B0KTleXp.d.mts → openai-completions-compat-DB7FFq7k.d.mts} +3 -3
  37. package/dist/openai-completions-stream-Bpns6uNc.mjs +1622 -0
  38. package/dist/{openai-responses-BXEcr-Tp.mjs → openai-responses-1GBcQujk.mjs} +8 -6
  39. package/dist/openai-responses-compaction-window-DwydGZI8.mjs +686 -0
  40. package/dist/{openai-responses-contracts-CD75pQ0m.d.mts → openai-responses-contracts-DgaR3t5T.d.mts} +14 -5
  41. package/dist/{openai-responses-payload-policy-CNGFT9zr.d.mts → openai-responses-payload-policy-rLRPsSmB.d.mts} +1 -0
  42. package/dist/{openai-responses-prompt-observer-internal-BG-1AsBI.mjs → openai-responses-prompt-observer-internal-_nhGTn2b.mjs} +3 -2
  43. package/dist/{openai-responses-shared-Cvt5MgEm.mjs → openai-responses-shared-zPmKnhF5.mjs} +315 -1468
  44. package/dist/openai-stop-reason-Drnn_6Qj.mjs +28 -0
  45. package/dist/openai-tool-schema-Dgl4H2MU.mjs +1695 -0
  46. package/dist/{provider-error-C8mBRJDl.mjs → provider-error-jZP5NMTZ.mjs} +3 -77
  47. package/dist/{provider-options-Cc5ZQ6Aa.d.mts → provider-options-HvA_slFa.d.mts} +13 -4
  48. package/dist/{provider-transcript-transform--gtf0ZbR.mjs → provider-transcript-transform-C01bQ5a3.mjs} +1 -1
  49. package/dist/provider-types.d.mts +18 -17
  50. package/dist/providers.d.mts +5 -6
  51. package/dist/providers.mjs +9 -9
  52. package/dist/{reasoning-tag-text-partitioner-5ygO2rZc.mjs → reasoning-tag-text-partitioner-CwzKb0bA.mjs} +1 -1
  53. package/dist/rolldown-runtime-BhDjJH2R.mjs +15 -0
  54. package/dist/{sanitize-unicode-BP7HLLZn.mjs → sanitize-unicode-DCkltN94.mjs} +1 -2
  55. package/dist/simple-options-DKx86yX9.mjs +155 -0
  56. package/dist/{anthropic-BQXQudmA.mjs → src-Bu3FiFAG.mjs} +1 -0
  57. package/dist/{stream-first-event-timeout-MK28puvq.mjs → stream-first-event-timeout-DcNjoFQE.mjs} +1 -1
  58. package/dist/{streaming-byte-guard-BrbkbwUu.mjs → streaming-byte-guard-CC-HMn_u.mjs} +5 -6
  59. package/dist/string-normalization--fwJ4S2q.mjs +16 -0
  60. package/dist/{tool-schema-json-projection-FEr-jOoZ.mjs → tool-schema-json-projection-qvTEs5Am.mjs} +2 -2
  61. package/dist/{simple-options-oqsXB6U3.mjs → transport-stream-shared-CT5ycdzn.mjs} +10 -118
  62. package/dist/transport-stream-shared-NjwWNaRY.d.mts +138 -0
  63. package/dist/{transport-utils-Bv0FHkd0.mjs → transport-utils-BHx9z8Cl.mjs} +9 -9
  64. package/dist/transports.d.mts +127 -189
  65. package/dist/transports.mjs +181 -1214
  66. package/dist/types-DtGu2d3C.d.mts +1 -0
  67. package/dist/{types-DTAP49HF.d.mts → types-h38Azne1.d.mts} +38 -17
  68. package/dist/types.d.mts +5 -4
  69. package/dist/types.mjs +1 -2
  70. package/dist/utf16-slice-qz3nsy87.mjs +84 -0
  71. package/dist/{validation-DYNNrU9u.d.mts → validation-C68lP2uy.d.mts} +1 -2
  72. package/dist/validation.d.mts +1 -1
  73. package/package.json +6 -6
  74. package/dist/anthropic-BECQCNdF.d.mts +0 -98
  75. package/dist/event-stream-BVVgDSdq.d.mts +0 -1
  76. package/dist/headers-B_e4-1J0.mjs +0 -9
  77. package/dist/index-BVVgDSdq.d.mts +0 -1
  78. package/dist/openai-completions-D88orSJ9.mjs +0 -632
  79. package/dist/openai-responses-contracts-DvILoqBk.mjs +0 -247
  80. package/dist/openai-responses-payload-policy-BDo8CQsx.mjs +0 -208
  81. package/dist/openai-stop-reason-9OONKyAm.mjs +0 -579
  82. package/dist/openai-tool-projection-CHGLt03m.mjs +0 -426
  83. package/dist/provider-options-AvldWZt8.mjs +0 -21
  84. package/dist/record-coerce-DdXsgUd_.mjs +0 -23
  85. package/dist/src-D2H6yKkH.mjs +0 -2
  86. package/dist/stream-first-event-timeout-DvDeSucC.d.mts +0 -29
  87. package/dist/string-coerce-fsri9iCu.mjs +0 -34
  88. package/dist/types-BVVgDSdq.d.mts +0 -1
  89. package/dist/utf16-slice-CvGodqok.mjs +0 -29
@@ -1,35 +1,35 @@
1
- import { D as Model, E as Message, J as ThinkingLevel, K as ThinkingBudgets, U as StreamOptions, a as AssistantMessage, n as Api, z as SimpleStreamOptions } from "../types-DTAP49HF.mjs";
1
+ import { D as Model, E as Message, J as ThinkingLevel, K as ThinkingBudgets, U as StreamOptions, a as AssistantMessage, n as Api, z as SimpleStreamOptions } from "../types-h38Azne1.mjs";
2
+ import "../types-DtGu2d3C.mjs";
2
3
  import { t as sanitizeSurrogates } from "../sanitize-unicode-BZiVbGwK.mjs";
3
4
  import { n as normalizeStructuredPromptSection, r as sortPromptCacheToolsByName, t as normalizePromptCapabilityIds } from "../prompt-cache-stability-Cwcjv_fx.mjs";
4
-
5
5
  //#region packages/ai/src/providers/simple-options.d.ts
6
6
  type FirstEventStreamOptions = {
7
7
  firstEventTimeoutMs?: number;
8
8
  onFirstEventTimeout?: (reason: Error) => void;
9
9
  };
10
- declare function buildBaseOptions(model: Model, options?: SimpleStreamOptions, apiKey?: string): StreamOptions & FirstEventStreamOptions;
11
- declare function clampMaxTokensToModel(model: Model, requestedMaxTokens: number): number;
12
- declare function clampMaxTokensToModel(model: Model, requestedMaxTokens: number | undefined): number | undefined;
13
- declare function clampReasoning(effort: ThinkingLevel): Exclude<ThinkingLevel, "xhigh">;
14
- declare function clampReasoning(effort: ThinkingLevel | undefined): Exclude<ThinkingLevel, "xhigh"> | undefined;
15
- declare function adjustMaxTokensForThinking(baseMaxTokens: number | undefined, modelMaxTokens: number, reasoningLevel: ThinkingLevel, customBudgets?: ThinkingBudgets): {
10
+ export declare function buildBaseOptions(model: Model, options?: SimpleStreamOptions, apiKey?: string): StreamOptions & FirstEventStreamOptions;
11
+ export declare function clampMaxTokensToModel(model: Model, requestedMaxTokens: number): number;
12
+ export declare function clampMaxTokensToModel(model: Model, requestedMaxTokens: number | undefined): number | undefined;
13
+ export declare function clampReasoning(effort: ThinkingLevel): Exclude<ThinkingLevel, "xhigh">;
14
+ export declare function clampReasoning(effort: ThinkingLevel | undefined): Exclude<ThinkingLevel, "xhigh"> | undefined;
15
+ export declare function adjustMaxTokensForThinking(baseMaxTokens: number | undefined, modelMaxTokens: number, reasoningLevel: ThinkingLevel, customBudgets?: ThinkingBudgets): {
16
16
  maxTokens: number;
17
17
  thinkingBudget: number;
18
18
  };
19
19
  //#endregion
20
20
  //#region packages/ai/src/providers/tool-result-text.d.ts
21
21
  /** Media metadata alone is not an attachment; provider emitters need inline bytes. */
22
- declare function hasMediaPayload(block: unknown): block is Record<string, unknown> & {
22
+ export declare function hasMediaPayload(block: unknown): block is Record<string, unknown> & {
23
23
  data: string;
24
24
  };
25
25
  /** Image metadata alone is not an attachment; provider emitters need inline bytes. */
26
- declare function isImageWithMediaPayload<T>(block: T): block is T & {
26
+ export declare function isImageWithMediaPayload<T>(block: T): block is T & {
27
27
  type: "image";
28
28
  data: string;
29
29
  };
30
- declare function describeToolResultMediaPlaceholder(blocks: readonly unknown[]): string | undefined;
31
- declare function extractToolResultBlockText(block: unknown): string | undefined;
32
- declare function extractToolResultText(blocks: readonly unknown[], options?: {
30
+ export declare function describeToolResultMediaPlaceholder(blocks: readonly unknown[]): string | undefined;
31
+ export declare function extractToolResultBlockText(block: unknown): string | undefined;
32
+ export declare function extractToolResultText(blocks: readonly unknown[], options?: {
33
33
  includeStructured?: boolean;
34
34
  }): string;
35
35
  type ToolResultMediaSupport = {
@@ -37,8 +37,8 @@ type ToolResultMediaSupport = {
37
37
  audio: boolean;
38
38
  };
39
39
  /** Describe media that cannot be represented on the target provider wire. */
40
- declare function describeUnsupportedToolResultMedia(blocks: readonly unknown[], support: ToolResultMediaSupport): string | undefined;
41
- declare function formatToolResultText(params: {
40
+ export declare function describeUnsupportedToolResultMedia(blocks: readonly unknown[], support: ToolResultMediaSupport): string | undefined;
41
+ export declare function formatToolResultText(params: {
42
42
  text: string;
43
43
  mediaPlaceholder?: string;
44
44
  omittedMediaPlaceholder?: string;
@@ -46,29 +46,29 @@ declare function formatToolResultText(params: {
46
46
  }): string;
47
47
  //#endregion
48
48
  //#region packages/ai/src/transcript-transform.d.ts
49
- declare function transformMessages<TApi extends Api>(messages: Message[], model: Model<TApi>, normalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string): Message[];
49
+ export declare function transformMessages<TApi extends Api>(messages: Message[], model: Model<TApi>, normalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string): Message[];
50
50
  //#endregion
51
51
  //#region packages/ai/src/utils/system-prompt-cache-boundary.d.ts
52
- declare const SYSTEM_PROMPT_CACHE_BOUNDARY = "\n<!-- OPENCLAW_CACHE_BOUNDARY -->\n";
53
- declare function stripSystemPromptCacheBoundary(text: string): string;
54
- declare function ensureSystemPromptCacheBoundary(systemPrompt: string): string;
55
- declare function splitSystemPromptCacheBoundary(text: string): {
52
+ export declare const SYSTEM_PROMPT_CACHE_BOUNDARY = "\n<!-- OPENCLAW_CACHE_BOUNDARY -->\n";
53
+ export declare function stripSystemPromptCacheBoundary(text: string): string;
54
+ export declare function ensureSystemPromptCacheBoundary(systemPrompt: string): string;
55
+ export declare function splitSystemPromptCacheBoundary(text: string): {
56
56
  stablePrefix: string;
57
57
  dynamicSuffix: string;
58
58
  } | undefined;
59
- declare function prependSystemPromptAdditionAfterCacheBoundary(params: {
59
+ export declare function prependSystemPromptAdditionAfterCacheBoundary(params: {
60
60
  systemPrompt: string;
61
61
  systemPromptAddition?: string;
62
62
  }): string;
63
63
  //#endregion
64
64
  //#region packages/ai/src/utils/tls-certificate-errors.d.ts
65
- type TlsCertificateErrorKind = "certificate_invalid" | "hostname_mismatch";
66
- type TlsCertificateErrorDetails = {
65
+ export type TlsCertificateErrorKind = "certificate_invalid" | "hostname_mismatch";
66
+ export type TlsCertificateErrorDetails = {
67
67
  kind: TlsCertificateErrorKind;
68
68
  code?: string;
69
69
  message: string;
70
70
  };
71
71
  /** Classify deterministic Node/OpenSSL certificate validation failures. */
72
- declare function inspectTlsCertificateError(error: unknown): TlsCertificateErrorDetails | null;
72
+ export declare function inspectTlsCertificateError(error: unknown): TlsCertificateErrorDetails | null;
73
73
  //#endregion
74
- export { SYSTEM_PROMPT_CACHE_BOUNDARY, TlsCertificateErrorDetails, TlsCertificateErrorKind, adjustMaxTokensForThinking, buildBaseOptions, clampMaxTokensToModel, clampReasoning, describeToolResultMediaPlaceholder, describeUnsupportedToolResultMedia, ensureSystemPromptCacheBoundary, extractToolResultBlockText, extractToolResultText, formatToolResultText, hasMediaPayload, inspectTlsCertificateError, isImageWithMediaPayload, normalizePromptCapabilityIds, normalizeStructuredPromptSection, prependSystemPromptAdditionAfterCacheBoundary, sanitizeSurrogates, sortPromptCacheToolsByName, splitSystemPromptCacheBoundary, stripSystemPromptCacheBoundary, transformMessages };
74
+ export { normalizePromptCapabilityIds, normalizeStructuredPromptSection, sanitizeSurrogates, sortPromptCacheToolsByName };
@@ -1,5 +1,5 @@
1
- import { t as sanitizeSurrogates } from "../sanitize-unicode-BP7HLLZn.mjs";
2
- import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as isImageWithMediaPayload, i as transformMessages, l as formatToolResultText, o as describeUnsupportedToolResultMedia, s as extractToolResultBlockText, u as hasMediaPayload } from "../host-DF_yxOsA.mjs";
3
- import { A as splitSystemPromptCacheBoundary, D as SYSTEM_PROMPT_CACHE_BOUNDARY, M as normalizePromptCapabilityIds, N as normalizeStructuredPromptSection, O as ensureSystemPromptCacheBoundary, P as sortPromptCacheToolsByName, i as clampReasoning, j as stripSystemPromptCacheBoundary, k as prependSystemPromptAdditionAfterCacheBoundary, n as buildBaseOptions, r as clampMaxTokensToModel, t as adjustMaxTokensForThinking } from "../simple-options-oqsXB6U3.mjs";
1
+ import { t as sanitizeSurrogates } from "../sanitize-unicode-DCkltN94.mjs";
2
+ import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as isImageWithMediaPayload, i as transformMessages, l as formatToolResultText, o as describeUnsupportedToolResultMedia, s as extractToolResultBlockText, u as hasMediaPayload } from "../host-D51fmkH6.mjs";
3
+ import { c as ensureSystemPromptCacheBoundary, d as stripSystemPromptCacheBoundary, f as normalizePromptCapabilityIds, i as clampReasoning, l as prependSystemPromptAdditionAfterCacheBoundary, m as sortPromptCacheToolsByName, n as buildBaseOptions, p as normalizeStructuredPromptSection, r as clampMaxTokensToModel, s as SYSTEM_PROMPT_CACHE_BOUNDARY, t as adjustMaxTokensForThinking, u as splitSystemPromptCacheBoundary } from "../simple-options-DKx86yX9.mjs";
4
4
  import { t as inspectTlsCertificateError } from "../tls-certificate-errors-DXSpluKI.mjs";
5
5
  export { SYSTEM_PROMPT_CACHE_BOUNDARY, adjustMaxTokensForThinking, buildBaseOptions, clampMaxTokensToModel, clampReasoning, describeToolResultMediaPlaceholder, describeUnsupportedToolResultMedia, ensureSystemPromptCacheBoundary, extractToolResultBlockText, extractToolResultText, formatToolResultText, hasMediaPayload, inspectTlsCertificateError, isImageWithMediaPayload, normalizePromptCapabilityIds, normalizeStructuredPromptSection, prependSystemPromptAdditionAfterCacheBoundary, sanitizeSurrogates, sortPromptCacheToolsByName, splitSystemPromptCacheBoundary, stripSystemPromptCacheBoundary, transformMessages };
@@ -1,4 +1,4 @@
1
- import { t as asNonArrayRecord } from "./record-coerce-DdXsgUd_.mjs";
1
+ import { n as asNonArrayRecord } from "./utf16-slice-qz3nsy87.mjs";
2
2
  import { parse } from "partial-json";
3
3
  //#region packages/ai/src/utils/json-parse.ts
4
4
  const VALID_JSON_ESCAPES = /* @__PURE__ */ new Set([
@@ -126,5 +126,21 @@ function parseStreamingJson(partialJson) {
126
126
  }
127
127
  }
128
128
  }
129
+ const TOOL_ARGUMENT_PREVIEW_FIRST_CHECKPOINT_CHARS = 512;
130
+ /**
131
+ * Streamed tool-call arguments are preview-only; the terminal parse re-reads
132
+ * the full buffer authoritatively at content_block_stop. Reparsing every delta
133
+ * scans an ever-growing buffer and makes assembly quadratic in the argument
134
+ * size, so refresh previews on a geometric length schedule instead — bounded
135
+ * staleness, linear total parse work.
136
+ */
137
+ function createToolArgumentPreviewSchedule() {
138
+ let nextCheckpointChars = TOOL_ARGUMENT_PREVIEW_FIRST_CHECKPOINT_CHARS;
139
+ return (accumulatedChars) => {
140
+ if (accumulatedChars < nextCheckpointChars) return false;
141
+ nextCheckpointChars = accumulatedChars * 2;
142
+ return true;
143
+ };
144
+ }
129
145
  //#endregion
130
- export { parseStreamingJson as n, repairJson as r, parseJsonWithRepair as t };
146
+ export { repairJson as i, parseJsonWithRepair as n, parseStreamingJson as r, createToolArgumentPreviewSchedule as t };
@@ -1,15 +1,18 @@
1
- import { n as getEnvApiKey } from "./env-api-keys-DrgeBuva.mjs";
2
1
  import { t as AssistantMessageEventStream } from "./event-stream-uSMZJ3FA.mjs";
3
- import { i as clampThinkingLevel, r as calculateCost, t as sanitizeSurrogates } from "./sanitize-unicode-BP7HLLZn.mjs";
4
- import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as isImageWithMediaPayload, l as formatToolResultText, n as getAiTransportHost } from "./host-DF_yxOsA.mjs";
5
- import { n as projectProviderError } from "./provider-error-C8mBRJDl.mjs";
6
- import { P as sortPromptCacheToolsByName, d as finalizeTerminalToolCallArguments, g as notifyProviderHttpResponse, j as stripSystemPromptCacheBoundary, n as buildBaseOptions, r as clampMaxTokensToModel, x as transportAbortError } from "./simple-options-oqsXB6U3.mjs";
7
- import { n as parseStreamingJson } from "./json-parse-CDnesDM_.mjs";
2
+ import { i as clampThinkingLevel, r as calculateCost, t as sanitizeSurrogates } from "./sanitize-unicode-DCkltN94.mjs";
3
+ import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as isImageWithMediaPayload, l as formatToolResultText, n as getAiTransportHost } from "./host-D51fmkH6.mjs";
4
+ import { n as projectProviderError } from "./provider-error-jZP5NMTZ.mjs";
5
+ import { d as stripSystemPromptCacheBoundary, m as sortPromptCacheToolsByName, n as buildBaseOptions, r as clampMaxTokensToModel } from "./simple-options-DKx86yX9.mjs";
6
+ import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
7
+ import { _ as transportAbortError, f as notifyProviderHttpResponse, s as finalizeTerminalToolCallArguments } from "./transport-stream-shared-CT5ycdzn.mjs";
8
+ import { r as parseStreamingJson, t as createToolArgumentPreviewSchedule } from "./json-parse-BuAJEbdW.mjs";
8
9
  import { t as shortHash } from "./hash-CHgqbJmD.mjs";
9
- import { t as transformProviderMessages } from "./provider-transcript-transform--gtf0ZbR.mjs";
10
- import { t as createSseByteGuard } from "./streaming-byte-guard-BrbkbwUu.mjs";
10
+ import { t as transformProviderMessages } from "./provider-transcript-transform-C01bQ5a3.mjs";
11
+ import { t as mapOpenAIStopReason } from "./openai-stop-reason-Drnn_6Qj.mjs";
12
+ import { t as createSseByteGuard } from "./streaming-byte-guard-CC-HMn_u.mjs";
11
13
  import { randomUUID } from "node:crypto";
12
- import { HTTPClient, Mistral } from "@mistralai/mistralai";
14
+ import { HTTPClient } from "@mistralai/mistralai/lib/http";
15
+ import { Chat } from "@mistralai/mistralai/sdk/chat";
13
16
  //#region packages/ai/src/providers/mistral.ts
14
17
  const MISTRAL_TOOL_CALL_ID_LENGTH = 9;
15
18
  const MISTRAL_STREAM_BODY_MAX_BYTES = 16 * 1024 * 1024;
@@ -77,7 +80,7 @@ const streamMistral = (model, context, options) => {
77
80
  reportedResponse = response;
78
81
  }
79
82
  });
80
- const mistral = new Mistral({
83
+ const chat = new Chat({
81
84
  apiKey,
82
85
  serverURL: model.baseUrl,
83
86
  httpClient
@@ -91,7 +94,7 @@ const streamMistral = (model, context, options) => {
91
94
  ...options?.headers
92
95
  };
93
96
  if (resolveMistralPromptCacheKey(options) && options?.sessionId) headers["x-affinity"] ||= options.sessionId;
94
- const mistralStream = await mistral.chat.stream(payload, {
97
+ const mistralStream = await chat.stream(payload, {
95
98
  headers,
96
99
  signal: options?.signal
97
100
  });
@@ -107,7 +110,7 @@ const streamMistral = (model, context, options) => {
107
110
  });
108
111
  await consumeChatStream(model, output, stream, mistralStream);
109
112
  if (options?.signal?.aborted) throw transportAbortError(options.signal);
110
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error("An unknown error occurred");
113
+ if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
111
114
  stream.push({
112
115
  type: "done",
113
116
  reason: output.stopReason,
@@ -241,6 +244,7 @@ async function consumeChatStream(model, output, stream, mistralStream) {
241
244
  const blocks = output.content;
242
245
  const blockIndex = () => blocks.length - 1;
243
246
  const toolBlockIdentities = /* @__PURE__ */ new Map();
247
+ const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
244
248
  const normalizeMissingToolCallId = createMistralToolCallIdNormalizer();
245
249
  const missingToolCallIdScope = randomUUID();
246
250
  const createMissingToolCallId = (contentIndex) => normalizeMissingToolCallId(`${missingToolCallIdScope}:toolcall:${contentIndex}`);
@@ -320,6 +324,7 @@ async function consumeChatStream(model, output, stream, mistralStream) {
320
324
  for await (const event of mistralStream) {
321
325
  const chunk = event.data;
322
326
  output.responseId ||= chunk.id;
327
+ if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
323
328
  if (chunk.usage) {
324
329
  const promptTokens = chunk.usage.promptTokens || 0;
325
330
  const cachedPromptTokens = readMistralCachedPromptTokens(chunk.usage, promptTokens);
@@ -334,7 +339,9 @@ async function consumeChatStream(model, output, stream, mistralStream) {
334
339
  if (!choice) continue;
335
340
  if (choice.finishReason) {
336
341
  terminalFinishReason = choice.finishReason;
337
- output.stopReason = mapChatStopReason(choice.finishReason);
342
+ const { stopReason, errorMessage } = mapOpenAIStopReason(choice.finishReason === "model_length" ? "length" : choice.finishReason);
343
+ output.stopReason = stopReason;
344
+ if (errorMessage) output.errorMessage = errorMessage;
338
345
  }
339
346
  const delta = choice.delta;
340
347
  if (delta.content !== null && delta.content !== void 0) {
@@ -445,6 +452,7 @@ async function consumeChatStream(model, output, stream, mistralStream) {
445
452
  partialArgs: ""
446
453
  };
447
454
  output.content.push(block);
455
+ toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
448
456
  toolBlockIdentities.set(contentIndex, {
449
457
  explicitIds: new Set(providedCallId ? [providedCallId] : []),
450
458
  functionNames: new Set(functionName ? [functionName] : []),
@@ -472,7 +480,7 @@ async function consumeChatStream(model, output, stream, mistralStream) {
472
480
  if (toolCallIndex !== void 0) identity.indexes.add(toolCallIndex);
473
481
  const argsDelta = typeof toolCall.function.arguments === "string" ? toolCall.function.arguments : JSON.stringify(toolCall.function.arguments || {});
474
482
  block.partialArgs = (block.partialArgs || "") + argsDelta;
475
- block.arguments = parseStreamingJson(block.partialArgs);
483
+ if (toolArgumentPreviewSchedules.get(block)?.(block.partialArgs.length)) block.arguments = parseStreamingJson(block.partialArgs);
476
484
  stream.push({
477
485
  type: "toolcall_delta",
478
486
  contentIndex,
@@ -661,16 +669,5 @@ function mapToolChoice(choice, convertedToolNames) {
661
669
  function: { name: toolName }
662
670
  };
663
671
  }
664
- function mapChatStopReason(reason) {
665
- if (reason === null) return "stop";
666
- switch (reason) {
667
- case "stop": return "stop";
668
- case "length":
669
- case "model_length": return "length";
670
- case "tool_calls": return "toolUse";
671
- case "error": return "error";
672
- default: return "stop";
673
- }
674
- }
675
672
  //#endregion
676
673
  export { createBoundedMistralFetcher, streamMistral, streamSimpleMistral };
@@ -1,23 +1,23 @@
1
- import { n as getEnvApiKey } from "./env-api-keys-DrgeBuva.mjs";
2
1
  import { i as formatThrownValue, n as createAssistantMessageDiagnostic, t as appendAssistantMessageDiagnostic } from "./diagnostics-COpOtRwq.mjs";
3
2
  import { t as AssistantMessageEventStream } from "./event-stream-uSMZJ3FA.mjs";
4
- import { n as getAiTransportHost, r as resolveAiTransportHeaderSentinels } from "./host-DF_yxOsA.mjs";
5
- import { n as projectProviderError } from "./provider-error-C8mBRJDl.mjs";
6
- import { n as toErrorObject, t as createResponsesPromptEgressObserver } from "./openai-responses-prompt-observer-internal-BG-1AsBI.mjs";
7
- import { c as resolveTimerTimeoutMs, i as clampTimerTimeoutMs } from "./number-coercion-H9qHik3g.mjs";
8
- import { S as supportsOpenAITemperature, m as responsesPromptObserver } from "./openai-responses-contracts-DvILoqBk.mjs";
3
+ import { n as getAiTransportHost, r as resolveAiTransportHeaderSentinels } from "./host-D51fmkH6.mjs";
4
+ import { n as projectProviderError } from "./provider-error-jZP5NMTZ.mjs";
5
+ import { n as toErrorObject, t as createResponsesPromptEgressObserver } from "./openai-responses-prompt-observer-internal-_nhGTn2b.mjs";
6
+ import { o as clampTimerTimeoutMs, u as resolveTimerTimeoutMs } from "./base64-CEFBpSkN.mjs";
9
7
  import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-mZTCdRPo.mjs";
10
- import { C as withProviderResponseHook, _ as notifyProviderStreamOpened, j as stripSystemPromptCacheBoundary, n as buildBaseOptions, x as transportAbortError } from "./simple-options-oqsXB6U3.mjs";
11
- import { t as headersToRecord } from "./headers-B_e4-1J0.mjs";
8
+ import { d as stripSystemPromptCacheBoundary, n as buildBaseOptions } from "./simple-options-DKx86yX9.mjs";
12
9
  import { parseRetryAfterHttpDateMs } from "./internal/retry-after.mjs";
13
- import { t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-utils-Bv0FHkd0.mjs";
14
- import { F as commitResponsesEncryptedContentAttempt, G as suppressOpenAIResponsesCompaction, L as isInvalidEncryptedContentError, U as buildOpenAIResponsesReasoningReplayMetadata, a as resolveResponsesReasoningEffort, c as processResponsesStream, i as createResponsesAssistantOutput, n as applyResponsesServiceTierPricing, p as ResponsesStreamFailure, r as convertResponsesMessages, s as convertResponsesToolPayload, z as resolveNextResponsesEncryptedContentAttempt } from "./openai-responses-shared-Cvt5MgEm.mjs";
15
- import { o as createOpenAIProviderAcceptanceHook, s as createOpenAIResponseHook } from "./openai-tool-projection-CHGLt03m.mjs";
16
- import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-MK28puvq.mjs";
10
+ import { t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-utils-BHx9z8Cl.mjs";
11
+ import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
12
+ import { C as headersToRecord, _ as transportAbortError, p as notifyProviderStreamOpened, y as withProviderResponseHook } from "./transport-stream-shared-CT5ycdzn.mjs";
13
+ import { F as commitResponsesEncryptedContentAttempt, L as isInvalidEncryptedContentError, W as buildOpenAIResponsesReasoningReplayMetadata, a as resolveResponsesReasoningEffort, c as processResponsesStream, i as createResponsesAssistantOutput, n as applyResponsesServiceTierPricing, p as ResponsesStreamFailure, q as suppressOpenAIResponsesCompaction, r as convertResponsesMessages, s as convertResponsesToolPayload, z as resolveNextResponsesEncryptedContentAttempt } from "./openai-responses-shared-zPmKnhF5.mjs";
14
+ import { C as createOpenAIProviderAcceptanceHook, w as createOpenAIResponseHook } from "./openai-tool-schema-Dgl4H2MU.mjs";
15
+ import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-DcNjoFQE.mjs";
16
+ import { A as supportsOpenAITemperature, S as responsesPromptObserver } from "./openai-responses-compaction-window-DwydGZI8.mjs";
17
+ import { t as createSseByteGuard } from "./streaming-byte-guard-CC-HMn_u.mjs";
17
18
  import { n as registerSessionResourceCleanup } from "./session-resources-CkR4WWy1.mjs";
18
19
  import "./diagnostics.mjs";
19
20
  import { n as resolveOpenAICodexAccountId } from "./openai-chatgpt-jwt-KWcgd0d_.mjs";
20
- import { t as createSseByteGuard } from "./streaming-byte-guard-BrbkbwUu.mjs";
21
21
  import { t as inspectTlsCertificateError } from "./tls-certificate-errors-DXSpluKI.mjs";
22
22
  //#region packages/ai/src/internal/retry-sleep.ts
23
23
  function sleepWithAbort(ms, signal) {
@@ -154,6 +154,12 @@ function isRequestTimeoutError(error, callerSignal, requestSignal, timeoutMs) {
154
154
  if (!(error instanceof Error)) return false;
155
155
  return error.name === "AbortError" || error.name === "TimeoutError" || error.message === "Request was aborted";
156
156
  }
157
+ /** Local-only failure category for transport diagnostics; never provider text. */
158
+ function classifyStreamFailure(error, signal, requestTimedOut) {
159
+ if (requestTimedOut) return "timeout";
160
+ if (signal?.aborted) return "caller-abort";
161
+ return error instanceof ResponsesStreamFailure || error instanceof CodexApiError ? "provider-failure" : "transport";
162
+ }
157
163
  function formatRequestTimeoutError(timeoutMs, cause) {
158
164
  return new Error(`Request timed out after ${timeoutMs}ms`, { cause: cause instanceof Error ? cause : void 0 });
159
165
  }
@@ -171,6 +177,7 @@ function compressRequestBodyZstd(bodyJson) {
171
177
  const streamOpenAICodexResponses = (model, context, options) => {
172
178
  const stream = new AssistantMessageEventStream();
173
179
  (async () => {
180
+ const startedAt = Date.now();
174
181
  let requestTimeoutMs;
175
182
  let requestTimeoutSignal;
176
183
  let activeSignal;
@@ -364,9 +371,19 @@ const streamOpenAICodexResponses = (model, context, options) => {
364
371
  });
365
372
  stream.end();
366
373
  } catch (error) {
367
- const normalizedError = isRequestTimeoutError(error, options?.signal, requestTimeoutSignal, requestTimeoutMs) && requestTimeoutMs !== void 0 ? formatRequestTimeoutError(requestTimeoutMs, error) : error;
374
+ const requestTimedOut = isRequestTimeoutError(error, options?.signal, requestTimeoutSignal, requestTimeoutMs) && requestTimeoutMs !== void 0;
375
+ const normalizedError = requestTimedOut && requestTimeoutMs !== void 0 ? formatRequestTimeoutError(requestTimeoutMs, error) : error;
368
376
  for (const block of output.content) delete block.partialJson;
369
377
  const terminal = projectProviderError(normalizedError, options?.signal);
378
+ getAiTransportHost().logWarn("openai-transport", "ChatGPT Responses stream terminated", {
379
+ provider: model.provider,
380
+ api: model.api,
381
+ model: model.id,
382
+ transport: options?.transport || "auto",
383
+ elapsedMs: Math.max(0, Date.now() - startedAt),
384
+ stopReason: terminal.stopReason,
385
+ failureKind: classifyStreamFailure(error, options?.signal, requestTimedOut)
386
+ });
370
387
  Object.assign(output, terminal);
371
388
  stream.push({
372
389
  type: "error",