@openclaw/ai 2026.9.2 → 2026.9.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/README.md +3 -2
- package/dist/anthropic-C4Qu4H0Z.mjs +377 -0
- package/dist/{anthropic-payload-policy-d46X2pR0.d.mts → anthropic-payload-policy-BZ8umAbk.d.mts} +16 -6
- package/dist/{anthropic-compaction-replay-DB2FGLQc.mjs → anthropic-stream-reducer-CILWF7JD.mjs} +931 -184
- package/dist/{api-registry-DWtPjzyn.d.mts → api-registry-ByUwIR0e.d.mts} +2 -2
- package/dist/assistant-output-tLt4H-iQ.mjs +16 -0
- package/dist/assistant-text-phase-C20rxWwP.mjs +55 -0
- package/dist/{azure-openai-responses-C5bZRfAP.mjs → azure-openai-responses-BAlqlKKc.mjs} +5 -5
- package/dist/{base64-CEFBpSkN.mjs → base64-D-su8YVo.mjs} +1 -27
- package/dist/{diagnostics-DfFyKeX_.mjs → diagnostics-QuErwCIl.mjs} +96 -21
- package/dist/diagnostics.d.mts +3 -1
- package/dist/diagnostics.mjs +3 -3
- package/dist/{event-stream-BhT5T1Ay.d.mts → event-stream-Bt5Y4Pav.d.mts} +11 -3
- package/dist/event-stream-C3WGFsum.d.mts +1 -0
- package/dist/{event-stream-BgDvQeum.mjs → event-stream-D8PARQfL.mjs} +45 -1
- package/dist/event-stream.d.mts +2 -2
- package/dist/event-stream.mjs +1 -1
- package/dist/{github-copilot-headers-NCJtz9i0.mjs → github-copilot-headers-B37TB3rB.mjs} +3 -10
- package/dist/github-copilot-request-facts-BTEBMeOv.mjs +16 -0
- package/dist/{google-4qeuE8iX.mjs → google-DPBAOaOW.mjs} +10 -10
- package/dist/google-messages-6JkpHrhJ.mjs +448 -0
- package/dist/google-shared-BvBeW9aq.mjs +185 -0
- package/dist/{google-vertex-O9BcnB6X.mjs → google-vertex-k-TMCAYD.mjs} +7 -6
- package/dist/{host-DjzGmdZ2.d.mts → host-4atIX-2V.d.mts} +5 -3
- package/dist/{host-CEvLw30U.mjs → host-B8YfDGd4.mjs} +181 -41
- package/dist/host-policy-Zcg_cNz8.mjs +37 -0
- package/dist/{index-FnHM2FcI.d.mts → index-DdD3qerf.d.mts} +4 -4
- package/dist/index.d.mts +7 -7
- package/dist/index.mjs +7 -6
- package/dist/internal/anthropic.d.mts +7 -7
- package/dist/internal/anthropic.mjs +4 -4
- package/dist/internal/google-model-family.d.mts +5 -0
- package/dist/internal/google-model-family.mjs +15 -0
- package/dist/internal/openai-responses-payload-policy.d.mts +3 -3
- package/dist/internal/openai-responses-payload-policy.mjs +3 -2
- package/dist/internal/openai.d.mts +8 -103
- package/dist/internal/openai.mjs +9 -10
- package/dist/internal/retry-after.d.mts +2 -4
- package/dist/internal/retry-after.mjs +57 -8
- package/dist/internal/runtime.d.mts +43 -7
- package/dist/internal/runtime.mjs +6 -7
- package/dist/internal/shared.d.mts +43 -3
- package/dist/internal/shared.mjs +5 -4
- package/dist/internal/tool-schema.d.mts +63 -0
- package/dist/internal/tool-schema.mjs +3 -0
- package/dist/{mistral-Tb6oalqH.mjs → mistral-CxUZ1jUb.mjs} +10 -37
- package/dist/model-transport-url-DKocrEsb.d.mts +28 -0
- package/dist/{openai-chatgpt-responses-yUXjPNfu.mjs → openai-chatgpt-responses-CgO6kZfo.mjs} +50 -41
- package/dist/{openai-completions-compat-CpjYUArk.d.mts → openai-completions-compat-eHgh5UPE.d.mts} +26 -4
- package/dist/{openai-completions-stream-BsrBe3Gg.mjs → openai-completions-stream-Da2vvl-S.mjs} +654 -453
- package/dist/openai-completions-yJuk7eis.mjs +187 -0
- package/dist/openai-prompt-cache-B4eYo2-I.d.mts +16 -0
- package/dist/openai-prompt-cache-Bds-n_9Q.mjs +220 -0
- package/dist/openai-provider-client-S2gCrM2Z.mjs +24 -0
- package/dist/{openai-responses-CCL41ALM.mjs → openai-responses-DaYwH05E.mjs} +14 -29
- package/dist/{openai-responses-compaction-window-BMVHFOtq.mjs → openai-responses-compaction-window-CIhBAkkq.mjs} +6 -246
- package/dist/{openai-responses-contracts-rF5DDRNS.d.mts → openai-responses-contracts-BjBAqAg_.d.mts} +5 -38
- package/dist/openai-responses-contracts-DDOHA62Y.mjs +245 -0
- package/dist/{openai-responses-prompt-observer-internal-D0bhBfgL.mjs → openai-responses-prompt-observer-internal-f8J7wpsk.mjs} +3 -3
- package/dist/{openai-responses-shared-Bmma_3Qc.mjs → openai-responses-shared-B8RdBPCv.mjs} +47 -118
- package/dist/openai-tool-projection-793cE3QX.d.mts +37 -0
- package/dist/{openai-tool-schema-_pTAJqKF.mjs → openai-tool-schema-CzjyYXun.mjs} +38 -556
- package/dist/openai-tool-schema-ynZBgqW-.d.mts +38 -0
- package/dist/openai-transport-params-9aPuV5YY.mjs +675 -0
- package/dist/positive-integer-41zhOdcV.mjs +8 -0
- package/dist/{provider-error-9TraxGvt.mjs → provider-error-BA-v_tKd.mjs} +70 -11
- package/dist/{provider-options-Bcc_p-TU.d.mts → provider-options-Ceqv1OKk.d.mts} +4 -39
- package/dist/{provider-replay-context-BuSUaAk5.mjs → provider-replay-context-CJ_YvcEW.mjs} +1 -1
- package/dist/{provider-transcript-transform-BaMbI1hr.mjs → provider-transcript-transform-V5YzU9zh.mjs} +1 -1
- package/dist/provider-transport-turn-state-D5EXOFL2.mjs +42 -0
- package/dist/provider-types-CVjKjsuq.d.mts +29 -0
- package/dist/provider-types.d.mts +6 -31
- package/dist/providers.d.mts +2 -2
- package/dist/providers.mjs +11 -11
- package/dist/{reasoning-tag-text-partitioner-DLCNXki6.mjs → reasoning-tag-text-partitioner-BcR5pztD.mjs} +19 -19
- package/dist/record-coerce-DwRYMj3t.mjs +32 -0
- package/dist/retry-after-CdCURCVg.d.mts +15 -0
- package/dist/session-affinity-Bcunsn4I.mjs +23 -0
- package/dist/{simple-options-BjHCCh4v.mjs → simple-options-BQbb4yQL.mjs} +24 -5
- package/dist/src-DDmEryvj.mjs +2 -0
- package/dist/{stream-first-event-timeout-DcNjoFQE.mjs → stream-first-event-timeout-2hfrquuz.mjs} +1 -1
- package/dist/string-coerce-fsri9iCu.mjs +34 -0
- package/dist/{string-normalization--fwJ4S2q.mjs → string-normalization-CmLIasuf.mjs} +1 -1
- package/dist/{tool-schema-json-projection-mJhXDcyz.mjs → tool-schema-json-projection-ClptDdAO.mjs} +2 -38
- package/dist/{transport-stream-shared-xnaqxmbP.d.mts → transport-stream-shared-DNvmoWnv.d.mts} +20 -36
- package/dist/{transport-stream-shared-CZqMhfIw.mjs → transport-stream-shared-zHll9BxO.mjs} +225 -13
- package/dist/transport-utils-zrYjICLZ.mjs +118 -0
- package/dist/transports.d.mts +137 -193
- package/dist/transports.mjs +204 -1334
- package/dist/types-DlfwzH3T.d.mts +1 -0
- package/dist/types-LFWwv0cF.mjs +8 -0
- package/dist/{types-CJ1-Ht7A.d.mts → types-Ntv5z2g2.d.mts} +74 -57
- package/dist/types.d.mts +6 -6
- package/dist/types.mjs +6 -5
- package/dist/{src-2qBGKg8O.mjs → usage-cost-BNWbbXav.mjs} +0 -1
- package/dist/utf16-slice-CvGodqok.mjs +29 -0
- package/dist/{validation-AKZBDGQd.d.mts → validation-B0t_G2H6.d.mts} +1 -1
- package/dist/{validation-CJZtym2g.mjs → validation-BDzVDnTs.mjs} +9 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/package.json +13 -3
- package/dist/anthropic-BDdqdVLK.mjs +0 -886
- package/dist/event-stream-zctLx0yr.d.mts +0 -1
- package/dist/google-shared-CWeG8RIl.mjs +0 -636
- package/dist/google-thinking-level-C-V3tecN.mjs +0 -9
- package/dist/hash-CHgqbJmD.mjs +0 -16
- package/dist/json-parse-BuAJEbdW.mjs +0 -146
- package/dist/openai-completions-BIUV3RDT.mjs +0 -403
- package/dist/openai-prompt-cache-CGnVB74a.mjs +0 -21
- package/dist/openai-prompt-cache-CNoIfHYC.d.mts +0 -16
- package/dist/sanitize-unicode-D6xUvZaS.mjs +0 -83
- package/dist/transport-utils-7il795_9.mjs +0 -138
- package/dist/types-3Lnm-QSJ.d.mts +0 -1
- package/dist/types-BDdaOVi2.mjs +0 -6
- package/dist/utf16-slice-qz3nsy87.mjs +0 -84
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { n as normalizeLowercaseStringOrEmpty } from "./string-coerce-fsri9iCu.mjs";
|
|
2
|
+
import { v as sanitizeSurrogates } from "./host-B8YfDGd4.mjs";
|
|
3
|
+
import { i as copyProviderAcceptanceObserver } from "./transport-stream-shared-zHll9BxO.mjs";
|
|
4
4
|
//#region packages/ai/src/utils/prompt-cache-stability.ts
|
|
5
5
|
/**
|
|
6
6
|
* Prompt-cache normalization helpers. They keep generated prompt sections
|
|
@@ -40,8 +40,23 @@ function normalizePromptCapabilityIds(capabilities) {
|
|
|
40
40
|
* Keeps stable prompt prefixes separate from dynamic runtime additions for provider prompt caching.
|
|
41
41
|
*/
|
|
42
42
|
const SYSTEM_PROMPT_CACHE_BOUNDARY = "\n<!-- OPENCLAW_CACHE_BOUNDARY -->\n";
|
|
43
|
+
/** Producer-delimited Runtime facts; instructions must remain outside this region. */
|
|
44
|
+
const SYSTEM_PROMPT_RELOCATABLE_BOUNDARY = "\n<!-- OPENCLAW-RELOCATABLE-BOUNDARY -->\n";
|
|
45
|
+
const SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END = "\n<!-- /OPENCLAW-RELOCATABLE-BOUNDARY -->";
|
|
43
46
|
function stripSystemPromptCacheBoundary(text) {
|
|
44
|
-
return text.replaceAll(SYSTEM_PROMPT_CACHE_BOUNDARY, "\n");
|
|
47
|
+
return stripSystemPromptRelocatableBoundary(text.replaceAll(SYSTEM_PROMPT_CACHE_BOUNDARY, "\n").replaceAll(SYSTEM_PROMPT_CACHE_BOUNDARY.trim(), ""));
|
|
48
|
+
}
|
|
49
|
+
/** Reject ambiguous markers from workspace or hook text instead of moving instructions. */
|
|
50
|
+
function splitSystemPromptRelocatableBoundary(text) {
|
|
51
|
+
const opening = SYSTEM_PROMPT_RELOCATABLE_BOUNDARY.trim();
|
|
52
|
+
const closing = SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END.trim();
|
|
53
|
+
const start = text.indexOf(opening);
|
|
54
|
+
const end = text.indexOf(closing);
|
|
55
|
+
if (start === -1 || end < start || text.includes(opening, start + 38) || text.includes(closing, end + 39)) return;
|
|
56
|
+
return {
|
|
57
|
+
remainingPrompt: [text.slice(0, start).trimEnd(), text.slice(end + 39).trimStart()].filter(Boolean).join("\n"),
|
|
58
|
+
relocatable: text.slice(start + 38, end).trim()
|
|
59
|
+
};
|
|
45
60
|
}
|
|
46
61
|
function ensureSystemPromptCacheBoundary(systemPrompt) {
|
|
47
62
|
if (systemPrompt.trim().length === 0) return systemPrompt;
|
|
@@ -55,6 +70,10 @@ function splitSystemPromptCacheBoundary(text) {
|
|
|
55
70
|
dynamicSuffix: text.slice(boundaryIndex + 34).trimStart()
|
|
56
71
|
};
|
|
57
72
|
}
|
|
73
|
+
/** Keep explicit cache breakpoints while removing relocation metadata. */
|
|
74
|
+
function stripSystemPromptRelocatableBoundary(text) {
|
|
75
|
+
return text.replaceAll(SYSTEM_PROMPT_RELOCATABLE_BOUNDARY, "\n").replaceAll(SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END, "").replaceAll(SYSTEM_PROMPT_RELOCATABLE_BOUNDARY.trim(), "").replaceAll(SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END.trim(), "");
|
|
76
|
+
}
|
|
58
77
|
function prependSystemPromptAdditionAfterCacheBoundary(params) {
|
|
59
78
|
const systemPromptAddition = typeof params.systemPromptAddition === "string" ? normalizeStructuredPromptSection(params.systemPromptAddition) : "";
|
|
60
79
|
if (!systemPromptAddition) return params.systemPrompt;
|
|
@@ -151,4 +170,4 @@ function adjustMaxTokensForThinking(baseMaxTokens, modelMaxTokens, reasoningLeve
|
|
|
151
170
|
};
|
|
152
171
|
}
|
|
153
172
|
//#endregion
|
|
154
|
-
export { codeModeToolSurfaceObserver as a,
|
|
173
|
+
export { normalizeStructuredPromptSection as _, codeModeToolSurfaceObserver as a, SYSTEM_PROMPT_RELOCATABLE_BOUNDARY as c, prependSystemPromptAdditionAfterCacheBoundary as d, splitSystemPromptCacheBoundary as f, normalizePromptCapabilityIds as g, stripSystemPromptRelocatableBoundary as h, clampReasoning as i, SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END as l, stripSystemPromptCacheBoundary as m, buildBaseOptions as n, reasoningTagTextPolicy as o, splitSystemPromptRelocatableBoundary as p, clampMaxTokensToModel as r, SYSTEM_PROMPT_CACHE_BOUNDARY as s, adjustMaxTokensForThinking as t, ensureSystemPromptCacheBoundary as u, sortPromptCacheToolsByName as v };
|
package/dist/{stream-first-event-timeout-DcNjoFQE.mjs → stream-first-event-timeout-2hfrquuz.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as clampTimerTimeoutMs } from "./base64-D-su8YVo.mjs";
|
|
2
2
|
//#region packages/ai/src/utils/stream-first-event-timeout.ts
|
|
3
3
|
function getFirstStreamEventTimeoutMs(options) {
|
|
4
4
|
return options?.firstEventTimeoutMs;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//#region packages/normalization-core/src/string-coerce.ts
|
|
2
|
+
/** Reads a value only when it is already a string, preserving whitespace. */
|
|
3
|
+
function readStringValue(value) {
|
|
4
|
+
return typeof value === "string" ? value : void 0;
|
|
5
|
+
}
|
|
6
|
+
/** Trims string input and returns null for non-strings or empty strings. */
|
|
7
|
+
function normalizeNullableString(value) {
|
|
8
|
+
if (typeof value !== "string") return null;
|
|
9
|
+
const trimmed = value.trim();
|
|
10
|
+
return trimmed ? trimmed : null;
|
|
11
|
+
}
|
|
12
|
+
/** Trims string input and returns undefined for non-strings or empty strings. */
|
|
13
|
+
function normalizeOptionalString(value) {
|
|
14
|
+
return normalizeNullableString(value) ?? void 0;
|
|
15
|
+
}
|
|
16
|
+
/** Stringifies primitive ids/flags before applying optional string normalization. */
|
|
17
|
+
function normalizeStringifiedOptionalString(value) {
|
|
18
|
+
if (typeof value === "string") return normalizeOptionalString(value);
|
|
19
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return normalizeOptionalString(String(value));
|
|
20
|
+
}
|
|
21
|
+
/** Lowercases a normalized optional string. */
|
|
22
|
+
function normalizeOptionalLowercaseString(value) {
|
|
23
|
+
return normalizeOptionalString(value)?.toLowerCase();
|
|
24
|
+
}
|
|
25
|
+
/** Lowercases a normalized string or returns an empty string when absent. */
|
|
26
|
+
function normalizeLowercaseStringOrEmpty(value) {
|
|
27
|
+
return normalizeOptionalLowercaseString(value) ?? "";
|
|
28
|
+
}
|
|
29
|
+
/** Type guard for strings that remain non-empty after trimming. */
|
|
30
|
+
function hasNonEmptyString(value) {
|
|
31
|
+
return normalizeOptionalString(value) !== void 0;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { normalizeOptionalString as a, normalizeOptionalLowercaseString as i, normalizeLowercaseStringOrEmpty as n, normalizeStringifiedOptionalString as o, normalizeNullableString as r, readStringValue as s, hasNonEmptyString as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as normalizeOptionalString } from "./string-coerce-fsri9iCu.mjs";
|
|
2
2
|
//#region packages/normalization-core/src/string-normalization.ts
|
|
3
3
|
/** Coerces entries to strings, trims them, and drops empty results. */
|
|
4
4
|
function normalizeStringEntries(list) {
|
package/dist/{tool-schema-json-projection-mJhXDcyz.mjs → tool-schema-json-projection-ClptDdAO.mjs}
RENAMED
|
@@ -1,41 +1,5 @@
|
|
|
1
|
-
import { o as isRecord } from "./
|
|
2
|
-
import { n as getAiTransportHost } from "./host-CEvLw30U.mjs";
|
|
1
|
+
import { o as isRecord } from "./record-coerce-DwRYMj3t.mjs";
|
|
3
2
|
import { types } from "node:util";
|
|
4
|
-
//#region packages/ai/src/transports/host-policy.ts
|
|
5
|
-
function buildGuardedModelFetch(model, timeoutMs, options) {
|
|
6
|
-
const host = getAiTransportHost();
|
|
7
|
-
if (options !== void 0) return host.buildModelFetch(model, timeoutMs, options) ?? globalThis.fetch;
|
|
8
|
-
if (timeoutMs !== void 0) return host.buildModelFetch(model, timeoutMs) ?? globalThis.fetch;
|
|
9
|
-
return host.buildModelFetch(model) ?? globalThis.fetch;
|
|
10
|
-
}
|
|
11
|
-
function resolveProviderEndpoint(model) {
|
|
12
|
-
return { endpointClass: getAiTransportHost().resolveProviderRequestCapabilities({
|
|
13
|
-
baseUrl: model.baseUrl,
|
|
14
|
-
model
|
|
15
|
-
}).endpointClass };
|
|
16
|
-
}
|
|
17
|
-
function resolveProviderRequestCapabilities(input, model) {
|
|
18
|
-
return getAiTransportHost().resolveProviderRequestCapabilities({
|
|
19
|
-
...input,
|
|
20
|
-
model
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
function resolveProviderRequestPolicyConfig(model, input) {
|
|
24
|
-
return { headers: getAiTransportHost().resolveProviderRequestHeaders({
|
|
25
|
-
...input,
|
|
26
|
-
model
|
|
27
|
-
}) };
|
|
28
|
-
}
|
|
29
|
-
function resolveModelRequestTimeoutMs(model, timeoutMs) {
|
|
30
|
-
return timeoutMs ?? getAiTransportHost().resolveModelRequestTimeoutMs(model);
|
|
31
|
-
}
|
|
32
|
-
function resolveOpenAIStrictToolSetting(model, options) {
|
|
33
|
-
return getAiTransportHost().resolveOpenAIStrictToolSetting(model, options);
|
|
34
|
-
}
|
|
35
|
-
function transformTransportMessages(messages, model, normalizeToolCallId, options) {
|
|
36
|
-
return getAiTransportHost().transformTransportMessages(messages, model, normalizeToolCallId, options);
|
|
37
|
-
}
|
|
38
|
-
//#endregion
|
|
39
3
|
//#region packages/ai/src/providers/tool-schema-json-projection.ts
|
|
40
4
|
function isNonFiniteNumberValue(value) {
|
|
41
5
|
if (typeof value === "number") return !Number.isFinite(value);
|
|
@@ -115,4 +79,4 @@ function projectRuntimeToolInputSchema(schema, path = "parameters") {
|
|
|
115
79
|
};
|
|
116
80
|
}
|
|
117
81
|
//#endregion
|
|
118
|
-
export {
|
|
82
|
+
export { projectRuntimeToolInputSchema as t };
|
package/dist/{transport-stream-shared-xnaqxmbP.d.mts → transport-stream-shared-DNvmoWnv.d.mts}
RENAMED
|
@@ -1,36 +1,8 @@
|
|
|
1
|
-
import "./index-
|
|
2
|
-
import {
|
|
3
|
-
import { r as createAssistantMessageEventStream, t as AssistantMessageEventStream } from "./event-stream-
|
|
4
|
-
import "./event-stream-
|
|
1
|
+
import "./index-DdD3qerf.mjs";
|
|
2
|
+
import { O as Model, V as ProviderResponse, Y as StreamOptions, a as AssistantMessage, ot as Usage } from "./types-Ntv5z2g2.mjs";
|
|
3
|
+
import { r as createAssistantMessageEventStream, t as AssistantMessageEventStream } from "./event-stream-Bt5Y4Pav.mjs";
|
|
4
|
+
import "./event-stream-C3WGFsum.mjs";
|
|
5
5
|
import { t as ProviderErrorProjection } from "./provider-error-CzNw4BWX.mjs";
|
|
6
|
-
//#region packages/ai/src/utils/stream-first-event-timeout.d.ts
|
|
7
|
-
type StreamStage = "responses" | "completions";
|
|
8
|
-
type FirstStreamEventTimeoutContext = {
|
|
9
|
-
provider?: string;
|
|
10
|
-
api?: string;
|
|
11
|
-
model?: string;
|
|
12
|
-
timeoutMs: number;
|
|
13
|
-
stage?: StreamStage;
|
|
14
|
-
hint?: string;
|
|
15
|
-
abort?: (reason: Error) => void;
|
|
16
|
-
onTimeout?: (reason: Error) => void;
|
|
17
|
-
};
|
|
18
|
-
type FirstStreamEventInternalOptions = {
|
|
19
|
-
firstEventTimeoutMs?: number;
|
|
20
|
-
abortFirstEventStream?: (reason: Error) => void;
|
|
21
|
-
onFirstEventTimeout?: (reason: Error) => void;
|
|
22
|
-
};
|
|
23
|
-
type FirstStreamEventAbortController = {
|
|
24
|
-
signal: AbortSignal;
|
|
25
|
-
abort: (reason: Error) => void;
|
|
26
|
-
dispose: () => void;
|
|
27
|
-
};
|
|
28
|
-
declare function getFirstStreamEventTimeoutMs(options: unknown): number | undefined;
|
|
29
|
-
declare function getFirstStreamEventTimeoutHandler(options: unknown): ((reason: Error) => void) | undefined;
|
|
30
|
-
declare function createFirstStreamEventTimeoutError(context: FirstStreamEventTimeoutContext): Error;
|
|
31
|
-
declare function createFirstStreamEventAbortController(parentSignal?: AbortSignal): FirstStreamEventAbortController;
|
|
32
|
-
declare function withFirstStreamEventTimeout<T>(stream: AsyncIterable<T>, context: FirstStreamEventTimeoutContext): AsyncIterable<T>;
|
|
33
|
-
//#endregion
|
|
34
6
|
//#region packages/ai/src/transports/transport-stream-shared.d.ts
|
|
35
7
|
type ContextUsage = NonNullable<Usage["contextUsage"]>;
|
|
36
8
|
type TransportUsage = {
|
|
@@ -52,12 +24,24 @@ type WritableTransportStream = Pick<ReturnType<typeof createAssistantMessageEven
|
|
|
52
24
|
declare function sanitizeTransportPayloadText(text: string): string;
|
|
53
25
|
declare function sanitizeNonEmptyTransportPayloadText(text: string, fallback?: string): string;
|
|
54
26
|
declare function coerceTransportToolCallArguments(argumentsValue: unknown): Record<string, unknown>;
|
|
55
|
-
/**
|
|
56
|
-
declare
|
|
27
|
+
/** Stable terminal fact: presentation must not infer unfinished calls from provider prose. */
|
|
28
|
+
declare class IncompleteToolCallError extends Error {
|
|
29
|
+
readonly code = "incomplete_tool_call";
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Admit only complete object-shaped terminal tool arguments; partial parsing is preview-only.
|
|
33
|
+
* `repairStringLiterals` opts a stream whose provider may deliver unvalidated tool input into
|
|
34
|
+
* string-literal repair before rejection.
|
|
35
|
+
*/
|
|
36
|
+
declare function parseTerminalToolCallArguments(value: unknown, errorMessage?: string, options?: {
|
|
37
|
+
repairStringLiterals?: boolean;
|
|
38
|
+
}): Record<string, unknown>;
|
|
57
39
|
/** Validate a complete sibling set before mutating any call into executable state. */
|
|
58
40
|
declare function finalizeTerminalToolCallArguments<T extends {
|
|
59
41
|
arguments: Record<string, unknown>;
|
|
60
|
-
}>(calls: readonly T[], readArguments: (call: T) => unknown, errorMessage?: string
|
|
42
|
+
}>(calls: readonly T[], readArguments: (call: T) => unknown, errorMessage?: string, options?: {
|
|
43
|
+
repairStringLiterals?: boolean;
|
|
44
|
+
}): void;
|
|
61
45
|
declare function mergeTransportHeaders(...headerSources: Array<Record<string, string> | undefined>): Record<string, string> | undefined;
|
|
62
46
|
declare function mergeTransportMetadata<T extends Record<string, unknown>>(payload: T, metadata?: Record<string, string>): T;
|
|
63
47
|
declare function createEmptyTransportUsage(): TransportUsage;
|
|
@@ -135,4 +119,4 @@ declare function failTransportStream(params: {
|
|
|
135
119
|
cleanup?: () => void;
|
|
136
120
|
}): void;
|
|
137
121
|
//#endregion
|
|
138
|
-
export {
|
|
122
|
+
export { withProviderResponseHook as S, parseTerminalToolCallArguments as _, coerceTransportToolCallArguments as a, transportAbortError as b, createWritableTransportEventStream as c, finalizeTransportStream as d, mergeTransportHeaders as f, notifyProviderStreamOpened as g, notifyProviderHttpResponse as h, assignTransportErrorDetails as i, failTransportStream as l, notifyProviderHttpMetadata as m, ProviderAcceptance as n, copyProviderAcceptanceObserver as o, mergeTransportMetadata as p, WritableTransportStream as r, createEmptyTransportUsage as s, IncompleteToolCallError as t, finalizeTerminalToolCallArguments as u, sanitizeNonEmptyTransportPayloadText as v, withProviderAcceptanceObserver as x, sanitizeTransportPayloadText as y };
|
|
@@ -1,9 +1,25 @@
|
|
|
1
1
|
import { n as createAssistantMessageDiagnostic, t as appendAssistantMessageDiagnostic } from "./diagnostics-CPeq9F7y.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { t as
|
|
5
|
-
import { n as projectProviderError, r as projectDiagnosticValue } from "./provider-error-
|
|
6
|
-
import {
|
|
2
|
+
import { i as createAssistantMessageEventStream } from "./event-stream-D8PARQfL.mjs";
|
|
3
|
+
import { n as getAiTransportHost, v as sanitizeSurrogates } from "./host-B8YfDGd4.mjs";
|
|
4
|
+
import { i as asOptionalRecord, n as asNullableRecord, t as asNonArrayRecord } from "./record-coerce-DwRYMj3t.mjs";
|
|
5
|
+
import { n as projectProviderError, r as projectDiagnosticValue } from "./provider-error-BA-v_tKd.mjs";
|
|
6
|
+
import { c as isTransientNetworkError } from "./diagnostics-QuErwCIl.mjs";
|
|
7
|
+
import { parse } from "partial-json";
|
|
8
|
+
//#region packages/ai/src/utils/hash.ts
|
|
9
|
+
/** Fast deterministic hash to shorten long strings */
|
|
10
|
+
function shortHash(str) {
|
|
11
|
+
let h1 = 3735928559;
|
|
12
|
+
let h2 = 1103547991;
|
|
13
|
+
for (let i = 0; i < str.length; i++) {
|
|
14
|
+
const ch = str.charCodeAt(i);
|
|
15
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
16
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
17
|
+
}
|
|
18
|
+
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
|
|
19
|
+
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
20
|
+
return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
7
23
|
//#region packages/ai/src/utils/headers.ts
|
|
8
24
|
/** Converts a Headers object to a plain record for provider request handling. */
|
|
9
25
|
function headersToRecord(headers) {
|
|
@@ -12,6 +28,155 @@ function headersToRecord(headers) {
|
|
|
12
28
|
return result;
|
|
13
29
|
}
|
|
14
30
|
//#endregion
|
|
31
|
+
//#region packages/ai/src/utils/json-parse.ts
|
|
32
|
+
const VALID_JSON_ESCAPES = /* @__PURE__ */ new Set([
|
|
33
|
+
"\"",
|
|
34
|
+
"\\",
|
|
35
|
+
"/",
|
|
36
|
+
"b",
|
|
37
|
+
"f",
|
|
38
|
+
"n",
|
|
39
|
+
"r",
|
|
40
|
+
"t",
|
|
41
|
+
"u"
|
|
42
|
+
]);
|
|
43
|
+
const JSON_CONTROL_ESCAPES = /* @__PURE__ */ new Set([
|
|
44
|
+
"b",
|
|
45
|
+
"f",
|
|
46
|
+
"n",
|
|
47
|
+
"r",
|
|
48
|
+
"t"
|
|
49
|
+
]);
|
|
50
|
+
function isControlCharacter(char) {
|
|
51
|
+
const codePoint = char.codePointAt(0);
|
|
52
|
+
return codePoint !== void 0 && codePoint >= 0 && codePoint <= 31;
|
|
53
|
+
}
|
|
54
|
+
function escapeControlCharacter(char) {
|
|
55
|
+
switch (char) {
|
|
56
|
+
case "\b": return "\\b";
|
|
57
|
+
case "\f": return "\\f";
|
|
58
|
+
case "\n": return "\\n";
|
|
59
|
+
case "\r": return "\\r";
|
|
60
|
+
case " ": return "\\t";
|
|
61
|
+
default: return `\\u${char.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000"}`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Repairs malformed JSON string literals by:
|
|
66
|
+
* - escaping raw control characters inside strings
|
|
67
|
+
* - doubling backslashes before invalid escape characters
|
|
68
|
+
*
|
|
69
|
+
* By default a valid control escape (`\n`, `\t`, ...) that follows a Windows-path-looking
|
|
70
|
+
* prefix is treated as an unescaped path separator and doubled. Pass
|
|
71
|
+
* `preserveValidControlEscapes` when the text is authoritative (for example a completed
|
|
72
|
+
* tool-call argument buffer) and every valid escape must survive as written.
|
|
73
|
+
*/
|
|
74
|
+
function repairJson(json, options) {
|
|
75
|
+
const preserveValidControlEscapes = options?.preserveValidControlEscapes === true;
|
|
76
|
+
let repaired = "";
|
|
77
|
+
let inString = false;
|
|
78
|
+
let stringValuePrefix = "";
|
|
79
|
+
for (let index = 0; index < json.length; index++) {
|
|
80
|
+
const char = json.charAt(index);
|
|
81
|
+
if (!inString) {
|
|
82
|
+
repaired += char;
|
|
83
|
+
if (char === "\"") {
|
|
84
|
+
inString = true;
|
|
85
|
+
stringValuePrefix = "";
|
|
86
|
+
}
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (char === "\"") {
|
|
90
|
+
repaired += char;
|
|
91
|
+
inString = false;
|
|
92
|
+
stringValuePrefix = "";
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (char === "\\") {
|
|
96
|
+
const nextChar = json.charAt(index + 1);
|
|
97
|
+
if (!nextChar) {
|
|
98
|
+
repaired += "\\\\";
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (nextChar === "u") {
|
|
102
|
+
const unicodeDigits = json.slice(index + 2, index + 6);
|
|
103
|
+
if (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) {
|
|
104
|
+
repaired += `\\u${unicodeDigits}`;
|
|
105
|
+
stringValuePrefix += `\\u${unicodeDigits}`;
|
|
106
|
+
index += 5;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
repaired += "\\\\";
|
|
110
|
+
stringValuePrefix += "\\";
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (!preserveValidControlEscapes && JSON_CONTROL_ESCAPES.has(nextChar) && looksLikeWindowsPathPrefix(stringValuePrefix)) {
|
|
114
|
+
repaired += "\\\\";
|
|
115
|
+
stringValuePrefix += "\\";
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (VALID_JSON_ESCAPES.has(nextChar)) {
|
|
119
|
+
repaired += `\\${nextChar}`;
|
|
120
|
+
stringValuePrefix += nextChar === "\\" ? "\\" : `\\${nextChar}`;
|
|
121
|
+
index += 1;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
repaired += "\\\\";
|
|
125
|
+
stringValuePrefix += "\\";
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
repaired += isControlCharacter(char) ? escapeControlCharacter(char) : char;
|
|
129
|
+
stringValuePrefix += char;
|
|
130
|
+
}
|
|
131
|
+
return repaired;
|
|
132
|
+
}
|
|
133
|
+
function parseJsonWithRepair(json) {
|
|
134
|
+
return JSON.parse(repairJson(json));
|
|
135
|
+
}
|
|
136
|
+
function looksLikeWindowsPathPrefix(prefix) {
|
|
137
|
+
const tail = prefix.slice(-160);
|
|
138
|
+
return /(?:^|[^A-Za-z0-9])[A-Za-z]:(?:[\\/][^"\\/:*?<>|\r\n]*)*$/.test(tail);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Attempts to parse potentially incomplete JSON during streaming.
|
|
142
|
+
* Always returns a valid object, even if the JSON is incomplete.
|
|
143
|
+
*
|
|
144
|
+
* @param partialJson The partial JSON string from streaming
|
|
145
|
+
* @returns Parsed object or empty object if parsing fails
|
|
146
|
+
*/
|
|
147
|
+
function parseStreamingJson(partialJson) {
|
|
148
|
+
if (!partialJson || partialJson.trim() === "") return {};
|
|
149
|
+
try {
|
|
150
|
+
return asNonArrayRecord(parseJsonWithRepair(partialJson));
|
|
151
|
+
} catch {
|
|
152
|
+
try {
|
|
153
|
+
return asNonArrayRecord(parse(partialJson));
|
|
154
|
+
} catch {
|
|
155
|
+
try {
|
|
156
|
+
return asNonArrayRecord(parse(repairJson(partialJson)));
|
|
157
|
+
} catch {
|
|
158
|
+
return {};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const TOOL_ARGUMENT_PREVIEW_FIRST_CHECKPOINT_CHARS = 512;
|
|
164
|
+
/**
|
|
165
|
+
* Streamed tool-call arguments are preview-only; the terminal parse re-reads
|
|
166
|
+
* the full buffer authoritatively at content_block_stop. Reparsing every delta
|
|
167
|
+
* scans an ever-growing buffer and makes assembly quadratic in the argument
|
|
168
|
+
* size, so refresh previews on a geometric length schedule instead — bounded
|
|
169
|
+
* staleness, linear total parse work.
|
|
170
|
+
*/
|
|
171
|
+
function createToolArgumentPreviewSchedule() {
|
|
172
|
+
let nextCheckpointChars = TOOL_ARGUMENT_PREVIEW_FIRST_CHECKPOINT_CHARS;
|
|
173
|
+
return (accumulatedChars) => {
|
|
174
|
+
if (accumulatedChars < nextCheckpointChars) return false;
|
|
175
|
+
nextCheckpointChars = accumulatedChars * 2;
|
|
176
|
+
return true;
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
//#endregion
|
|
15
180
|
//#region packages/ai/src/transports/json-unsafe-integers.ts
|
|
16
181
|
/**
|
|
17
182
|
* JSON parsing helpers that preserve integer literals larger than
|
|
@@ -123,15 +288,59 @@ function coerceTransportToolCallArguments(argumentsValue) {
|
|
|
123
288
|
} catch {}
|
|
124
289
|
return {};
|
|
125
290
|
}
|
|
126
|
-
/**
|
|
127
|
-
|
|
291
|
+
/** Stable terminal fact: presentation must not infer unfinished calls from provider prose. */
|
|
292
|
+
var IncompleteToolCallError = class extends Error {
|
|
293
|
+
constructor(..._args) {
|
|
294
|
+
super(..._args);
|
|
295
|
+
this.code = "incomplete_tool_call";
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
const MALFORMED_TOOL_CALL_TERMINAL_ERROR_CODE = "malformed_tool_call_arguments";
|
|
299
|
+
function createMalformedToolCallArgumentsError(value, errorMessage, repairAttempted) {
|
|
300
|
+
const text = typeof value === "string" ? value : void 0;
|
|
301
|
+
const diagnostics = {
|
|
302
|
+
code: MALFORMED_TOOL_CALL_TERMINAL_ERROR_CODE,
|
|
303
|
+
argumentChars: text?.length ?? 0,
|
|
304
|
+
argumentHash: text === void 0 ? "" : shortHash(text),
|
|
305
|
+
repairAttempted
|
|
306
|
+
};
|
|
307
|
+
const error = new Error(errorMessage, { cause: diagnostics });
|
|
308
|
+
Object.assign(error, {
|
|
309
|
+
errorCode: MALFORMED_TOOL_CALL_TERMINAL_ERROR_CODE,
|
|
310
|
+
errorBody: JSON.stringify(diagnostics)
|
|
311
|
+
});
|
|
312
|
+
return error;
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Repair a complete-but-invalid terminal argument buffer. Anthropic fine-grained tool
|
|
316
|
+
* streaming skips server-side JSON validation, so a finished tool_use block can carry raw
|
|
317
|
+
* control characters or invalid escapes inside string values. Only string-literal repairs
|
|
318
|
+
* are applied and every valid escape is preserved as written; truncated or non-object
|
|
319
|
+
* buffers stay rejected so a cut-off write never executes with partial arguments.
|
|
320
|
+
*/
|
|
321
|
+
function repairTerminalToolCallArguments(value) {
|
|
322
|
+
const repaired = repairJson(value, { preserveValidControlEscapes: true });
|
|
323
|
+
if (repaired === value) return null;
|
|
324
|
+
return parseJsonObjectPreservingUnsafeIntegers(repaired);
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Admit only complete object-shaped terminal tool arguments; partial parsing is preview-only.
|
|
328
|
+
* `repairStringLiterals` opts a stream whose provider may deliver unvalidated tool input into
|
|
329
|
+
* string-literal repair before rejection.
|
|
330
|
+
*/
|
|
331
|
+
function parseTerminalToolCallArguments(value, errorMessage = MALFORMED_TOOL_CALL_TERMINAL_ERROR_MESSAGE, options) {
|
|
128
332
|
const parsed = parseJsonObjectPreservingUnsafeIntegers(value);
|
|
129
|
-
if (
|
|
130
|
-
|
|
333
|
+
if (parsed) return parsed;
|
|
334
|
+
const repairStringLiterals = options?.repairStringLiterals === true && typeof value === "string";
|
|
335
|
+
if (repairStringLiterals) {
|
|
336
|
+
const repaired = repairTerminalToolCallArguments(value);
|
|
337
|
+
if (repaired) return repaired;
|
|
338
|
+
}
|
|
339
|
+
throw createMalformedToolCallArgumentsError(value, errorMessage, repairStringLiterals);
|
|
131
340
|
}
|
|
132
341
|
/** Validate a complete sibling set before mutating any call into executable state. */
|
|
133
|
-
function finalizeTerminalToolCallArguments(calls, readArguments, errorMessage) {
|
|
134
|
-
const validated = calls.map((call) => [call, parseTerminalToolCallArguments(readArguments(call), errorMessage)]);
|
|
342
|
+
function finalizeTerminalToolCallArguments(calls, readArguments, errorMessage, options) {
|
|
343
|
+
const validated = calls.map((call) => [call, parseTerminalToolCallArguments(readArguments(call), errorMessage, options)]);
|
|
135
344
|
for (const [call, argumentsValue] of validated) call.arguments = argumentsValue;
|
|
136
345
|
}
|
|
137
346
|
function mergeTransportHeaders(...headerSources) {
|
|
@@ -229,6 +438,7 @@ async function awaitProviderLifecycleCallback(callback, signal) {
|
|
|
229
438
|
if (signal?.aborted) throw transportAbortError(signal);
|
|
230
439
|
if (!callback) return;
|
|
231
440
|
const callbackPromise = Promise.resolve().then(callback);
|
|
441
|
+
getAiTransportHost().observePendingProviderWork?.(callbackPromise);
|
|
232
442
|
if (!signal) {
|
|
233
443
|
await callbackPromise;
|
|
234
444
|
return;
|
|
@@ -247,7 +457,9 @@ async function awaitProviderLifecycleCallback(callback, signal) {
|
|
|
247
457
|
function startProviderStreamCancellation(cancelStream, error) {
|
|
248
458
|
const reason = error instanceof Error ? error : new Error(String(error));
|
|
249
459
|
try {
|
|
250
|
-
Promise.resolve(cancelStream(reason))
|
|
460
|
+
const pending = Promise.resolve(cancelStream(reason));
|
|
461
|
+
pending.catch(() => void 0);
|
|
462
|
+
getAiTransportHost().observePendingProviderWork?.(pending);
|
|
251
463
|
} catch {}
|
|
252
464
|
}
|
|
253
465
|
async function awaitProviderLifecycleWithCleanup(params) {
|
|
@@ -352,4 +564,4 @@ function failTransportStream(params) {
|
|
|
352
564
|
stream.end();
|
|
353
565
|
}
|
|
354
566
|
//#endregion
|
|
355
|
-
export {
|
|
567
|
+
export { quoteUnsafeIntegerLiterals as C, repairJson as D, parseStreamingJson as E, headersToRecord as O, parseJsonPreservingUnsafeIntegers as S, parseJsonWithRepair as T, sanitizeTransportPayloadText as _, createEmptyTransportUsage as a, withProviderResponseHook as b, finalizeTerminalToolCallArguments as c, mergeTransportMetadata as d, notifyProviderHttpMetadata as f, sanitizeNonEmptyTransportPayloadText as g, parseTerminalToolCallArguments as h, copyProviderAcceptanceObserver as i, shortHash as k, finalizeTransportStream as l, notifyProviderStreamOpened as m, assignTransportErrorDetails as n, createWritableTransportEventStream as o, notifyProviderHttpResponse as p, coerceTransportToolCallArguments as r, failTransportStream as s, IncompleteToolCallError as t, mergeTransportHeaders as u, transportAbortError as v, createToolArgumentPreviewSchedule as w, parseJsonObjectPreservingUnsafeIntegers as x, withProviderAcceptanceObserver as y };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { n as getAiTransportHost } from "./host-B8YfDGd4.mjs";
|
|
2
|
+
import { t as truncateUtf16Safe } from "./utf16-slice-CvGodqok.mjs";
|
|
3
|
+
import "./provider-error-BA-v_tKd.mjs";
|
|
4
|
+
import "./internal/retry-after.mjs";
|
|
5
|
+
import "./positive-integer-41zhOdcV.mjs";
|
|
6
|
+
//#region packages/normalization-core/src/response-bytes.ts
|
|
7
|
+
async function consumeResponseBytes(options) {
|
|
8
|
+
let size = 0;
|
|
9
|
+
while (true) {
|
|
10
|
+
const { done, value } = await options.read();
|
|
11
|
+
if (done) return {
|
|
12
|
+
size,
|
|
13
|
+
truncated: false
|
|
14
|
+
};
|
|
15
|
+
if (options.skipEmptyChunks !== false && !value?.length) continue;
|
|
16
|
+
const remaining = options.maxBytes - size;
|
|
17
|
+
size += value.length;
|
|
18
|
+
if (size > options.maxBytes || options.stopAtLimit && size === options.maxBytes) {
|
|
19
|
+
if (remaining > 0) options.onChunk(value.subarray(0, remaining));
|
|
20
|
+
await options.onLimit(size);
|
|
21
|
+
return {
|
|
22
|
+
size,
|
|
23
|
+
truncated: true
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
options.onChunk(value);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region packages/ai/src/transports/transport-utils.ts
|
|
31
|
+
const MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE = "OpenClaw transport error: malformed_streaming_fragment";
|
|
32
|
+
const NON_LATIN_RE = /[\u2E80-\u9FFF\uA000-\uA4FF\uAC00-\uD7AF\uF900-\uFAFF\uFF01-\uFF60\uFFE0-\uFFE6\u{20000}-\u{2FA1F}]/gu;
|
|
33
|
+
const CJK_SURROGATE_HIGH_RE = /[\uD840-\uD87E][\uDC00-\uDFFF]/g;
|
|
34
|
+
function redactSensitiveText(text, _options) {
|
|
35
|
+
return getAiTransportHost().redactToolPayloadText(text);
|
|
36
|
+
}
|
|
37
|
+
function resolveModelHeaderSentinels(model) {
|
|
38
|
+
if (!model.headers) return model;
|
|
39
|
+
let headers;
|
|
40
|
+
for (const [name, value] of Object.entries(model.headers)) {
|
|
41
|
+
const resolved = getAiTransportHost().resolveSecretSentinel(value);
|
|
42
|
+
if (resolved !== value) {
|
|
43
|
+
headers ??= { ...model.headers };
|
|
44
|
+
headers[name] = resolved;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return headers ? {
|
|
48
|
+
...model,
|
|
49
|
+
headers
|
|
50
|
+
} : model;
|
|
51
|
+
}
|
|
52
|
+
function createAbortError(message, options) {
|
|
53
|
+
const error = new Error(message, options);
|
|
54
|
+
error.name = "AbortError";
|
|
55
|
+
return error;
|
|
56
|
+
}
|
|
57
|
+
function estimateStringChars(text) {
|
|
58
|
+
if (!text) return 0;
|
|
59
|
+
const nonLatinCount = (text.match(NON_LATIN_RE) ?? []).length;
|
|
60
|
+
return (nonLatinCount === 0 ? text.length : text.length - (text.match(CJK_SURROGATE_HIGH_RE) ?? []).length) + nonLatinCount * 3;
|
|
61
|
+
}
|
|
62
|
+
function supportsModelTools(model) {
|
|
63
|
+
return (model.compat && typeof model.compat === "object" ? model.compat : void 0)?.supportsTools !== false;
|
|
64
|
+
}
|
|
65
|
+
function isCodeModeModelVisibleToolName(name, visibleToolNames) {
|
|
66
|
+
return visibleToolNames.has(name);
|
|
67
|
+
}
|
|
68
|
+
async function readChunkWithIdleTimeout(reader, timeoutMs, onIdleTimeout) {
|
|
69
|
+
let timer;
|
|
70
|
+
try {
|
|
71
|
+
return await Promise.race([reader.read(), new Promise((_resolve, reject) => {
|
|
72
|
+
timer = setTimeout(() => reject(onIdleTimeout?.({ chunkTimeoutMs: timeoutMs }) ?? /* @__PURE__ */ new Error("Read timed out")), timeoutMs);
|
|
73
|
+
})]);
|
|
74
|
+
} finally {
|
|
75
|
+
if (timer) clearTimeout(timer);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async function readResponseTextSnippet(response, options) {
|
|
79
|
+
const maxBytes = options?.maxBytes ?? 8192;
|
|
80
|
+
const maxChars = options?.maxChars ?? 200;
|
|
81
|
+
const reader = response.body?.getReader();
|
|
82
|
+
if (!reader) return;
|
|
83
|
+
const chunks = [];
|
|
84
|
+
let bytes = 0;
|
|
85
|
+
let truncated = false;
|
|
86
|
+
try {
|
|
87
|
+
if (bytes < maxBytes) {
|
|
88
|
+
const result = await consumeResponseBytes({
|
|
89
|
+
maxBytes,
|
|
90
|
+
stopAtLimit: true,
|
|
91
|
+
read: () => options?.chunkTimeoutMs ? readChunkWithIdleTimeout(reader, options.chunkTimeoutMs, options.onIdleTimeout) : reader.read(),
|
|
92
|
+
onChunk: (chunk) => chunks.push(chunk),
|
|
93
|
+
onLimit: async () => {
|
|
94
|
+
await reader.cancel().catch(() => void 0);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
bytes = Math.min(result.size, maxBytes);
|
|
98
|
+
truncated = result.truncated;
|
|
99
|
+
}
|
|
100
|
+
} catch (error) {
|
|
101
|
+
await reader.cancel(error).catch(() => void 0);
|
|
102
|
+
throw error;
|
|
103
|
+
} finally {
|
|
104
|
+
reader.releaseLock();
|
|
105
|
+
}
|
|
106
|
+
const merged = new Uint8Array(bytes);
|
|
107
|
+
let offset = 0;
|
|
108
|
+
for (const chunk of chunks) {
|
|
109
|
+
merged.set(chunk, offset);
|
|
110
|
+
offset += chunk.length;
|
|
111
|
+
}
|
|
112
|
+
const collapsed = new TextDecoder().decode(merged).replace(/\s+/g, " ").trim();
|
|
113
|
+
if (!collapsed) return;
|
|
114
|
+
if (collapsed.length > maxChars) return `${truncateUtf16Safe(collapsed, maxChars)}…`;
|
|
115
|
+
return truncated ? `${collapsed}…` : collapsed;
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
export { readResponseTextSnippet as a, supportsModelTools as c, isCodeModeModelVisibleToolName as i, createAbortError as n, redactSensitiveText as o, estimateStringChars as r, resolveModelHeaderSentinels as s, MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE as t };
|