@causyne/agent 1.20.121 → 1.20.122
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 -3
- package/package.json +1 -1
- package/src/acp/agentCatalog.js +81 -26
- package/src/acp/agentCatalog.ts +73 -29
- package/src/acp/client.js +210 -53
- package/src/acp/client.ts +202 -52
- package/src/acp/peerProfiles.js +55 -22
- package/src/acp/peerProfiles.ts +51 -22
- package/src/acp/protocol.js +37 -8
- package/src/acp/protocol.ts +30 -8
- package/src/acp/server.js +123 -25
- package/src/acp/server.ts +124 -24
- package/src/agent/errorClassifier.js +6 -2
- package/src/agent/errorClassifier.ts +6 -2
- package/src/agentLoop.js +11 -5
- package/src/agentLoop.ts +11 -5
- package/src/approvalGrants.js +19 -7
- package/src/approvalGrants.ts +20 -7
- package/src/approvalPolicy.js +48 -15
- package/src/approvalPolicy.ts +46 -15
- package/src/autoUpdate.js +5 -2
- package/src/autoUpdate.ts +5 -2
- package/src/browser/causyneBrowser.js +3 -2
- package/src/browser/causyneBrowser.ts +3 -2
- package/src/browser/searchProviders.js +1 -1
- package/src/browser/searchProviders.ts +1 -1
- package/src/config.js +287 -250
- package/src/config.ts +342 -0
- package/src/configVault.js +84 -17
- package/src/configVault.ts +77 -17
- package/src/continuum/compactor.js +2 -1
- package/src/continuum/compactor.ts +2 -1
- package/src/continuum/sanitizer.js +10 -3
- package/src/continuum/sanitizer.ts +9 -3
- package/src/continuum/ui/continuumPickerView.js +3 -2
- package/src/continuum/ui/continuumPickerView.ts +3 -2
- package/src/cortex/vectorDb.js +26 -15
- package/src/cortex/vectorDb.ts +26 -16
- package/src/creative/liveBridge.js +7 -5
- package/src/creative/liveBridge.ts +7 -5
- package/src/creative/studioScripts.js +16 -5
- package/src/creative/studioScripts.ts +14 -5
- package/src/decisionPolicy.js +16 -4
- package/src/decisionPolicy.ts +14 -4
- package/src/documentEngine/antiSlopAuditor.js +10 -5
- package/src/documentEngine/antiSlopAuditor.ts +11 -5
- package/src/documentEngine/documentForge.js +47 -15
- package/src/documentEngine/documentForge.ts +43 -14
- package/src/engines/design.js +2 -1
- package/src/engines/design.ts +2 -1
- package/src/engines/film.js +4 -4
- package/src/engines/film.ts +2 -2
- package/src/engines/light.js +2 -1
- package/src/engines/light.ts +2 -1
- package/src/engines/registry.js +1 -1
- package/src/engines/registry.ts +1 -1
- package/src/engines/reverseHarness.js +4 -3
- package/src/engines/reverseHarness.ts +4 -3
- package/src/headlessCli.js +2 -1
- package/src/headlessCli.ts +2 -1
- package/src/historyPruner.js +3 -2
- package/src/historyPruner.ts +3 -2
- package/src/hooks.js +3 -0
- package/src/hooks.ts +3 -0
- package/src/implementationPlan.js +21 -11
- package/src/implementationPlan.ts +21 -11
- package/src/infra/atomicWriter.js +4 -1
- package/src/infra/atomicWriter.ts +4 -1
- package/src/launchIntent.js +1 -1
- package/src/launchIntent.ts +1 -1
- package/src/memory/scopedFacts.js +1 -1
- package/src/memory/scopedFacts.ts +1 -1
- package/src/memory/symbolFolder.js +1 -1
- package/src/memory/symbolFolder.ts +1 -1
- package/src/modelRouter.js +1 -1
- package/src/modelRouter.ts +1 -1
- package/src/observer/evidence.js +10 -4
- package/src/observer/evidence.ts +10 -4
- package/src/osKeychain.js +62 -8
- package/src/osKeychain.ts +50 -8
- package/src/perception.js +3 -2
- package/src/perception.ts +3 -2
- package/src/planCache.js +2 -2
- package/src/planCache.ts +2 -2
- package/src/pluginsFactory/pluginsFactory.js +19 -11
- package/src/pluginsFactory/pluginsFactory.ts +18 -11
- package/src/promptMentions.js +2 -2
- package/src/promptMentions.ts +2 -2
- package/src/providers/acp.js +1 -1
- package/src/providers/acp.ts +1 -1
- package/src/providers/anthropic.js +327 -401
- package/src/providers/anthropic.ts +386 -0
- package/src/providers/antigravity.js +10 -4
- package/src/providers/antigravity.ts +10 -4
- package/src/providers/base.js +221 -319
- package/src/providers/base.ts +340 -0
- package/src/providers/byokHttp.js +58 -15
- package/src/providers/byokHttp.ts +59 -16
- package/src/providers/byokStream.js +142 -51
- package/src/providers/byokStream.ts +146 -42
- package/src/providers/dashscope-byok.js +97 -89
- package/src/providers/dashscope-byok.ts +114 -0
- package/src/providers/deepseek.js +73 -72
- package/src/providers/deepseek.ts +99 -0
- package/src/providers/factory.js +35 -28
- package/src/providers/factory.ts +40 -0
- package/src/providers/gemini.js +227 -278
- package/src/providers/gemini.ts +261 -0
- package/src/providers/loopGuard.js +9 -5
- package/src/providers/loopGuard.ts +10 -5
- package/src/providers/moonshot.js +70 -72
- package/src/providers/moonshot.ts +93 -0
- package/src/providers/muse.js +82 -152
- package/src/providers/muse.ts +122 -0
- package/src/providers/ollama.js +114 -106
- package/src/providers/ollama.ts +135 -0
- package/src/providers/openai-compatible.js +113 -96
- package/src/providers/openai-compatible.ts +139 -0
- package/src/providers/openai.js +22 -15
- package/src/providers/openai.ts +30 -0
- package/src/providers/openrouter.js +136 -74
- package/src/providers/openrouter.ts +133 -72
- package/src/providers/pi.js +6 -0
- package/src/providers/pi.ts +6 -0
- package/src/providers/qwen-byok.js +96 -87
- package/src/providers/qwen-byok.ts +113 -0
- package/src/providers/toolContracts.js +40 -14
- package/src/providers/toolContracts.ts +35 -14
- package/src/providers/wireNormalizer.js +78 -11
- package/src/providers/wireNormalizer.ts +68 -12
- package/src/providers/xai.js +73 -72
- package/src/providers/xai.ts +97 -0
- package/src/reliability/assetEvidence.js +4 -2
- package/src/reliability/assetEvidence.ts +4 -2
- package/src/sandbox.js +489 -554
- package/src/sandbox.ts +552 -0
- package/src/sandboxPolicy.js +95 -16
- package/src/sandboxPolicy.ts +97 -16
- package/src/sessionJournal.js +8 -3
- package/src/sessionJournal.ts +9 -3
- package/src/skills/skillResourceSafety.js +19 -8
- package/src/skills/skillResourceSafety.ts +16 -7
- package/src/skillsManager.js +3 -3
- package/src/skillsManager.ts +3 -3
- package/src/smartToolsUse.js +28 -4
- package/src/smartToolsUse.ts +29 -7
- package/src/stallGuard.js +45 -22
- package/src/stallGuard.ts +46 -22
- package/src/subagentJournal.js +6 -4
- package/src/subagentJournal.ts +6 -4
- package/src/textDiff.js +6 -1
- package/src/textDiff.ts +6 -1
- package/src/timeMachine.js +7 -1
- package/src/timeMachine.ts +7 -1
- package/src/tokenTracker.js +43 -28
- package/src/tokenTracker.ts +44 -30
- package/src/toolPacks.js +3 -1
- package/src/toolPacks.ts +3 -1
- package/src/tools/archive.js +245 -35
- package/src/tools/archive.ts +244 -35
- package/src/tools/computerUse.js +7 -3
- package/src/tools/computerUse.ts +7 -3
- package/src/tools/creativeApps.js +13 -8
- package/src/tools/creativeApps.ts +22 -9
- package/src/tools/deferredMcpSearch.js +26 -14
- package/src/tools/deferredMcpSearch.ts +26 -14
- package/src/tools/desktopOpen.js +69 -10
- package/src/tools/desktopOpen.ts +70 -11
- package/src/tools/documentForge.js +167 -82
- package/src/tools/documentForge.ts +169 -84
- package/src/tools/fsEdit.js +101 -30
- package/src/tools/fsEdit.ts +105 -32
- package/src/tools/fsFind.js +8 -5
- package/src/tools/fsFind.ts +7 -4
- package/src/tools/fsRead.js +119 -13
- package/src/tools/fsRead.ts +124 -13
- package/src/tools/fsWrite.js +17 -5
- package/src/tools/fsWrite.ts +17 -7
- package/src/tools/generateMediaViaApi.js +82 -19
- package/src/tools/generateMediaViaApi.ts +80 -19
- package/src/tools/memoryRecall.js +62 -11
- package/src/tools/memoryRecall.ts +70 -13
- package/src/tools/memoryWrite.js +27 -14
- package/src/tools/memoryWrite.ts +30 -14
- package/src/tools/multiEdit.js +100 -30
- package/src/tools/multiEdit.ts +104 -32
- package/src/tools/nativeEngine.js +33 -18
- package/src/tools/nativeEngine.ts +31 -18
- package/src/tools/openSourceToolProvisioner.js +49 -14
- package/src/tools/openSourceToolProvisioner.ts +54 -15
- package/src/tools/osSandbox.js +54 -14
- package/src/tools/osSandbox.ts +48 -14
- package/src/tools/payloadSanitizer.js +40 -8
- package/src/tools/payloadSanitizer.ts +39 -8
- package/src/tools/peerAgent.js +96 -34
- package/src/tools/peerAgent.ts +114 -37
- package/src/tools/pluginsFactory.js +38 -6
- package/src/tools/pluginsFactory.ts +42 -6
- package/src/tools/readNativeSkill.js +10 -8
- package/src/tools/readNativeSkill.ts +10 -8
- package/src/tools/requestDecision.js +10 -3
- package/src/tools/requestDecision.ts +10 -3
- package/src/tools/resolveAutomator.js +91 -17
- package/src/tools/resolveAutomator.ts +102 -17
- package/src/tools/reverseEngineering.js +168 -41
- package/src/tools/reverseEngineering.ts +161 -41
- package/src/tools/sysRun.js +69 -29
- package/src/tools/sysRun.ts +66 -24
- package/src/tools/toolDispatch.js +24 -1
- package/src/tools/toolDispatch.ts +21 -1
- package/src/tools/toolOutputStore.js +62 -23
- package/src/tools/toolOutputStore.ts +56 -23
- package/src/tools/toolScanner.js +13 -10
- package/src/tools/toolScanner.ts +13 -10
- package/src/tools/toolSelfRepair.js +94 -28
- package/src/tools/toolSelfRepair.ts +96 -28
- package/src/tools/uiForge.js +71 -6
- package/src/tools/uiForge.ts +74 -6
- package/src/tools/viewImage.js +62 -17
- package/src/tools/viewImage.ts +57 -12
- package/src/tools/visionInspector.js +15 -3
- package/src/tools/visionInspector.ts +15 -3
- package/src/tools/walkerSafety.js +2 -0
- package/src/tools/walkerSafety.ts +1 -0
- package/src/tools/webFetch.js +105 -10
- package/src/tools/webFetch.ts +105 -11
- package/src/tui/banner.js +3 -2
- package/src/tui/banner.ts +3 -2
- package/src/tui/consoleGuard.js +12 -4
- package/src/tui/consoleGuard.ts +9 -4
- package/src/tui/messageInteraction.js +2 -3
- package/src/tui/messageInteraction.ts +2 -3
- package/src/tui/modelPicker.js +1 -0
- package/src/tui/modelPicker.ts +1 -0
- package/src/tui/overlay.js +3 -1
- package/src/tui/overlay.ts +3 -1
- package/src/tui/sessionPicker.js +3 -2
- package/src/tui/sessionPicker.ts +3 -2
- package/src/tui/sessionPickerView.js +7 -1
- package/src/tui/sessionPickerView.ts +6 -1
- package/src/tui/toolOutputNormalizer.js +2 -3
- package/src/tui/toolOutputNormalizer.ts +4 -3
- package/src/tui/viewport.js +4 -4
- package/src/tui/viewport.ts +5 -5
- package/src/tui/workspaceIdentity.js +2 -1
- package/src/tui/workspaceIdentity.ts +2 -1
- package/src/uncertainty.js +8 -3
- package/src/uncertainty.ts +8 -3
- package/src/utils/paths.js +8 -5
- package/src/utils/paths.ts +9 -7
- package/src/vfeTracker.js +9 -3
- package/src/vfeTracker.ts +9 -3
- package/src/config.d.ts +0 -2
- package/src/providers/base.d.ts +0 -94
- package/src/providers/factory.d.ts +0 -1
- package/src/sandbox.d.ts +0 -1
|
@@ -69,7 +69,11 @@ export class ProviderHttpError extends Error {
|
|
|
69
69
|
* Preserve explicit `0` temperature (unlike `options.temperature || 0.1`).
|
|
70
70
|
*/
|
|
71
71
|
export function resolveTemperature(value: unknown, fallback = 0.1): number {
|
|
72
|
-
|
|
72
|
+
const safeFallback = typeof fallback === 'number' && Number.isFinite(fallback)
|
|
73
|
+
? Math.min(2, Math.max(0, fallback))
|
|
74
|
+
: 0.1;
|
|
75
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return safeFallback;
|
|
76
|
+
return Math.min(2, Math.max(0, value));
|
|
73
77
|
}
|
|
74
78
|
|
|
75
79
|
/**
|
|
@@ -82,6 +86,9 @@ export function requireApiKey(apiKey: unknown, providerLabel: string): string {
|
|
|
82
86
|
`${providerLabel} API requires a valid API key (BYOK mode). Configure it with \`causyne config\`.`
|
|
83
87
|
);
|
|
84
88
|
}
|
|
89
|
+
if (/[\r\n\0]/.test(trimmed)) {
|
|
90
|
+
throw new Error(`${providerLabel} API key contains invalid control characters.`);
|
|
91
|
+
}
|
|
85
92
|
return trimmed;
|
|
86
93
|
}
|
|
87
94
|
|
|
@@ -97,7 +104,16 @@ export function isLoopbackHost(rawHostname: string): boolean {
|
|
|
97
104
|
.replace(/\]$/, '')
|
|
98
105
|
.replace(/\.$/, '');
|
|
99
106
|
if (!host) return false;
|
|
100
|
-
if (
|
|
107
|
+
if (
|
|
108
|
+
host === 'localhost'
|
|
109
|
+
|| host.endsWith('.localhost')
|
|
110
|
+
|| host === '::1'
|
|
111
|
+
|| host === '0:0:0:0:0:0:0:1'
|
|
112
|
+
|| /^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(host)
|
|
113
|
+
) return true;
|
|
114
|
+
if (host.startsWith('::ffff:127.')) {
|
|
115
|
+
return isLoopbackHost(host.slice(7));
|
|
116
|
+
}
|
|
101
117
|
if (host.startsWith('127.')) {
|
|
102
118
|
const octets = host.split('.');
|
|
103
119
|
return octets.length === 4 && octets.every((part) => {
|
|
@@ -123,6 +139,9 @@ export function validateProviderEndpointUrl(
|
|
|
123
139
|
if (!trimmed) {
|
|
124
140
|
throw new Error(`${label} endpoint URL is required.`);
|
|
125
141
|
}
|
|
142
|
+
if (/[\x00-\x1f\x7f]/.test(trimmed)) {
|
|
143
|
+
throw new Error(`${label} endpoint URL contains invalid control characters.`);
|
|
144
|
+
}
|
|
126
145
|
|
|
127
146
|
let parsed: URL;
|
|
128
147
|
try {
|
|
@@ -138,6 +157,12 @@ export function validateProviderEndpointUrl(
|
|
|
138
157
|
if (parsed.username || parsed.password) {
|
|
139
158
|
throw new Error(`${label} endpoint URL must not embed credentials.`);
|
|
140
159
|
}
|
|
160
|
+
for (const param of parsed.searchParams.keys()) {
|
|
161
|
+
const lowered = param.toLowerCase();
|
|
162
|
+
if (lowered === 'key' || lowered === 'api_key' || lowered === 'apikey' || lowered === 'access_token') {
|
|
163
|
+
throw new Error(`${label} endpoint URL must not embed API keys in query parameters.`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
141
166
|
|
|
142
167
|
if (
|
|
143
168
|
parsed.protocol === 'http:'
|
|
@@ -146,7 +171,7 @@ export function validateProviderEndpointUrl(
|
|
|
146
171
|
&& !isLoopbackHost(parsed.hostname)
|
|
147
172
|
) {
|
|
148
173
|
throw new Error(
|
|
149
|
-
`${label} refused to send an API key over unencrypted remote HTTP (${parsed.hostname}). Use https:// or set allowInsecureHttp: true for a trusted private network.`
|
|
174
|
+
`${label} refused to send an API key over unencrypted remote HTTP (${safeDisplay(parsed.hostname)}). Use https:// or set allowInsecureHttp: true for a trusted private network.`
|
|
150
175
|
);
|
|
151
176
|
}
|
|
152
177
|
|
|
@@ -161,10 +186,10 @@ export function parseRetryAfterMs(headerValue: string | null | undefined): numbe
|
|
|
161
186
|
const trimmed = headerValue.trim();
|
|
162
187
|
if (!trimmed) return undefined;
|
|
163
188
|
|
|
164
|
-
if (/^\d
|
|
189
|
+
if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
|
|
165
190
|
const seconds = Number(trimmed);
|
|
166
191
|
if (!Number.isFinite(seconds) || seconds < 0) return undefined;
|
|
167
|
-
return Math.min(seconds * 1000, 300_000);
|
|
192
|
+
return Math.min(Math.ceil(seconds * 1000), 300_000);
|
|
168
193
|
}
|
|
169
194
|
|
|
170
195
|
const parsedDate = Date.parse(trimmed);
|
|
@@ -201,7 +226,8 @@ export function redactProviderSecrets(
|
|
|
201
226
|
// Linear-time token masks (no nested quantifiers / zero ReDoS risk).
|
|
202
227
|
text = text.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{6,}/gi, 'Bearer [REDACTED]');
|
|
203
228
|
text = text.replace(/([?&](?:api_?)?key=)[^&\s"']+/gi, '$1[REDACTED]');
|
|
204
|
-
text = text.replace(/\b(?:
|
|
229
|
+
text = text.replace(/\b(x-(?:goog-)?api-key\s*[:=]\s*)[A-Za-z0-9._~+/=-]{6,}/gi, '$1[REDACTED]');
|
|
230
|
+
text = text.replace(/\b(?:sk-[A-Za-z0-9_-]{12,}|AIza[A-Za-z0-9_-]{20,}|xai-[A-Za-z0-9_-]{12,}|gsk_[A-Za-z0-9_-]{12,}|ya29\.[A-Za-z0-9._-]{16,})\b/g, '[REDACTED]');
|
|
205
231
|
|
|
206
232
|
if (text.length > MAX_PROVIDER_ERROR_CHARS) {
|
|
207
233
|
return `${text.slice(0, MAX_PROVIDER_ERROR_CHARS)}…`;
|
|
@@ -236,7 +262,10 @@ export async function readBoundedResponseText(
|
|
|
236
262
|
maxBytes: number,
|
|
237
263
|
options: { truncate?: boolean | undefined; label?: string | undefined } = {}
|
|
238
264
|
): Promise<string> {
|
|
239
|
-
|
|
265
|
+
if (!response) return '';
|
|
266
|
+
const limit = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 1
|
|
267
|
+
? Math.floor(maxBytes)
|
|
268
|
+
: MAX_PROVIDER_JSON_BYTES;
|
|
240
269
|
const declaredLen = getHeaderCaseInsensitive(response, 'content-length');
|
|
241
270
|
if (!options.truncate && declaredLen && /^\d+$/.test(declaredLen.trim())) {
|
|
242
271
|
const contentLength = Number(declaredLen.trim());
|
|
@@ -282,7 +311,7 @@ export async function readBoundedResponseText(
|
|
|
282
311
|
const text = await response.text();
|
|
283
312
|
const byteLen = Buffer.byteLength(text, 'utf8');
|
|
284
313
|
if (byteLen > limit) {
|
|
285
|
-
if (options.truncate) return text.
|
|
314
|
+
if (options.truncate) return Buffer.from(text, 'utf8').subarray(0, limit).toString('utf8');
|
|
286
315
|
throw new Error(
|
|
287
316
|
`${options.label || 'Provider'} response exceeded maximum allowed size (${limit} bytes).`
|
|
288
317
|
);
|
|
@@ -316,10 +345,8 @@ function isAbortLikeError(err: unknown): boolean {
|
|
|
316
345
|
export async function safeProviderFetch(
|
|
317
346
|
options: SafeProviderFetchOptions
|
|
318
347
|
): Promise<{ response: Response; cleanup: () => void }> {
|
|
319
|
-
const hasKey = options.hasApiKey ??
|
|
320
|
-
|
|
321
|
-
|| options.headers?.['x-api-key']
|
|
322
|
-
|| options.headers?.['x-goog-api-key']
|
|
348
|
+
const hasKey = options.hasApiKey ?? Object.entries(options.headers ?? {}).some(
|
|
349
|
+
([k, v]) => /^(?:authorization|x-api-key|x-goog-api-key)$/i.test(k) && Boolean(v)
|
|
323
350
|
);
|
|
324
351
|
|
|
325
352
|
const safeUrl = validateProviderEndpointUrl(options.url, {
|
|
@@ -362,7 +389,15 @@ export async function safeProviderFetch(
|
|
|
362
389
|
redirect: 'error',
|
|
363
390
|
signal: controller.signal
|
|
364
391
|
};
|
|
365
|
-
if (options.headers)
|
|
392
|
+
if (options.headers) {
|
|
393
|
+
for (const [headerName, headerVal] of Object.entries(options.headers)) {
|
|
394
|
+
if (/[\r\n\0]/.test(headerName) || (typeof headerVal === 'string' && /[\r\n\0]/.test(headerVal))) {
|
|
395
|
+
cleanup();
|
|
396
|
+
throw new Error(`${options.providerLabel} request header contains invalid control characters.`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
fetchInit.headers = options.headers;
|
|
400
|
+
}
|
|
366
401
|
if (options.body !== undefined) fetchInit.body = options.body;
|
|
367
402
|
|
|
368
403
|
try {
|
|
@@ -389,7 +424,9 @@ export async function safeProviderFetch(
|
|
|
389
424
|
);
|
|
390
425
|
}
|
|
391
426
|
const safeMsg = redactProviderSecrets(rawMsg, options.secrets);
|
|
392
|
-
|
|
427
|
+
const safeCause = causeMsg ? redactProviderSecrets(causeMsg, options.secrets) : '';
|
|
428
|
+
const detail = safeCause && !safeMsg.includes(safeCause) ? `${safeMsg} (${safeCause})` : safeMsg;
|
|
429
|
+
throw new Error(`${options.providerLabel} network error: ${detail}`);
|
|
393
430
|
}
|
|
394
431
|
}
|
|
395
432
|
|
|
@@ -431,7 +468,12 @@ export async function safeProviderFetchJson<T = Record<string, unknown>>(
|
|
|
431
468
|
|
|
432
469
|
// Minimal unit-test mocks may supply `.json()` without `.body` or `.text()`.
|
|
433
470
|
if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
|
|
434
|
-
|
|
471
|
+
try {
|
|
472
|
+
return (await response.json()) as T;
|
|
473
|
+
} catch (err: unknown) {
|
|
474
|
+
const safeErr = redactProviderSecrets(err instanceof Error ? err.message : String(err), options.secrets);
|
|
475
|
+
throw new Error(`${options.providerLabel} returned a non-JSON response (HTTP ${response.status}): ${safeErr}`);
|
|
476
|
+
}
|
|
435
477
|
}
|
|
436
478
|
|
|
437
479
|
const rawText = await readBoundedResponseText(
|
|
@@ -440,8 +482,9 @@ export async function safeProviderFetchJson<T = Record<string, unknown>>(
|
|
|
440
482
|
{ truncate: false, label: options.providerLabel }
|
|
441
483
|
);
|
|
442
484
|
|
|
485
|
+
const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
443
486
|
try {
|
|
444
|
-
return JSON.parse(
|
|
487
|
+
return JSON.parse(cleanText) as T;
|
|
445
488
|
} catch {
|
|
446
489
|
const preview = redactProviderSecrets(rawText.slice(0, 240), options.secrets);
|
|
447
490
|
throw new Error(
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* - Secret redaction, ANSI sanitization & `Retry-After` preservation
|
|
12
12
|
* - Graceful fallback when an upstream proxy returns non-streaming JSON
|
|
13
13
|
*/
|
|
14
|
+
import { safeParseJsonObject } from './wireNormalizer.js';
|
|
14
15
|
import { MAX_PROVIDER_ERROR_BYTES, MAX_PROVIDER_JSON_BYTES, MAX_SSE_BUFFER_BYTES, ProviderHttpError, parseRetryAfterMs, readBoundedResponseText, redactProviderSecrets, safeProviderFetch } from './byokHttp.js';
|
|
15
16
|
export function wantsStreaming(options) {
|
|
16
17
|
if (!options || typeof options !== 'object')
|
|
@@ -26,8 +27,8 @@ function getHeader(response, name) {
|
|
|
26
27
|
return '';
|
|
27
28
|
}
|
|
28
29
|
function isJsonContentType(contentType) {
|
|
29
|
-
const
|
|
30
|
-
return
|
|
30
|
+
const mediaType = (contentType.split(';')[0] ?? '').trim().toLowerCase();
|
|
31
|
+
return mediaType === 'application/json' || mediaType.endsWith('+json');
|
|
31
32
|
}
|
|
32
33
|
function isRecord(value) {
|
|
33
34
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
@@ -67,8 +68,9 @@ async function openHardenedStream(options) {
|
|
|
67
68
|
return { mode: 'json', data: isRecord(parsed) ? parsed : {} };
|
|
68
69
|
}
|
|
69
70
|
const rawText = await readBoundedResponseText(response, options.maxBytes ?? MAX_PROVIDER_JSON_BYTES, { truncate: false, label: options.providerLabel });
|
|
71
|
+
const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
70
72
|
try {
|
|
71
|
-
const parsed = JSON.parse(
|
|
73
|
+
const parsed = JSON.parse(cleanText);
|
|
72
74
|
return { mode: 'json', data: isRecord(parsed) ? parsed : {} };
|
|
73
75
|
}
|
|
74
76
|
catch {
|
|
@@ -82,26 +84,39 @@ async function openHardenedStream(options) {
|
|
|
82
84
|
}
|
|
83
85
|
return { mode: 'stream', response, cleanup };
|
|
84
86
|
}
|
|
85
|
-
async function consumeSseStream(response, providerLabel, maxBytes, onEvent) {
|
|
87
|
+
async function consumeSseStream(response, providerLabel, maxBytes, onEvent, signal) {
|
|
88
|
+
const safeMaxBytes = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 1
|
|
89
|
+
? Math.floor(maxBytes)
|
|
90
|
+
: MAX_PROVIDER_JSON_BYTES;
|
|
86
91
|
const reader = response.body.getReader();
|
|
87
92
|
const decoder = new TextDecoder('utf-8');
|
|
88
93
|
let buffer = '';
|
|
89
94
|
let totalBytes = 0;
|
|
90
95
|
let currentEvent = '';
|
|
91
96
|
let dataLines = [];
|
|
97
|
+
let sawFirstLine = false;
|
|
98
|
+
let eventBytes = 0;
|
|
92
99
|
const flushEvent = () => {
|
|
93
100
|
if (dataLines.length === 0) {
|
|
94
101
|
currentEvent = '';
|
|
102
|
+
eventBytes = 0;
|
|
95
103
|
return;
|
|
96
104
|
}
|
|
97
105
|
const payload = dataLines.join('\n');
|
|
98
106
|
const eventName = currentEvent || 'message';
|
|
99
107
|
currentEvent = '';
|
|
100
108
|
dataLines = [];
|
|
109
|
+
eventBytes = 0;
|
|
101
110
|
onEvent({ event: eventName, data: payload });
|
|
102
111
|
};
|
|
103
112
|
const processLine = (rawLine) => {
|
|
104
|
-
|
|
113
|
+
let stripped = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
|
|
114
|
+
if (!sawFirstLine) {
|
|
115
|
+
sawFirstLine = true;
|
|
116
|
+
if (stripped.charCodeAt(0) === 0xfeff)
|
|
117
|
+
stripped = stripped.slice(1);
|
|
118
|
+
}
|
|
119
|
+
const line = stripped;
|
|
105
120
|
if (line === '') {
|
|
106
121
|
flushEvent();
|
|
107
122
|
return;
|
|
@@ -109,25 +124,35 @@ async function consumeSseStream(response, providerLabel, maxBytes, onEvent) {
|
|
|
109
124
|
if (line.startsWith(':'))
|
|
110
125
|
return; // SSE comment / keep-alive
|
|
111
126
|
if (line.startsWith('event:')) {
|
|
112
|
-
|
|
127
|
+
const val = line.slice(6);
|
|
128
|
+
currentEvent = (val.startsWith(' ') ? val.slice(1) : val).trim();
|
|
113
129
|
return;
|
|
114
130
|
}
|
|
115
131
|
if (line.startsWith('data:')) {
|
|
116
132
|
const value = line.slice(5);
|
|
117
|
-
|
|
133
|
+
const entry = value.startsWith(' ') ? value.slice(1) : value;
|
|
134
|
+
eventBytes += Buffer.byteLength(entry, 'utf8') + 1;
|
|
135
|
+
if (eventBytes > MAX_SSE_BUFFER_BYTES) {
|
|
136
|
+
throw new Error(`${providerLabel} SSE event payload exceeded safety limit (${MAX_SSE_BUFFER_BYTES} bytes).`);
|
|
137
|
+
}
|
|
138
|
+
dataLines.push(entry);
|
|
118
139
|
}
|
|
119
140
|
};
|
|
120
141
|
try {
|
|
121
142
|
while (true) {
|
|
143
|
+
if (signal?.aborted) {
|
|
144
|
+
await reader.cancel().catch(() => { });
|
|
145
|
+
throw signal.reason ?? new DOMException('Aborted', 'AbortError');
|
|
146
|
+
}
|
|
122
147
|
const { done, value } = await reader.read();
|
|
123
148
|
if (done)
|
|
124
149
|
break;
|
|
125
150
|
if (!value)
|
|
126
151
|
continue;
|
|
127
152
|
totalBytes += value.byteLength;
|
|
128
|
-
if (totalBytes >
|
|
153
|
+
if (totalBytes > safeMaxBytes) {
|
|
129
154
|
await reader.cancel().catch(() => { });
|
|
130
|
-
throw new Error(`${providerLabel} stream exceeded maximum allowed size (${
|
|
155
|
+
throw new Error(`${providerLabel} stream exceeded maximum allowed size (${safeMaxBytes} bytes).`);
|
|
131
156
|
}
|
|
132
157
|
buffer += decoder.decode(value, { stream: true });
|
|
133
158
|
if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
|
|
@@ -154,13 +179,17 @@ async function consumeSseStream(response, providerLabel, maxBytes, onEvent) {
|
|
|
154
179
|
reader.releaseLock();
|
|
155
180
|
}
|
|
156
181
|
}
|
|
157
|
-
async function consumeNdjsonStream(response, providerLabel, maxBytes, onObject) {
|
|
182
|
+
async function consumeNdjsonStream(response, providerLabel, maxBytes, onObject, signal) {
|
|
183
|
+
const safeMaxBytes = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 1
|
|
184
|
+
? Math.floor(maxBytes)
|
|
185
|
+
: MAX_PROVIDER_JSON_BYTES;
|
|
158
186
|
const reader = response.body.getReader();
|
|
159
187
|
const decoder = new TextDecoder('utf-8');
|
|
160
188
|
let buffer = '';
|
|
161
189
|
let totalBytes = 0;
|
|
162
190
|
const processLine = (rawLine) => {
|
|
163
|
-
const
|
|
191
|
+
const stripped = rawLine.charCodeAt(0) === 0xfeff ? rawLine.slice(1) : rawLine;
|
|
192
|
+
const trimmed = stripped.trim();
|
|
164
193
|
if (!trimmed)
|
|
165
194
|
return;
|
|
166
195
|
try {
|
|
@@ -174,15 +203,19 @@ async function consumeNdjsonStream(response, providerLabel, maxBytes, onObject)
|
|
|
174
203
|
};
|
|
175
204
|
try {
|
|
176
205
|
while (true) {
|
|
206
|
+
if (signal?.aborted) {
|
|
207
|
+
await reader.cancel().catch(() => { });
|
|
208
|
+
throw signal.reason ?? new DOMException('Aborted', 'AbortError');
|
|
209
|
+
}
|
|
177
210
|
const { done, value } = await reader.read();
|
|
178
211
|
if (done)
|
|
179
212
|
break;
|
|
180
213
|
if (!value)
|
|
181
214
|
continue;
|
|
182
215
|
totalBytes += value.byteLength;
|
|
183
|
-
if (totalBytes >
|
|
216
|
+
if (totalBytes > safeMaxBytes) {
|
|
184
217
|
await reader.cancel().catch(() => { });
|
|
185
|
-
throw new Error(`${providerLabel} stream exceeded maximum allowed size (${
|
|
218
|
+
throw new Error(`${providerLabel} stream exceeded maximum allowed size (${safeMaxBytes} bytes).`);
|
|
186
219
|
}
|
|
187
220
|
buffer += decoder.decode(value, { stream: true });
|
|
188
221
|
if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
|
|
@@ -226,6 +259,10 @@ export async function streamOpenAICompatibleChat(options) {
|
|
|
226
259
|
body: JSON.stringify(streamPayload)
|
|
227
260
|
});
|
|
228
261
|
if (opened.mode === 'json') {
|
|
262
|
+
if (isRecord(opened.data.error)) {
|
|
263
|
+
const msg = redactProviderSecrets(typeof opened.data.error.message === 'string' ? opened.data.error.message : JSON.stringify(opened.data.error), options.secrets);
|
|
264
|
+
throw new Error(`${options.providerLabel} stream error: ${msg}`);
|
|
265
|
+
}
|
|
229
266
|
const choices = Array.isArray(opened.data.choices) ? opened.data.choices : [];
|
|
230
267
|
const first = isRecord(choices[0]) ? choices[0] : null;
|
|
231
268
|
const message = first && isRecord(first.message) ? first.message : null;
|
|
@@ -287,12 +324,38 @@ export async function streamOpenAICompatibleChat(options) {
|
|
|
287
324
|
content += delta.content;
|
|
288
325
|
options.onChunk?.(delta.content);
|
|
289
326
|
}
|
|
327
|
+
else if (Array.isArray(delta.content)) {
|
|
328
|
+
for (const part of delta.content) {
|
|
329
|
+
if (isRecord(part) && typeof part.text === 'string' && part.text.length > 0) {
|
|
330
|
+
content += part.text;
|
|
331
|
+
options.onChunk?.(part.text);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
290
335
|
if (Array.isArray(delta.tool_calls)) {
|
|
291
336
|
for (let pos = 0; pos < delta.tool_calls.length; pos++) {
|
|
292
337
|
const tc = delta.tool_calls[pos];
|
|
293
338
|
if (!isRecord(tc))
|
|
294
339
|
continue;
|
|
295
|
-
|
|
340
|
+
let idx;
|
|
341
|
+
if (typeof tc.index === 'number' && Number.isInteger(tc.index) && tc.index >= 0) {
|
|
342
|
+
idx = tc.index;
|
|
343
|
+
}
|
|
344
|
+
else if (typeof tc.id === 'string' && tc.id) {
|
|
345
|
+
const match = [...toolCallMap.entries()].find(([, item]) => item.id === tc.id);
|
|
346
|
+
if (match) {
|
|
347
|
+
idx = match[0];
|
|
348
|
+
}
|
|
349
|
+
else if (toolCallMap.get(pos)?.id && toolCallMap.get(pos)?.id !== tc.id) {
|
|
350
|
+
idx = Math.max(-1, ...toolCallMap.keys()) + 1;
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
idx = pos;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
idx = pos;
|
|
358
|
+
}
|
|
296
359
|
let entry = toolCallMap.get(idx);
|
|
297
360
|
if (!entry) {
|
|
298
361
|
entry = { id: '', type: 'function', function: { name: '', arguments: '' } };
|
|
@@ -310,7 +373,7 @@ export async function streamOpenAICompatibleChat(options) {
|
|
|
310
373
|
}
|
|
311
374
|
}
|
|
312
375
|
}
|
|
313
|
-
});
|
|
376
|
+
}, options.signal);
|
|
314
377
|
}
|
|
315
378
|
finally {
|
|
316
379
|
opened.cleanup();
|
|
@@ -350,6 +413,11 @@ export async function streamAnthropicMessages(options) {
|
|
|
350
413
|
body: JSON.stringify(streamPayload)
|
|
351
414
|
});
|
|
352
415
|
if (opened.mode === 'json') {
|
|
416
|
+
if (opened.data.type === 'error' || isRecord(opened.data.error)) {
|
|
417
|
+
const errObj = isRecord(opened.data.error) ? opened.data.error : opened.data;
|
|
418
|
+
const msg = redactProviderSecrets(typeof errObj.message === 'string' ? errObj.message : JSON.stringify(errObj), options.secrets);
|
|
419
|
+
throw new Error(`${options.providerLabel} stream error: ${msg}`);
|
|
420
|
+
}
|
|
353
421
|
const blocks = Array.isArray(opened.data.content) ? opened.data.content : [];
|
|
354
422
|
for (const block of blocks) {
|
|
355
423
|
if (!isRecord(block))
|
|
@@ -370,6 +438,17 @@ export async function streamAnthropicMessages(options) {
|
|
|
370
438
|
cache_read_input_tokens: 0,
|
|
371
439
|
cache_creation_input_tokens: 0
|
|
372
440
|
};
|
|
441
|
+
let stopReason;
|
|
442
|
+
const applyUsage = (u) => {
|
|
443
|
+
if (typeof u.input_tokens === 'number' && Number.isFinite(u.input_tokens) && u.input_tokens >= 0)
|
|
444
|
+
usage.input_tokens = u.input_tokens;
|
|
445
|
+
if (typeof u.output_tokens === 'number' && Number.isFinite(u.output_tokens) && u.output_tokens >= 0)
|
|
446
|
+
usage.output_tokens = u.output_tokens;
|
|
447
|
+
if (typeof u.cache_read_input_tokens === 'number' && Number.isFinite(u.cache_read_input_tokens) && u.cache_read_input_tokens >= 0)
|
|
448
|
+
usage.cache_read_input_tokens = u.cache_read_input_tokens;
|
|
449
|
+
if (typeof u.cache_creation_input_tokens === 'number' && Number.isFinite(u.cache_creation_input_tokens) && u.cache_creation_input_tokens >= 0)
|
|
450
|
+
usage.cache_creation_input_tokens = u.cache_creation_input_tokens;
|
|
451
|
+
};
|
|
373
452
|
try {
|
|
374
453
|
await consumeSseStream(opened.response, options.providerLabel, options.maxBytes ?? MAX_PROVIDER_JSON_BYTES, ({ data }) => {
|
|
375
454
|
const trimmed = data.trim();
|
|
@@ -391,30 +470,19 @@ export async function streamAnthropicMessages(options) {
|
|
|
391
470
|
throw new Error(`${options.providerLabel} stream error: ${msg}`);
|
|
392
471
|
}
|
|
393
472
|
if (eventType === 'message_start' && isRecord(parsed.message) && isRecord(parsed.message.usage)) {
|
|
394
|
-
|
|
395
|
-
if (typeof u.input_tokens === 'number')
|
|
396
|
-
usage.input_tokens = u.input_tokens;
|
|
397
|
-
if (typeof u.output_tokens === 'number')
|
|
398
|
-
usage.output_tokens = u.output_tokens;
|
|
399
|
-
if (typeof u.cache_read_input_tokens === 'number')
|
|
400
|
-
usage.cache_read_input_tokens = u.cache_read_input_tokens;
|
|
401
|
-
if (typeof u.cache_creation_input_tokens === 'number')
|
|
402
|
-
usage.cache_creation_input_tokens = u.cache_creation_input_tokens;
|
|
473
|
+
applyUsage(parsed.message.usage);
|
|
403
474
|
return;
|
|
404
475
|
}
|
|
405
|
-
if (eventType === 'message_delta'
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
if (
|
|
410
|
-
usage
|
|
411
|
-
|
|
412
|
-
usage.cache_read_input_tokens = u.cache_read_input_tokens;
|
|
413
|
-
if (typeof u.cache_creation_input_tokens === 'number')
|
|
414
|
-
usage.cache_creation_input_tokens = u.cache_creation_input_tokens;
|
|
476
|
+
if (eventType === 'message_delta') {
|
|
477
|
+
if (isRecord(parsed.delta) && typeof parsed.delta.stop_reason === 'string') {
|
|
478
|
+
stopReason = parsed.delta.stop_reason;
|
|
479
|
+
}
|
|
480
|
+
if (isRecord(parsed.usage)) {
|
|
481
|
+
applyUsage(parsed.usage);
|
|
482
|
+
}
|
|
415
483
|
return;
|
|
416
484
|
}
|
|
417
|
-
if (eventType === 'content_block_start' && typeof parsed.index === 'number' && isRecord(parsed.content_block)) {
|
|
485
|
+
if (eventType === 'content_block_start' && typeof parsed.index === 'number' && Number.isInteger(parsed.index) && parsed.index >= 0 && isRecord(parsed.content_block)) {
|
|
418
486
|
const initial = { ...parsed.content_block };
|
|
419
487
|
if (initial.type === 'text' && typeof initial.text === 'string' && initial.text) {
|
|
420
488
|
options.onChunk?.(initial.text);
|
|
@@ -448,7 +516,7 @@ export async function streamAnthropicMessages(options) {
|
|
|
448
516
|
acc.partialJson += delta.partial_json;
|
|
449
517
|
}
|
|
450
518
|
}
|
|
451
|
-
});
|
|
519
|
+
}, options.signal);
|
|
452
520
|
}
|
|
453
521
|
finally {
|
|
454
522
|
opened.cleanup();
|
|
@@ -457,19 +525,14 @@ export async function streamAnthropicMessages(options) {
|
|
|
457
525
|
.sort((a, b) => a[0] - b[0])
|
|
458
526
|
.map(([, acc]) => {
|
|
459
527
|
if (acc.block.type === 'tool_use' && acc.partialJson.trim().length > 0) {
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
acc.block.input = parsedInput;
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
catch {
|
|
467
|
-
// Keep existing input object if partial JSON could not be parsed
|
|
528
|
+
const recovered = safeParseJsonObject(acc.partialJson);
|
|
529
|
+
if (Object.keys(recovered).length > 0) {
|
|
530
|
+
acc.block.input = recovered;
|
|
468
531
|
}
|
|
469
532
|
}
|
|
470
533
|
return acc.block;
|
|
471
534
|
});
|
|
472
|
-
return { content: contentBlocks, usage };
|
|
535
|
+
return { content: contentBlocks, usage, ...(stopReason ? { stop_reason: stopReason } : {}) };
|
|
473
536
|
}
|
|
474
537
|
/**
|
|
475
538
|
* Converts a Gemini `:generateContent` endpoint URL to `:streamGenerateContent?alt=sse`
|
|
@@ -477,6 +540,7 @@ export async function streamAnthropicMessages(options) {
|
|
|
477
540
|
*/
|
|
478
541
|
export function buildGeminiStreamUrl(generateContentUrl) {
|
|
479
542
|
const parsed = new URL(generateContentUrl);
|
|
543
|
+
parsed.searchParams.delete('key');
|
|
480
544
|
if (parsed.pathname.endsWith(':generateContent')) {
|
|
481
545
|
parsed.pathname = `${parsed.pathname.slice(0, -':generateContent'.length)}:streamGenerateContent`;
|
|
482
546
|
}
|
|
@@ -500,6 +564,10 @@ export async function streamGeminiGenerateContent(options) {
|
|
|
500
564
|
body: JSON.stringify(options.payload)
|
|
501
565
|
});
|
|
502
566
|
if (opened.mode === 'json') {
|
|
567
|
+
if (isRecord(opened.data.error)) {
|
|
568
|
+
const msg = redactProviderSecrets(typeof opened.data.error.message === 'string' ? opened.data.error.message : JSON.stringify(opened.data.error), options.secrets);
|
|
569
|
+
throw new Error(`${options.providerLabel} stream error: ${msg}`);
|
|
570
|
+
}
|
|
503
571
|
const candidates = Array.isArray(opened.data.candidates) ? opened.data.candidates : [];
|
|
504
572
|
const first = isRecord(candidates[0]) ? candidates[0] : null;
|
|
505
573
|
const content = first && isRecord(first.content) ? first.content : null;
|
|
@@ -522,6 +590,8 @@ export async function streamGeminiGenerateContent(options) {
|
|
|
522
590
|
let reasoningContent = '';
|
|
523
591
|
const functionCallParts = [];
|
|
524
592
|
let usageMetadata;
|
|
593
|
+
let promptFeedback;
|
|
594
|
+
let finishReason;
|
|
525
595
|
let sawCandidate = false;
|
|
526
596
|
try {
|
|
527
597
|
await consumeSseStream(opened.response, options.providerLabel, options.maxBytes ?? MAX_PROVIDER_JSON_BYTES, ({ data }) => {
|
|
@@ -544,11 +614,16 @@ export async function streamGeminiGenerateContent(options) {
|
|
|
544
614
|
if (isRecord(parsed.usageMetadata)) {
|
|
545
615
|
usageMetadata = parsed.usageMetadata;
|
|
546
616
|
}
|
|
617
|
+
if (isRecord(parsed.promptFeedback)) {
|
|
618
|
+
promptFeedback = parsed.promptFeedback;
|
|
619
|
+
}
|
|
547
620
|
const candidates = Array.isArray(parsed.candidates) ? parsed.candidates : [];
|
|
548
621
|
const first = isRecord(candidates[0]) ? candidates[0] : null;
|
|
549
622
|
if (!first)
|
|
550
623
|
return;
|
|
551
624
|
sawCandidate = true;
|
|
625
|
+
if (typeof first.finishReason === 'string')
|
|
626
|
+
finishReason = first.finishReason;
|
|
552
627
|
const content = isRecord(first.content) ? first.content : null;
|
|
553
628
|
const parts = content && Array.isArray(content.parts) ? content.parts : [];
|
|
554
629
|
for (const part of parts) {
|
|
@@ -565,10 +640,14 @@ export async function streamGeminiGenerateContent(options) {
|
|
|
565
640
|
}
|
|
566
641
|
}
|
|
567
642
|
else if (isRecord(part.functionCall)) {
|
|
568
|
-
|
|
643
|
+
const fcPart = { functionCall: part.functionCall };
|
|
644
|
+
const sig = typeof part.thoughtSignature === 'string' ? part.thoughtSignature : (typeof part.thought_signature === 'string' ? part.thought_signature : undefined);
|
|
645
|
+
if (sig)
|
|
646
|
+
fcPart.thoughtSignature = sig;
|
|
647
|
+
functionCallParts.push(fcPart);
|
|
569
648
|
}
|
|
570
649
|
}
|
|
571
|
-
});
|
|
650
|
+
}, options.signal);
|
|
572
651
|
}
|
|
573
652
|
finally {
|
|
574
653
|
opened.cleanup();
|
|
@@ -578,8 +657,9 @@ export async function streamGeminiGenerateContent(options) {
|
|
|
578
657
|
finalParts.push({ text: textContent });
|
|
579
658
|
finalParts.push(...functionCallParts);
|
|
580
659
|
return {
|
|
581
|
-
candidates: sawCandidate ? [{ content: { role: 'model', parts: finalParts } }] : [],
|
|
660
|
+
candidates: sawCandidate ? [{ content: { role: 'model', parts: finalParts }, ...(finishReason ? { finishReason } : {}) }] : [],
|
|
582
661
|
...(usageMetadata ? { usageMetadata } : {}),
|
|
662
|
+
...(promptFeedback ? { promptFeedback } : {}),
|
|
583
663
|
...(reasoningContent ? { reasoningContent } : {})
|
|
584
664
|
};
|
|
585
665
|
}
|
|
@@ -602,6 +682,13 @@ export async function streamOllamaChat(options) {
|
|
|
602
682
|
body: JSON.stringify(streamPayload)
|
|
603
683
|
});
|
|
604
684
|
if (opened.mode === 'json') {
|
|
685
|
+
if (typeof opened.data.error === 'string' && opened.data.error) {
|
|
686
|
+
throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(opened.data.error, options.secrets)}`);
|
|
687
|
+
}
|
|
688
|
+
if (isRecord(opened.data.error)) {
|
|
689
|
+
const errMsg = typeof opened.data.error.message === 'string' ? opened.data.error.message : JSON.stringify(opened.data.error);
|
|
690
|
+
throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(errMsg, options.secrets)}`);
|
|
691
|
+
}
|
|
605
692
|
const msg = isRecord(opened.data.message) ? opened.data.message : null;
|
|
606
693
|
if (msg) {
|
|
607
694
|
if (typeof msg.thinking === 'string' && msg.thinking)
|
|
@@ -621,6 +708,10 @@ export async function streamOllamaChat(options) {
|
|
|
621
708
|
if (typeof chunk.error === 'string' && chunk.error) {
|
|
622
709
|
throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(chunk.error, options.secrets)}`);
|
|
623
710
|
}
|
|
711
|
+
if (isRecord(chunk.error)) {
|
|
712
|
+
const errMsg = typeof chunk.error.message === 'string' ? chunk.error.message : JSON.stringify(chunk.error);
|
|
713
|
+
throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(errMsg, options.secrets)}`);
|
|
714
|
+
}
|
|
624
715
|
const msg = isRecord(chunk.message) ? chunk.message : null;
|
|
625
716
|
if (msg) {
|
|
626
717
|
if (typeof msg.thinking === 'string' && msg.thinking.length > 0) {
|
|
@@ -635,11 +726,11 @@ export async function streamOllamaChat(options) {
|
|
|
635
726
|
toolCalls.push(...msg.tool_calls);
|
|
636
727
|
}
|
|
637
728
|
}
|
|
638
|
-
if (typeof chunk.prompt_eval_count === 'number')
|
|
729
|
+
if (typeof chunk.prompt_eval_count === 'number' && Number.isFinite(chunk.prompt_eval_count) && chunk.prompt_eval_count >= 0)
|
|
639
730
|
promptEvalCount = chunk.prompt_eval_count;
|
|
640
|
-
if (typeof chunk.eval_count === 'number')
|
|
731
|
+
if (typeof chunk.eval_count === 'number' && Number.isFinite(chunk.eval_count) && chunk.eval_count >= 0)
|
|
641
732
|
evalCount = chunk.eval_count;
|
|
642
|
-
});
|
|
733
|
+
}, options.signal);
|
|
643
734
|
}
|
|
644
735
|
finally {
|
|
645
736
|
opened.cleanup();
|