@openclaw/ai 0.0.0 → 2026.7.1-beta.4
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.
- package/LICENSE +21 -0
- package/README.md +27 -3
- package/dist/anthropic-B5gZQM5X.mjs +1383 -0
- package/dist/api-registry-COYU2fF4.d.mts +33 -0
- package/dist/azure-openai-responses-CkxVwqPL.mjs +141 -0
- package/dist/azure-openai-responses-client-compat-a_O_GVQV.mjs +41 -0
- package/dist/diagnostics-BaTA9eVl.d.mts +25 -0
- package/dist/diagnostics-COpOtRwq.mjs +36 -0
- package/dist/diagnostics.d.mts +2 -0
- package/dist/diagnostics.mjs +2 -0
- package/dist/env-api-keys-CtMlqaQ4.mjs +171 -0
- package/dist/event-stream-C-T9juXb.d.mts +26 -0
- package/dist/event-stream-ReMmOTzX.mjs +65 -0
- package/dist/event-stream.d.mts +2 -0
- package/dist/event-stream.mjs +2 -0
- package/dist/github-copilot-headers-BsH5cqGj.mjs +48 -0
- package/dist/google-D6sIQ1bL.mjs +55 -0
- package/dist/google-shared-ZPSl2qTi.mjs +548 -0
- package/dist/google-vertex-rDGwkoZK.mjs +111 -0
- package/dist/hash-CHgqbJmD.mjs +16 -0
- package/dist/headers-B_e4-1J0.mjs +9 -0
- package/dist/host-4t713IeR.mjs +37 -0
- package/dist/index-BoTnz8cv.d.mts +74 -0
- package/dist/index.d.mts +69 -0
- package/dist/index.mjs +7 -0
- package/dist/internal/anthropic.d.mts +234 -0
- package/dist/internal/anthropic.mjs +4 -0
- package/dist/internal/openai.d.mts +242 -0
- package/dist/internal/openai.mjs +7 -0
- package/dist/internal/runtime.d.mts +245 -0
- package/dist/internal/runtime.mjs +176 -0
- package/dist/internal/shared.d.mts +48 -0
- package/dist/internal/shared.mjs +3 -0
- package/dist/json-parse-DzNSIQBq.mjs +134 -0
- package/dist/llm-request-activity-CehVkZP-.mjs +35 -0
- package/dist/mistral-CePVNdws.mjs +563 -0
- package/dist/model-utils-DgmOla96.mjs +69 -0
- package/dist/openai-chatgpt-jwt-DhAAzLkj.mjs +39 -0
- package/dist/openai-chatgpt-responses-CYqFzw4W.mjs +1068 -0
- package/dist/openai-completions-IOlOeB-u.mjs +841 -0
- package/dist/openai-responses-CKTUdtu9.mjs +136 -0
- package/dist/openai-responses-shared-CO5L7re5.mjs +1936 -0
- package/dist/openai-tool-projection-BknoV11q.mjs +195 -0
- package/dist/providers.d.mts +11 -0
- package/dist/providers.mjs +109 -0
- package/dist/reasoning-tag-text-partitioner-axhAdUwg.mjs +394 -0
- package/dist/sanitize-unicode-BZiVbGwK.d.mts +24 -0
- package/dist/sanitize-unicode-DT5o51ur.mjs +26 -0
- package/dist/src-CZ503MYJ.mjs +99 -0
- package/dist/stream-CREqxHgU.mjs +74 -0
- package/dist/stream-first-event-timeout-RjWszj8c.mjs +106 -0
- package/dist/streaming-byte-guard-BrbkbwUu.mjs +46 -0
- package/dist/tool-schema-json-projection-BXtBc_mD.mjs +74 -0
- package/dist/transform-messages-BhGF_fF4.mjs +507 -0
- package/dist/types-BVVgDSdq.d.mts +1 -0
- package/dist/types-DZAZItYw.d.mts +585 -0
- package/dist/types.d.mts +6 -0
- package/dist/types.mjs +5 -0
- package/dist/validation-Ctw0PWEu.d.mts +9 -0
- package/dist/validation-FrchoOlv.mjs +199 -0
- package/dist/validation.d.mts +2 -0
- package/dist/validation.mjs +2 -0
- package/npm-shrinkwrap.json +645 -0
- package/package.json +75 -3
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
import { a as resolveClaudeFable5ModelIdentity, i as requiresClaudeMandatoryAdaptiveThinking, l as resolveClaudeSonnet5ModelIdentity, r as requiresClaudeDefaultSampling, s as resolveClaudeMythos5ModelIdentity } from "./src-CZ503MYJ.mjs";
|
|
2
|
+
import { n as getAiTransportHost } from "./host-4t713IeR.mjs";
|
|
3
|
+
import { t as sanitizeSurrogates } from "./sanitize-unicode-DT5o51ur.mjs";
|
|
4
|
+
//#region packages/normalization-core/src/string-coerce.ts
|
|
5
|
+
/** Trims string input and returns null for non-strings or empty strings. */
|
|
6
|
+
function normalizeNullableString(value) {
|
|
7
|
+
if (typeof value !== "string") return null;
|
|
8
|
+
const trimmed = value.trim();
|
|
9
|
+
return trimmed ? trimmed : null;
|
|
10
|
+
}
|
|
11
|
+
/** Trims string input and returns undefined for non-strings or empty strings. */
|
|
12
|
+
function normalizeOptionalString(value) {
|
|
13
|
+
return normalizeNullableString(value) ?? void 0;
|
|
14
|
+
}
|
|
15
|
+
/** Lowercases a normalized optional string. */
|
|
16
|
+
function normalizeOptionalLowercaseString(value) {
|
|
17
|
+
return normalizeOptionalString(value)?.toLowerCase();
|
|
18
|
+
}
|
|
19
|
+
/** Lowercases a normalized string or returns an empty string when absent. */
|
|
20
|
+
function normalizeLowercaseStringOrEmpty(value) {
|
|
21
|
+
return normalizeOptionalLowercaseString(value) ?? "";
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region packages/ai/src/utils/prompt-cache-stability.ts
|
|
25
|
+
/**
|
|
26
|
+
* Prompt-cache normalization helpers. They keep generated prompt sections
|
|
27
|
+
* deterministic across platform newlines, trailing whitespace, and input
|
|
28
|
+
* ordering.
|
|
29
|
+
*/
|
|
30
|
+
/** Normalize structured prompt text before hashing or snapshot comparison. */
|
|
31
|
+
function normalizeStructuredPromptSection(text) {
|
|
32
|
+
return sanitizeSurrogates(text).replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "").trim();
|
|
33
|
+
}
|
|
34
|
+
/** Normalize, de-dupe, and sort capability ids for stable prompt payloads. */
|
|
35
|
+
function normalizePromptCapabilityIds(capabilities) {
|
|
36
|
+
const seen = /* @__PURE__ */ new Set();
|
|
37
|
+
const normalized = [];
|
|
38
|
+
for (const capability of capabilities) {
|
|
39
|
+
const value = normalizeLowercaseStringOrEmpty(normalizeStructuredPromptSection(capability));
|
|
40
|
+
if (!value || seen.has(value)) continue;
|
|
41
|
+
seen.add(value);
|
|
42
|
+
normalized.push(value);
|
|
43
|
+
}
|
|
44
|
+
return normalized.toSorted((left, right) => left.localeCompare(right));
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region packages/ai/src/utils/system-prompt-cache-boundary.ts
|
|
48
|
+
/**
|
|
49
|
+
* System prompt cache-boundary helpers.
|
|
50
|
+
*
|
|
51
|
+
* Keeps stable prompt prefixes separate from dynamic runtime additions for provider prompt caching.
|
|
52
|
+
*/
|
|
53
|
+
const SYSTEM_PROMPT_CACHE_BOUNDARY = "\n<!-- OPENCLAW_CACHE_BOUNDARY -->\n";
|
|
54
|
+
function stripSystemPromptCacheBoundary(text) {
|
|
55
|
+
return text.replaceAll(SYSTEM_PROMPT_CACHE_BOUNDARY, "\n");
|
|
56
|
+
}
|
|
57
|
+
function ensureSystemPromptCacheBoundary(systemPrompt) {
|
|
58
|
+
if (systemPrompt.trim().length === 0) return systemPrompt;
|
|
59
|
+
return systemPrompt.includes("\n<!-- OPENCLAW_CACHE_BOUNDARY -->\n") ? systemPrompt : `${systemPrompt}${SYSTEM_PROMPT_CACHE_BOUNDARY}`;
|
|
60
|
+
}
|
|
61
|
+
function splitSystemPromptCacheBoundary(text) {
|
|
62
|
+
const boundaryIndex = text.indexOf(SYSTEM_PROMPT_CACHE_BOUNDARY);
|
|
63
|
+
if (boundaryIndex === -1) return;
|
|
64
|
+
return {
|
|
65
|
+
stablePrefix: text.slice(0, boundaryIndex).trimEnd(),
|
|
66
|
+
dynamicSuffix: text.slice(boundaryIndex + 34).trimStart()
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function prependSystemPromptAdditionAfterCacheBoundary(params) {
|
|
70
|
+
const systemPromptAddition = typeof params.systemPromptAddition === "string" ? normalizeStructuredPromptSection(params.systemPromptAddition) : "";
|
|
71
|
+
if (!systemPromptAddition) return params.systemPrompt;
|
|
72
|
+
if (params.systemPrompt.trim().length === 0) return systemPromptAddition;
|
|
73
|
+
const split = splitSystemPromptCacheBoundary(params.systemPrompt);
|
|
74
|
+
if (!split) return `${systemPromptAddition}\n\n${params.systemPrompt}`;
|
|
75
|
+
const dynamicSuffix = split.dynamicSuffix ? normalizeStructuredPromptSection(split.dynamicSuffix) : "";
|
|
76
|
+
if (!dynamicSuffix) return `${split.stablePrefix}${SYSTEM_PROMPT_CACHE_BOUNDARY}${systemPromptAddition}`;
|
|
77
|
+
return `${split.stablePrefix}${SYSTEM_PROMPT_CACHE_BOUNDARY}${systemPromptAddition}\n\n${dynamicSuffix}`;
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region packages/ai/src/providers/anthropic-model-contract.ts
|
|
81
|
+
function normalizeModelId(modelId) {
|
|
82
|
+
const normalized = normalizeLowercaseStringOrEmpty(modelId);
|
|
83
|
+
return (normalized.startsWith("anthropic/") ? normalized.slice(10) : normalized).replace(/[._\s]+/g, "-");
|
|
84
|
+
}
|
|
85
|
+
function normalizeApi(api) {
|
|
86
|
+
const normalized = normalizeLowercaseStringOrEmpty(api);
|
|
87
|
+
return normalized === "openclaw-anthropic-messages-transport" ? "anthropic-messages" : normalized;
|
|
88
|
+
}
|
|
89
|
+
function hasConcreteResponseModel(ref) {
|
|
90
|
+
const responseModelId = normalizeModelId(ref.responseModelId);
|
|
91
|
+
return responseModelId.length > 0 && responseModelId !== normalizeModelId(ref.modelId);
|
|
92
|
+
}
|
|
93
|
+
function usesClaudeFable5MessagesContract(model) {
|
|
94
|
+
return normalizeApi(model.api) === "anthropic-messages" && resolveClaudeFable5ModelIdentity(model) !== void 0;
|
|
95
|
+
}
|
|
96
|
+
/** Return whether streamed output must wait for the terminal refusal decision. */
|
|
97
|
+
function usesClaudeStreamingRefusalContract(model) {
|
|
98
|
+
if (normalizeApi(model.api) !== "anthropic-messages") return false;
|
|
99
|
+
return resolveClaudeFable5ModelIdentity(model) !== void 0 || resolveClaudeMythos5ModelIdentity(model) !== void 0 || resolveClaudeSonnet5ModelIdentity(model) !== void 0;
|
|
100
|
+
}
|
|
101
|
+
function requiresClaudeAdaptiveThinking(model) {
|
|
102
|
+
if (normalizeApi(model.api) !== "anthropic-messages") return false;
|
|
103
|
+
return requiresClaudeMandatoryAdaptiveThinking(model);
|
|
104
|
+
}
|
|
105
|
+
/** Return whether omitted thinking should default to adaptive/high. */
|
|
106
|
+
function defaultsClaudeAdaptiveThinking(model) {
|
|
107
|
+
return requiresClaudeAdaptiveThinking(model) || normalizeApi(model.api) === "anthropic-messages" && resolveClaudeSonnet5ModelIdentity(model) !== void 0;
|
|
108
|
+
}
|
|
109
|
+
/** Remove Sonnet 5 assistant prefills while preserving completed tool-use turns. */
|
|
110
|
+
function prepareClaudeSonnet5RequestContext(model, context) {
|
|
111
|
+
if (!resolveClaudeSonnet5ModelIdentity(model)) return context;
|
|
112
|
+
let end = context.messages.length;
|
|
113
|
+
while (end > 0) {
|
|
114
|
+
const message = context.messages[end - 1];
|
|
115
|
+
if (message?.role !== "assistant" || Array.isArray(message.content) && message.content.some((block) => block.type === "toolCall")) break;
|
|
116
|
+
end -= 1;
|
|
117
|
+
}
|
|
118
|
+
return end === context.messages.length ? context : {
|
|
119
|
+
...context,
|
|
120
|
+
messages: context.messages.slice(0, end)
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function applyClaudeRequestContract(params, model) {
|
|
124
|
+
if (normalizeApi(model.api) !== "anthropic-messages") return;
|
|
125
|
+
const sonnet5 = resolveClaudeSonnet5ModelIdentity(model) !== void 0;
|
|
126
|
+
if (!requiresClaudeDefaultSampling(model) && !sonnet5) return;
|
|
127
|
+
delete params.temperature;
|
|
128
|
+
delete params.top_p;
|
|
129
|
+
delete params.top_k;
|
|
130
|
+
if (sonnet5) delete params.service_tier;
|
|
131
|
+
}
|
|
132
|
+
function resolveReplayModelBoundIdentity(ref) {
|
|
133
|
+
if (normalizeApi(ref.api) !== "anthropic-messages") return;
|
|
134
|
+
const modelRef = hasConcreteResponseModel(ref) ? { id: ref.responseModelId } : {
|
|
135
|
+
id: ref.modelId,
|
|
136
|
+
params: ref.modelParams
|
|
137
|
+
};
|
|
138
|
+
const fableIdentity = resolveClaudeFable5ModelIdentity(modelRef);
|
|
139
|
+
if (fableIdentity) return `fable:${fableIdentity}`;
|
|
140
|
+
const mythosIdentity = resolveClaudeMythos5ModelIdentity(modelRef);
|
|
141
|
+
if (mythosIdentity) return `mythos:${mythosIdentity}`;
|
|
142
|
+
const sonnetIdentity = resolveClaudeSonnet5ModelIdentity(modelRef);
|
|
143
|
+
return sonnetIdentity ? `sonnet:${sonnetIdentity}` : void 0;
|
|
144
|
+
}
|
|
145
|
+
function resolveModelBoundThinkingReplayMode(params) {
|
|
146
|
+
const sourceApi = normalizeApi(params.source.api);
|
|
147
|
+
const targetApi = normalizeApi(params.target.api);
|
|
148
|
+
const sourceIdentity = resolveReplayModelBoundIdentity(params.source);
|
|
149
|
+
const targetIdentity = resolveReplayModelBoundIdentity(params.target);
|
|
150
|
+
const sameRoute = normalizeLowercaseStringOrEmpty(params.source.provider) === normalizeLowercaseStringOrEmpty(params.target.provider) && sourceApi === targetApi && normalizeModelId(params.source.modelId) === normalizeModelId(params.target.modelId);
|
|
151
|
+
if (!sourceIdentity && !targetIdentity) return "default";
|
|
152
|
+
if (!sourceIdentity && !hasConcreteResponseModel(params.source) && targetIdentity && sameRoute) return "preserve";
|
|
153
|
+
return sourceApi === targetApi && sourceIdentity === targetIdentity ? "preserve" : "drop";
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
//#region packages/normalization-core/src/record-coerce.ts
|
|
157
|
+
/** Type guard for non-array object records at browser-safe boundaries. */
|
|
158
|
+
function isRecord(value) {
|
|
159
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region packages/ai/src/providers/simple-options.ts
|
|
163
|
+
function buildBaseOptions(model, options, apiKey) {
|
|
164
|
+
const firstEventOptions = options;
|
|
165
|
+
return {
|
|
166
|
+
temperature: options?.temperature,
|
|
167
|
+
maxTokens: options?.maxTokens,
|
|
168
|
+
stop: options?.stop,
|
|
169
|
+
signal: options?.signal,
|
|
170
|
+
apiKey: apiKey || options?.apiKey,
|
|
171
|
+
transport: options?.transport,
|
|
172
|
+
cacheRetention: options?.cacheRetention,
|
|
173
|
+
sessionId: options?.sessionId,
|
|
174
|
+
promptCacheKey: options?.promptCacheKey,
|
|
175
|
+
headers: options?.headers,
|
|
176
|
+
onPayload: options?.onPayload,
|
|
177
|
+
onResponse: options?.onResponse,
|
|
178
|
+
timeoutMs: options?.timeoutMs,
|
|
179
|
+
firstEventTimeoutMs: firstEventOptions?.firstEventTimeoutMs,
|
|
180
|
+
onFirstEventTimeout: firstEventOptions?.onFirstEventTimeout,
|
|
181
|
+
maxRetries: options?.maxRetries,
|
|
182
|
+
maxRetryDelayMs: options?.maxRetryDelayMs,
|
|
183
|
+
metadata: options?.metadata
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
function clampReasoning(effort) {
|
|
187
|
+
return effort === "xhigh" ? "high" : effort;
|
|
188
|
+
}
|
|
189
|
+
function adjustMaxTokensForThinking(baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) {
|
|
190
|
+
const budgets = {
|
|
191
|
+
minimal: 1024,
|
|
192
|
+
low: 2048,
|
|
193
|
+
medium: 8192,
|
|
194
|
+
high: 16384,
|
|
195
|
+
max: 32768,
|
|
196
|
+
...customBudgets
|
|
197
|
+
};
|
|
198
|
+
const minOutputTokens = 1024;
|
|
199
|
+
let thinkingBudget = budgets[clampReasoning(reasoningLevel)];
|
|
200
|
+
const maxTokens = baseMaxTokens === void 0 ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);
|
|
201
|
+
if (maxTokens <= thinkingBudget) thinkingBudget = Math.max(0, maxTokens - minOutputTokens);
|
|
202
|
+
return {
|
|
203
|
+
maxTokens,
|
|
204
|
+
thinkingBudget
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
//#endregion
|
|
208
|
+
//#region packages/normalization-core/src/utf16-slice.ts
|
|
209
|
+
function isHighSurrogate(codeUnit) {
|
|
210
|
+
return codeUnit >= 55296 && codeUnit <= 56319;
|
|
211
|
+
}
|
|
212
|
+
function isLowSurrogate(codeUnit) {
|
|
213
|
+
return codeUnit >= 56320 && codeUnit <= 57343;
|
|
214
|
+
}
|
|
215
|
+
/** Slices a UTF-16 string without returning dangling surrogate halves at either edge. */
|
|
216
|
+
function sliceUtf16Safe(input, start, end) {
|
|
217
|
+
const len = input.length;
|
|
218
|
+
let from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
|
|
219
|
+
let to = end === void 0 ? len : end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
|
|
220
|
+
if (to <= from) return "";
|
|
221
|
+
if (from > 0 && from < len) {
|
|
222
|
+
if (isLowSurrogate(input.charCodeAt(from)) && isHighSurrogate(input.charCodeAt(from - 1))) from += 1;
|
|
223
|
+
}
|
|
224
|
+
if (to > 0 && to < len) {
|
|
225
|
+
if (isHighSurrogate(input.charCodeAt(to - 1)) && isLowSurrogate(input.charCodeAt(to))) to -= 1;
|
|
226
|
+
}
|
|
227
|
+
return input.slice(from, to);
|
|
228
|
+
}
|
|
229
|
+
/** Truncates a UTF-16 string without cutting a surrogate pair in half. */
|
|
230
|
+
function truncateUtf16Safe(input, maxLen) {
|
|
231
|
+
const limit = Math.max(0, Math.floor(maxLen));
|
|
232
|
+
if (input.length <= limit) return input;
|
|
233
|
+
return sliceUtf16Safe(input, 0, limit);
|
|
234
|
+
}
|
|
235
|
+
//#endregion
|
|
236
|
+
//#region packages/ai/src/providers/tool-result-text.ts
|
|
237
|
+
const PROVIDER_TOOL_RESULT_MAX_CHARS = 8e3;
|
|
238
|
+
const IMAGE_TOOL_RESULT_TYPES = /* @__PURE__ */ new Set([
|
|
239
|
+
"image",
|
|
240
|
+
"image_url",
|
|
241
|
+
"input_image"
|
|
242
|
+
]);
|
|
243
|
+
const AUDIO_TOOL_RESULT_TYPES = /* @__PURE__ */ new Set([
|
|
244
|
+
"audio",
|
|
245
|
+
"input_audio",
|
|
246
|
+
"output_audio"
|
|
247
|
+
]);
|
|
248
|
+
const MEDIA_ONLY_TOOL_RESULT_TYPES = /* @__PURE__ */ new Set([...IMAGE_TOOL_RESULT_TYPES, ...AUDIO_TOOL_RESULT_TYPES]);
|
|
249
|
+
const INLINE_DATA_URI_PATTERN = /(^|[^A-Za-z0-9_])data:([a-z][a-z0-9.+-]*\/[a-z0-9.+-]+(?:;[a-z0-9.+-]+=[^,;"'\s]+|;base64)*,[^\s"'<>)]+)/gi;
|
|
250
|
+
const MIME_KEY_CANDIDATES = [
|
|
251
|
+
"mimeType",
|
|
252
|
+
"mime_type",
|
|
253
|
+
"mediaType",
|
|
254
|
+
"media_type",
|
|
255
|
+
"contentType",
|
|
256
|
+
"content_type"
|
|
257
|
+
];
|
|
258
|
+
const TEXTUAL_MIME_PATTERN = /^(?:text\/|application\/(?:json|ld\+json|x-ndjson|xml|javascript|x-www-form-urlencoded)|[^/]+\/[^+]+\+(?:json|xml)$)/i;
|
|
259
|
+
const OPAQUE_OR_BINARY_FIELD_RE = /^(?:blob|buffer|bytes|encrypted_content|encrypted_stdout)$/i;
|
|
260
|
+
function readMimeType(value) {
|
|
261
|
+
if (!isRecord(value)) return;
|
|
262
|
+
for (const key of MIME_KEY_CANDIDATES) {
|
|
263
|
+
const mimeType = value[key];
|
|
264
|
+
if (typeof mimeType === "string" && mimeType.trim().length > 0) return mimeType;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
function isBinaryMimeType(mimeType) {
|
|
268
|
+
const normalized = mimeType.split(";", 1)[0]?.trim().toLowerCase();
|
|
269
|
+
return normalized ? !TEXTUAL_MIME_PATTERN.test(normalized) : false;
|
|
270
|
+
}
|
|
271
|
+
function describeOmittedValue(value, label) {
|
|
272
|
+
const length = typeof value === "string" ? value.length : JSON.stringify(value)?.length;
|
|
273
|
+
return length ? `[${label} omitted: ${length} chars]` : `[${label} omitted]`;
|
|
274
|
+
}
|
|
275
|
+
function redactInlineDataUris(value) {
|
|
276
|
+
return value.replace(INLINE_DATA_URI_PATTERN, (_match, prefix, uri) => `${prefix}[inline data URI: ${uri.length} chars]`);
|
|
277
|
+
}
|
|
278
|
+
function redactStructuredTextValue(value) {
|
|
279
|
+
const host = getAiTransportHost();
|
|
280
|
+
const redacted = host.redactToolPayloadText(value);
|
|
281
|
+
const trimmed = redacted.trim();
|
|
282
|
+
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return redacted;
|
|
283
|
+
try {
|
|
284
|
+
const redactedWrapper = host.redactSecrets({ structuredTextValue: JSON.parse(redacted) });
|
|
285
|
+
return JSON.stringify(redactedWrapper.structuredTextValue);
|
|
286
|
+
} catch {
|
|
287
|
+
return redacted;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function stringifyStructuredBlock(block) {
|
|
291
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
292
|
+
try {
|
|
293
|
+
const redactedBlock = getAiTransportHost().redactSecrets({ structuredToolResult: block }).structuredToolResult;
|
|
294
|
+
const serialized = JSON.stringify(redactedBlock, function structuredToolResultReplacer(key, value) {
|
|
295
|
+
if (OPAQUE_OR_BINARY_FIELD_RE.test(key)) return `[omitted ${key}]`;
|
|
296
|
+
if (key === "data") {
|
|
297
|
+
const mimeType = readMimeType(this);
|
|
298
|
+
if (mimeType && isBinaryMimeType(mimeType)) return describeOmittedValue(value, "binary data");
|
|
299
|
+
}
|
|
300
|
+
if (typeof value === "bigint") return value.toString();
|
|
301
|
+
if (typeof value === "string") return redactInlineDataUris(redactStructuredTextValue(value));
|
|
302
|
+
if (typeof value === "function" || typeof value === "symbol" || value === void 0) return;
|
|
303
|
+
if (!value || typeof value !== "object") return value;
|
|
304
|
+
if (seen.has(value)) return "[Circular]";
|
|
305
|
+
seen.add(value);
|
|
306
|
+
return value;
|
|
307
|
+
});
|
|
308
|
+
if (!serialized || serialized === "{}") return;
|
|
309
|
+
return serialized;
|
|
310
|
+
} catch {
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function truncateProviderToolText(text) {
|
|
315
|
+
if (text.length <= PROVIDER_TOOL_RESULT_MAX_CHARS) return text;
|
|
316
|
+
return `${truncateUtf16Safe(text, PROVIDER_TOOL_RESULT_MAX_CHARS)}\n…(truncated)…`;
|
|
317
|
+
}
|
|
318
|
+
function describeToolResultMediaPlaceholder(blocks) {
|
|
319
|
+
let hasImage = false;
|
|
320
|
+
let hasAudio = false;
|
|
321
|
+
for (const block of blocks) {
|
|
322
|
+
if (!block || typeof block !== "object") continue;
|
|
323
|
+
const record = block;
|
|
324
|
+
const type = typeof record.type === "string" ? record.type : void 0;
|
|
325
|
+
const mimeType = readMimeType(record);
|
|
326
|
+
if (type && IMAGE_TOOL_RESULT_TYPES.has(type) || mimeType?.toLowerCase().startsWith("image/")) hasImage = true;
|
|
327
|
+
if (type && AUDIO_TOOL_RESULT_TYPES.has(type) || mimeType?.toLowerCase().startsWith("audio/")) hasAudio = true;
|
|
328
|
+
}
|
|
329
|
+
if (hasImage && hasAudio) return "(see attached media)";
|
|
330
|
+
if (hasAudio) return "(see attached audio)";
|
|
331
|
+
if (hasImage) return "(see attached image)";
|
|
332
|
+
}
|
|
333
|
+
function extractToolResultBlockText(block) {
|
|
334
|
+
if (!block || typeof block !== "object") return;
|
|
335
|
+
const record = block;
|
|
336
|
+
if (typeof record.type === "string" && MEDIA_ONLY_TOOL_RESULT_TYPES.has(record.type)) return;
|
|
337
|
+
if (record.type === "text") {
|
|
338
|
+
const text = typeof record.text === "string" ? record.text : "";
|
|
339
|
+
return text ? sanitizeSurrogates(text) : void 0;
|
|
340
|
+
}
|
|
341
|
+
const structured = stringifyStructuredBlock(record);
|
|
342
|
+
return structured ? sanitizeSurrogates(truncateProviderToolText(structured)) : void 0;
|
|
343
|
+
}
|
|
344
|
+
function extractToolResultText(blocks) {
|
|
345
|
+
const explicitTexts = [];
|
|
346
|
+
const structuredTexts = [];
|
|
347
|
+
for (const block of blocks) {
|
|
348
|
+
const text = extractToolResultBlockText(block);
|
|
349
|
+
if (!text) continue;
|
|
350
|
+
if (block.type === "text") explicitTexts.push(text);
|
|
351
|
+
else structuredTexts.push(text);
|
|
352
|
+
}
|
|
353
|
+
if (explicitTexts.length > 0) return sanitizeSurrogates(explicitTexts.join("\n"));
|
|
354
|
+
return sanitizeSurrogates(truncateProviderToolText(structuredTexts.join("\n")));
|
|
355
|
+
}
|
|
356
|
+
//#endregion
|
|
357
|
+
//#region packages/ai/src/providers/transform-messages.ts
|
|
358
|
+
const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
|
|
359
|
+
const NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
|
|
360
|
+
function replaceImagesWithPlaceholder(content, placeholder) {
|
|
361
|
+
const result = [];
|
|
362
|
+
let previousWasPlaceholder = false;
|
|
363
|
+
for (const block of content) {
|
|
364
|
+
if (block.type === "image") {
|
|
365
|
+
if (!previousWasPlaceholder) result.push({
|
|
366
|
+
type: "text",
|
|
367
|
+
text: placeholder
|
|
368
|
+
});
|
|
369
|
+
previousWasPlaceholder = true;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
result.push(block);
|
|
373
|
+
previousWasPlaceholder = block.text === placeholder;
|
|
374
|
+
}
|
|
375
|
+
return result;
|
|
376
|
+
}
|
|
377
|
+
function downgradeUnsupportedImages(messages, model) {
|
|
378
|
+
if (model.input.includes("image")) return messages;
|
|
379
|
+
return messages.map((msg) => {
|
|
380
|
+
if (msg.role === "user" && Array.isArray(msg.content)) return {
|
|
381
|
+
...msg,
|
|
382
|
+
content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER)
|
|
383
|
+
};
|
|
384
|
+
if (msg.role === "toolResult") return {
|
|
385
|
+
...msg,
|
|
386
|
+
content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER)
|
|
387
|
+
};
|
|
388
|
+
return msg;
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Normalize tool call ID for cross-provider compatibility.
|
|
393
|
+
* OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.
|
|
394
|
+
* Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).
|
|
395
|
+
*/
|
|
396
|
+
function transformMessages(messages, model, normalizeToolCallId) {
|
|
397
|
+
const toolCallIdMap = /* @__PURE__ */ new Map();
|
|
398
|
+
const transformed = downgradeUnsupportedImages(messages, model).map((msg) => {
|
|
399
|
+
if (msg.role === "user") return msg;
|
|
400
|
+
if (msg.role === "toolResult") {
|
|
401
|
+
const normalizedId = toolCallIdMap.get(msg.toolCallId);
|
|
402
|
+
if (normalizedId && normalizedId !== msg.toolCallId) return Object.assign({}, msg, { toolCallId: normalizedId });
|
|
403
|
+
return msg;
|
|
404
|
+
}
|
|
405
|
+
if (msg.role === "assistant") {
|
|
406
|
+
const assistantMsg = msg;
|
|
407
|
+
const modelBoundThinkingReplayMode = resolveModelBoundThinkingReplayMode({
|
|
408
|
+
source: {
|
|
409
|
+
provider: assistantMsg.provider,
|
|
410
|
+
api: assistantMsg.api,
|
|
411
|
+
modelId: assistantMsg.model,
|
|
412
|
+
responseModelId: assistantMsg.responseModel
|
|
413
|
+
},
|
|
414
|
+
target: {
|
|
415
|
+
provider: model.provider,
|
|
416
|
+
api: model.api,
|
|
417
|
+
modelId: model.id,
|
|
418
|
+
modelParams: model.params
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
const isSameModel = modelBoundThinkingReplayMode === "preserve" || assistantMsg.provider === model.provider && assistantMsg.api === model.api && assistantMsg.model === model.id;
|
|
422
|
+
const transformedContent = (typeof assistantMsg.content === "string" ? [{
|
|
423
|
+
type: "text",
|
|
424
|
+
text: assistantMsg.content
|
|
425
|
+
}] : assistantMsg.content).flatMap((block) => {
|
|
426
|
+
if (block.type === "thinking") {
|
|
427
|
+
if (modelBoundThinkingReplayMode === "drop") return [];
|
|
428
|
+
if (block.redacted) return isSameModel ? block : [];
|
|
429
|
+
if (isSameModel && block.thinkingSignature) return block;
|
|
430
|
+
if (!block.thinking || block.thinking.trim() === "") return [];
|
|
431
|
+
if (isSameModel) return block;
|
|
432
|
+
return {
|
|
433
|
+
type: "text",
|
|
434
|
+
text: block.thinking
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
if (block.type === "text") {
|
|
438
|
+
if (isSameModel) return block;
|
|
439
|
+
return {
|
|
440
|
+
type: "text",
|
|
441
|
+
text: block.text
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
if (block.type === "toolCall") {
|
|
445
|
+
const toolCall = block;
|
|
446
|
+
let normalizedToolCall = toolCall;
|
|
447
|
+
if (!isSameModel && toolCall.thoughtSignature) {
|
|
448
|
+
normalizedToolCall = Object.assign({}, toolCall);
|
|
449
|
+
delete normalizedToolCall.thoughtSignature;
|
|
450
|
+
}
|
|
451
|
+
if (!isSameModel && normalizeToolCallId) {
|
|
452
|
+
const normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);
|
|
453
|
+
if (normalizedId !== toolCall.id) {
|
|
454
|
+
toolCallIdMap.set(toolCall.id, normalizedId);
|
|
455
|
+
normalizedToolCall = Object.assign({}, normalizedToolCall, { id: normalizedId });
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return normalizedToolCall;
|
|
459
|
+
}
|
|
460
|
+
return block;
|
|
461
|
+
});
|
|
462
|
+
return Object.assign({}, assistantMsg, { content: transformedContent });
|
|
463
|
+
}
|
|
464
|
+
return msg;
|
|
465
|
+
});
|
|
466
|
+
const result = [];
|
|
467
|
+
let pendingToolCalls = [];
|
|
468
|
+
let existingToolResultIds = /* @__PURE__ */ new Set();
|
|
469
|
+
const insertSyntheticToolResults = () => {
|
|
470
|
+
if (pendingToolCalls.length > 0) {
|
|
471
|
+
for (const tc of pendingToolCalls) if (!existingToolResultIds.has(tc.id)) result.push({
|
|
472
|
+
role: "toolResult",
|
|
473
|
+
toolCallId: tc.id,
|
|
474
|
+
toolName: tc.name,
|
|
475
|
+
content: [{
|
|
476
|
+
type: "text",
|
|
477
|
+
text: "No result provided"
|
|
478
|
+
}],
|
|
479
|
+
isError: true,
|
|
480
|
+
timestamp: Date.now()
|
|
481
|
+
});
|
|
482
|
+
pendingToolCalls = [];
|
|
483
|
+
existingToolResultIds = /* @__PURE__ */ new Set();
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
for (const msg of transformed) if (msg.role === "assistant") {
|
|
487
|
+
insertSyntheticToolResults();
|
|
488
|
+
const assistantMsg = msg;
|
|
489
|
+
if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") continue;
|
|
490
|
+
const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall");
|
|
491
|
+
if (toolCalls.length > 0) {
|
|
492
|
+
pendingToolCalls = toolCalls;
|
|
493
|
+
existingToolResultIds = /* @__PURE__ */ new Set();
|
|
494
|
+
}
|
|
495
|
+
result.push(msg);
|
|
496
|
+
} else if (msg.role === "toolResult") {
|
|
497
|
+
existingToolResultIds.add(msg.toolCallId);
|
|
498
|
+
result.push(msg);
|
|
499
|
+
} else if (msg.role === "user") {
|
|
500
|
+
insertSyntheticToolResults();
|
|
501
|
+
result.push(msg);
|
|
502
|
+
} else result.push(msg);
|
|
503
|
+
insertSyntheticToolResults();
|
|
504
|
+
return result;
|
|
505
|
+
}
|
|
506
|
+
//#endregion
|
|
507
|
+
export { normalizeLowercaseStringOrEmpty as C, normalizeStructuredPromptSection as S, ensureSystemPromptCacheBoundary as _, adjustMaxTokensForThinking as a, stripSystemPromptCacheBoundary as b, isRecord as c, prepareClaudeSonnet5RequestContext as d, requiresClaudeAdaptiveThinking as f, SYSTEM_PROMPT_CACHE_BOUNDARY as g, usesClaudeStreamingRefusalContract as h, extractToolResultText as i, applyClaudeRequestContract as l, usesClaudeFable5MessagesContract as m, describeToolResultMediaPlaceholder as n, buildBaseOptions as o, resolveModelBoundThinkingReplayMode as p, extractToolResultBlockText as r, clampReasoning as s, transformMessages as t, defaultsClaudeAdaptiveThinking as u, prependSystemPromptAdditionAfterCacheBoundary as v, normalizeOptionalString as w, normalizePromptCapabilityIds as x, splitSystemPromptCacheBoundary as y };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|