@causyne/agent 1.20.118 → 1.20.121
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/package.json +1 -1
- package/src/agent/errorClassifier.js +113 -0
- package/src/agent/errorClassifier.ts +161 -0
- package/src/agent/promptIntent.js +200 -0
- package/src/agent/promptIntent.ts +203 -0
- package/src/agent/toolArgValidator.js +97 -0
- package/src/agent/toolArgValidator.ts +112 -0
- package/src/agentLoop.js +51 -351
- package/src/agentLoop.ts +69 -363
- package/src/autoUpdate.js +111 -8
- package/src/autoUpdate.ts +144 -8
- package/src/browser/causyneBrowser.js +231 -136
- package/src/browser/causyneBrowser.ts +229 -140
- package/src/browser/searchProviders.js +41 -30
- package/src/browser/searchProviders.ts +24 -14
- package/src/browser/workspacePathSafety.js +50 -0
- package/src/browser/workspacePathSafety.ts +50 -0
- package/src/browser/workspacePreview.js +27 -4
- package/src/browser/workspacePreview.ts +28 -4
- package/src/cliMode.js +17 -3
- package/src/commands.js +15 -22
- package/src/config.js +42 -63
- package/src/configVault.js +204 -0
- package/src/configVault.ts +213 -0
- package/src/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- package/src/creative/liveBridge.js +34 -1
- package/src/creative/liveBridge.ts +28 -1
- package/src/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- package/src/entrypoint.js +77 -4
- package/src/headlessCli.js +304 -0
- package/src/headlessCli.ts +380 -0
- package/src/mcp/mcpClient.js +38 -11
- package/src/mcp/mcpClient.ts +44 -11
- package/src/mcp/mcpRegistry.js +2 -5
- package/src/mcp/mcpRegistry.ts +2 -5
- package/src/mcp/mcpSecurity.js +189 -0
- package/src/mcp/mcpSecurity.ts +190 -0
- package/src/observer/evidence.js +23 -0
- package/src/observer/evidence.ts +21 -0
- package/src/osKeychain.js +209 -0
- package/src/osKeychain.ts +245 -0
- package/src/providers/anthropic.js +61 -28
- package/src/providers/base.js +14 -0
- package/src/providers/byokHttp.js +354 -0
- package/src/providers/byokHttp.ts +454 -0
- package/src/providers/byokStream.js +657 -0
- package/src/providers/byokStream.ts +759 -0
- package/src/providers/dashscope-byok.js +47 -32
- package/src/providers/deepseek.js +43 -39
- package/src/providers/gemini.js +73 -38
- package/src/providers/moonshot.js +43 -33
- package/src/providers/muse.js +10 -10
- package/src/providers/ollama.js +46 -31
- package/src/providers/openai-compatible.js +57 -32
- package/src/providers/openrouter.js +77 -113
- package/src/providers/openrouter.ts +99 -118
- package/src/providers/qwen-byok.js +46 -23
- package/src/providers/toolContracts.js +9 -3
- package/src/providers/toolContracts.ts +9 -3
- package/src/providers/wireNormalizer.js +238 -0
- package/src/providers/wireNormalizer.ts +279 -0
- package/src/providers/xai.js +43 -33
- package/src/sandbox.js +77 -56
- package/src/sandboxPolicy.js +1208 -0
- package/src/sandboxPolicy.ts +1300 -0
- package/src/sessionJournal.js +47 -0
- package/src/sessionJournal.ts +49 -0
- package/src/tools/browserAutomator.js +13 -1
- package/src/tools/browserAutomator.ts +13 -0
- package/src/tools/creativeApps.js +2 -1
- package/src/tools/creativeApps.ts +2 -1
- package/src/tools/gameAssetFetcher.js +130 -26
- package/src/tools/gameAssetHarvester.js +80 -58
- package/src/tools/nativeEngine.js +1 -1
- package/src/tools/nativeEngine.ts +1 -1
- package/src/tools/osSandbox.js +473 -0
- package/src/tools/osSandbox.ts +554 -0
- package/src/tools/persistentShell.js +8 -3
- package/src/tools/registry.js +13 -0
- package/src/tools/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +39 -6
- package/src/tools/sysRun.ts +53 -7
- package/src/tools/toolScanner.js +596 -140
- package/src/tools/toolScanner.ts +665 -147
- package/src/tools/toolSelfRepair.js +243 -114
- package/src/tools/toolSelfRepair.ts +262 -111
- package/src/tools/webFetch.js +161 -24
- package/src/tools/webFetch.ts +157 -22
- package/src/tools/webSearch.js +33 -4
- package/src/tools/webSearch.ts +27 -4
- package/src/tui/sessionPicker.js +132 -35
- package/src/tui/sessionPicker.ts +153 -32
- package/src/tui/sessionPickerView.js +277 -34
- package/src/tui/sessionPickerView.ts +328 -34
- package/src/tui/statusLine.js +3 -0
- package/src/tui/statusLine.ts +5 -0
- package/src/tui/workspaceIdentity.js +133 -0
- package/src/tui/workspaceIdentity.ts +146 -0
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
// Hardened HTTP transport guard for all BYOK & cloud LLM providers.
|
|
2
|
+
// Enforces:
|
|
3
|
+
// - Endpoint URL & protocol validation (blocks cleartext remote API key leakage)
|
|
4
|
+
// - Zero redirect credential exfiltration (`redirect: 'error'`)
|
|
5
|
+
// - Cooperative AbortSignal cancellation + bounded request timeouts
|
|
6
|
+
// - Bounded response & error body streaming (prevents OOM from hostile endpoints)
|
|
7
|
+
// - Secret redaction & ANSI sanitization in error diagnostics
|
|
8
|
+
// - Structured HTTP status & Retry-After metadata preservation
|
|
9
|
+
// Authored in Strict TypeScript. Source-available under BUSL-1.1.
|
|
10
|
+
import { safeDisplay } from '../tui/text.js';
|
|
11
|
+
export const DEFAULT_PROVIDER_TIMEOUT_MS = 180_000;
|
|
12
|
+
export const MIN_PROVIDER_TIMEOUT_MS = 1_000;
|
|
13
|
+
export const MAX_PROVIDER_TIMEOUT_MS = 600_000;
|
|
14
|
+
export const MAX_PROVIDER_JSON_BYTES = 32 * 1024 * 1024;
|
|
15
|
+
export const MAX_PROVIDER_ERROR_BYTES = 64 * 1024;
|
|
16
|
+
export const MAX_PROVIDER_ERROR_CHARS = 2_048;
|
|
17
|
+
export const MAX_SSE_BUFFER_BYTES = 4 * 1024 * 1024;
|
|
18
|
+
export class ProviderHttpError extends Error {
|
|
19
|
+
status;
|
|
20
|
+
retryAfterMs;
|
|
21
|
+
code;
|
|
22
|
+
constructor(message, options) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = 'ProviderHttpError';
|
|
25
|
+
this.status = options.status;
|
|
26
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
27
|
+
this.code = options.code;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Preserve explicit `0` temperature (unlike `options.temperature || 0.1`).
|
|
32
|
+
*/
|
|
33
|
+
export function resolveTemperature(value, fallback = 0.1) {
|
|
34
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Validate that a required cloud BYOK API key is present before issuing a request.
|
|
38
|
+
*/
|
|
39
|
+
export function requireApiKey(apiKey, providerLabel) {
|
|
40
|
+
const trimmed = typeof apiKey === 'string' ? apiKey.trim() : '';
|
|
41
|
+
if (!trimmed) {
|
|
42
|
+
throw new Error(`${providerLabel} API requires a valid API key (BYOK mode). Configure it with \`causyne config\`.`);
|
|
43
|
+
}
|
|
44
|
+
return trimmed;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* True for loopback addresses where local unencrypted HTTP inference servers
|
|
48
|
+
* (Ollama, LM Studio, vLLM, llama.cpp) legitimately run.
|
|
49
|
+
*/
|
|
50
|
+
export function isLoopbackHost(rawHostname) {
|
|
51
|
+
const host = String(rawHostname || '')
|
|
52
|
+
.trim()
|
|
53
|
+
.toLowerCase()
|
|
54
|
+
.replace(/^\[/, '')
|
|
55
|
+
.replace(/\]$/, '')
|
|
56
|
+
.replace(/\.$/, '');
|
|
57
|
+
if (!host)
|
|
58
|
+
return false;
|
|
59
|
+
if (host === 'localhost' || host.endsWith('.localhost') || host === '::1')
|
|
60
|
+
return true;
|
|
61
|
+
if (host.startsWith('127.')) {
|
|
62
|
+
const octets = host.split('.');
|
|
63
|
+
return octets.length === 4 && octets.every((part) => {
|
|
64
|
+
if (!/^\d{1,3}$/.test(part))
|
|
65
|
+
return false;
|
|
66
|
+
const num = Number(part);
|
|
67
|
+
return num >= 0 && num <= 255;
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Validate a provider endpoint URL before transmitting requests or credentials.
|
|
74
|
+
* Blocks invalid schemes, embedded URL credentials, and cleartext remote HTTP
|
|
75
|
+
* when transmitting an API key (unless explicitly opted in).
|
|
76
|
+
*/
|
|
77
|
+
export function validateProviderEndpointUrl(rawUrl, options = {}) {
|
|
78
|
+
const label = options.providerLabel || 'Provider';
|
|
79
|
+
const trimmed = typeof rawUrl === 'string' ? rawUrl.trim() : '';
|
|
80
|
+
if (!trimmed) {
|
|
81
|
+
throw new Error(`${label} endpoint URL is required.`);
|
|
82
|
+
}
|
|
83
|
+
let parsed;
|
|
84
|
+
try {
|
|
85
|
+
parsed = new URL(trimmed);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
throw new Error(`${label} endpoint URL is invalid.`);
|
|
89
|
+
}
|
|
90
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
91
|
+
throw new Error(`${label} endpoint URL must use https:// or http:// (got ${parsed.protocol}).`);
|
|
92
|
+
}
|
|
93
|
+
if (parsed.username || parsed.password) {
|
|
94
|
+
throw new Error(`${label} endpoint URL must not embed credentials.`);
|
|
95
|
+
}
|
|
96
|
+
if (parsed.protocol === 'http:'
|
|
97
|
+
&& options.hasApiKey === true
|
|
98
|
+
&& options.allowInsecureHttp !== true
|
|
99
|
+
&& !isLoopbackHost(parsed.hostname)) {
|
|
100
|
+
throw new Error(`${label} refused to send an API key over unencrypted remote HTTP (${parsed.hostname}). Use https:// or set allowInsecureHttp: true for a trusted private network.`);
|
|
101
|
+
}
|
|
102
|
+
return parsed.toString();
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Parse an HTTP `Retry-After` header (delta-seconds or HTTP-date) into bounded ms.
|
|
106
|
+
*/
|
|
107
|
+
export function parseRetryAfterMs(headerValue) {
|
|
108
|
+
if (typeof headerValue !== 'string')
|
|
109
|
+
return undefined;
|
|
110
|
+
const trimmed = headerValue.trim();
|
|
111
|
+
if (!trimmed)
|
|
112
|
+
return undefined;
|
|
113
|
+
if (/^\d+$/.test(trimmed)) {
|
|
114
|
+
const seconds = Number(trimmed);
|
|
115
|
+
if (!Number.isFinite(seconds) || seconds < 0)
|
|
116
|
+
return undefined;
|
|
117
|
+
return Math.min(seconds * 1000, 300_000);
|
|
118
|
+
}
|
|
119
|
+
const parsedDate = Date.parse(trimmed);
|
|
120
|
+
if (Number.isFinite(parsedDate)) {
|
|
121
|
+
const delta = parsedDate - Date.now();
|
|
122
|
+
return Math.max(0, Math.min(delta, 300_000));
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Redact API keys, Bearer tokens, and query keys from provider errors and
|
|
128
|
+
* sanitize terminal control/ANSI escape sequences.
|
|
129
|
+
*/
|
|
130
|
+
export function redactProviderSecrets(rawText, secrets = []) {
|
|
131
|
+
let text = safeDisplay(typeof rawText === 'string' ? rawText : String(rawText ?? ''));
|
|
132
|
+
for (const secret of secrets) {
|
|
133
|
+
if (typeof secret === 'string') {
|
|
134
|
+
const trimmed = secret.trim();
|
|
135
|
+
if (trimmed.length >= 6) {
|
|
136
|
+
text = text.split(trimmed).join('[REDACTED]');
|
|
137
|
+
const encoded = encodeURIComponent(trimmed);
|
|
138
|
+
if (encoded !== trimmed && encoded.length >= 6) {
|
|
139
|
+
text = text.split(encoded).join('[REDACTED]');
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// Linear-time token masks (no nested quantifiers / zero ReDoS risk).
|
|
145
|
+
text = text.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{6,}/gi, 'Bearer [REDACTED]');
|
|
146
|
+
text = text.replace(/([?&](?:api_?)?key=)[^&\s"']+/gi, '$1[REDACTED]');
|
|
147
|
+
text = text.replace(/\b(?:sk-[A-Za-z0-9_-]{12,}|AIza[A-Za-z0-9_-]{20,})\b/g, '[REDACTED]');
|
|
148
|
+
if (text.length > MAX_PROVIDER_ERROR_CHARS) {
|
|
149
|
+
return `${text.slice(0, MAX_PROVIDER_ERROR_CHARS)}…`;
|
|
150
|
+
}
|
|
151
|
+
return text;
|
|
152
|
+
}
|
|
153
|
+
function getHeaderCaseInsensitive(response, name) {
|
|
154
|
+
const headers = response.headers;
|
|
155
|
+
if (headers && typeof headers.get === 'function') {
|
|
156
|
+
return headers.get(name);
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
async function cancelBodySafely(response) {
|
|
161
|
+
try {
|
|
162
|
+
if (response.body && typeof response.body.cancel === 'function') {
|
|
163
|
+
await response.body.cancel();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// Ignore stream cancellation errors during cleanup.
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Read a Response body as UTF-8 text while enforcing a strict byte cap so a
|
|
172
|
+
* hostile or misconfigured upstream cannot exhaust host RAM.
|
|
173
|
+
*/
|
|
174
|
+
export async function readBoundedResponseText(response, maxBytes, options = {}) {
|
|
175
|
+
const limit = Math.max(1, Math.floor(maxBytes));
|
|
176
|
+
const declaredLen = getHeaderCaseInsensitive(response, 'content-length');
|
|
177
|
+
if (!options.truncate && declaredLen && /^\d+$/.test(declaredLen.trim())) {
|
|
178
|
+
const contentLength = Number(declaredLen.trim());
|
|
179
|
+
if (Number.isFinite(contentLength) && contentLength > limit) {
|
|
180
|
+
await cancelBodySafely(response);
|
|
181
|
+
throw new Error(`${options.label || 'Provider'} response exceeded maximum allowed size (${limit} bytes).`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (response.body && typeof response.body.getReader === 'function') {
|
|
185
|
+
const reader = response.body.getReader();
|
|
186
|
+
const chunks = [];
|
|
187
|
+
let totalBytes = 0;
|
|
188
|
+
try {
|
|
189
|
+
while (true) {
|
|
190
|
+
const { done, value } = await reader.read();
|
|
191
|
+
if (done)
|
|
192
|
+
break;
|
|
193
|
+
if (!value)
|
|
194
|
+
continue;
|
|
195
|
+
if (totalBytes + value.byteLength > limit) {
|
|
196
|
+
if (options.truncate) {
|
|
197
|
+
const remaining = Math.max(0, limit - totalBytes);
|
|
198
|
+
if (remaining > 0)
|
|
199
|
+
chunks.push(value.subarray(0, remaining));
|
|
200
|
+
await reader.cancel().catch(() => { });
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
await reader.cancel().catch(() => { });
|
|
204
|
+
throw new Error(`${options.label || 'Provider'} response exceeded maximum allowed size (${limit} bytes).`);
|
|
205
|
+
}
|
|
206
|
+
chunks.push(value);
|
|
207
|
+
totalBytes += value.byteLength;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
reader.releaseLock();
|
|
212
|
+
}
|
|
213
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
214
|
+
}
|
|
215
|
+
if (typeof response.text === 'function') {
|
|
216
|
+
const text = await response.text();
|
|
217
|
+
const byteLen = Buffer.byteLength(text, 'utf8');
|
|
218
|
+
if (byteLen > limit) {
|
|
219
|
+
if (options.truncate)
|
|
220
|
+
return text.slice(0, limit);
|
|
221
|
+
throw new Error(`${options.label || 'Provider'} response exceeded maximum allowed size (${limit} bytes).`);
|
|
222
|
+
}
|
|
223
|
+
return text;
|
|
224
|
+
}
|
|
225
|
+
return '';
|
|
226
|
+
}
|
|
227
|
+
function clampTimeout(timeoutMs) {
|
|
228
|
+
if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs)) {
|
|
229
|
+
return DEFAULT_PROVIDER_TIMEOUT_MS;
|
|
230
|
+
}
|
|
231
|
+
return Math.max(MIN_PROVIDER_TIMEOUT_MS, Math.min(Math.floor(timeoutMs), MAX_PROVIDER_TIMEOUT_MS));
|
|
232
|
+
}
|
|
233
|
+
function isAbortLikeError(err) {
|
|
234
|
+
if (!err || typeof err !== 'object')
|
|
235
|
+
return false;
|
|
236
|
+
const name = err.name;
|
|
237
|
+
return name === 'AbortError' || name === 'TimeoutError';
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Perform a hardened `fetch()` to an LLM provider endpoint with:
|
|
241
|
+
* - Endpoint URL validation
|
|
242
|
+
* - `redirect: 'error'` (prevents auth header leakage across redirects)
|
|
243
|
+
* - Cooperative caller AbortSignal + bounded request timeout
|
|
244
|
+
* - Secret redaction on thrown network errors
|
|
245
|
+
*/
|
|
246
|
+
export async function safeProviderFetch(options) {
|
|
247
|
+
const hasKey = options.hasApiKey ?? Boolean(options.headers?.Authorization
|
|
248
|
+
|| options.headers?.['x-api-key']
|
|
249
|
+
|| options.headers?.['x-goog-api-key']);
|
|
250
|
+
const safeUrl = validateProviderEndpointUrl(options.url, {
|
|
251
|
+
hasApiKey: hasKey,
|
|
252
|
+
allowInsecureHttp: options.allowInsecureHttp,
|
|
253
|
+
providerLabel: options.providerLabel
|
|
254
|
+
});
|
|
255
|
+
const timeoutMs = clampTimeout(options.timeoutMs);
|
|
256
|
+
const controller = new AbortController();
|
|
257
|
+
let timedOut = false;
|
|
258
|
+
const onCallerAbort = () => {
|
|
259
|
+
controller.abort(options.signal?.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
260
|
+
};
|
|
261
|
+
if (options.signal) {
|
|
262
|
+
if (options.signal.aborted) {
|
|
263
|
+
onCallerAbort();
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
options.signal.addEventListener('abort', onCallerAbort, { once: true });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const timer = setTimeout(() => {
|
|
270
|
+
timedOut = true;
|
|
271
|
+
controller.abort(new DOMException(`Timed out after ${timeoutMs}ms`, 'TimeoutError'));
|
|
272
|
+
}, timeoutMs);
|
|
273
|
+
if (typeof timer.unref === 'function')
|
|
274
|
+
timer.unref();
|
|
275
|
+
const cleanup = () => {
|
|
276
|
+
clearTimeout(timer);
|
|
277
|
+
if (options.signal) {
|
|
278
|
+
options.signal.removeEventListener('abort', onCallerAbort);
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
const fetchInit = {
|
|
282
|
+
method: options.method || 'POST',
|
|
283
|
+
redirect: 'error',
|
|
284
|
+
signal: controller.signal
|
|
285
|
+
};
|
|
286
|
+
if (options.headers)
|
|
287
|
+
fetchInit.headers = options.headers;
|
|
288
|
+
if (options.body !== undefined)
|
|
289
|
+
fetchInit.body = options.body;
|
|
290
|
+
try {
|
|
291
|
+
const response = await fetch(safeUrl, fetchInit);
|
|
292
|
+
return { response, cleanup };
|
|
293
|
+
}
|
|
294
|
+
catch (err) {
|
|
295
|
+
cleanup();
|
|
296
|
+
if (options.signal?.aborted) {
|
|
297
|
+
throw err;
|
|
298
|
+
}
|
|
299
|
+
if (timedOut || (isAbortLikeError(err) && !options.signal?.aborted)) {
|
|
300
|
+
const timeoutErr = new Error(`${options.providerLabel} request timed out after ${timeoutMs}ms (ETIMEDOUT)`);
|
|
301
|
+
timeoutErr.code = 'ETIMEDOUT';
|
|
302
|
+
throw timeoutErr;
|
|
303
|
+
}
|
|
304
|
+
const rawMsg = err instanceof Error ? err.message : String(err);
|
|
305
|
+
const causeMsg = err instanceof Error && err.cause instanceof Error ? err.cause.message : '';
|
|
306
|
+
const combined = `${rawMsg} ${causeMsg}`.toLowerCase();
|
|
307
|
+
if (combined.includes('redirect')) {
|
|
308
|
+
throw new Error(`${options.providerLabel} refused an HTTP redirect to protect API credentials.`);
|
|
309
|
+
}
|
|
310
|
+
const safeMsg = redactProviderSecrets(rawMsg, options.secrets);
|
|
311
|
+
throw new Error(`${options.providerLabel} network error: ${safeMsg}`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Perform a hardened BYOK provider JSON request, enforcing bounded response/error
|
|
316
|
+
* reading, secret redaction, Retry-After extraction, and clean non-JSON error handling.
|
|
317
|
+
*/
|
|
318
|
+
export async function safeProviderFetchJson(options) {
|
|
319
|
+
const { response, cleanup } = await safeProviderFetch(options);
|
|
320
|
+
try {
|
|
321
|
+
if (!response.ok) {
|
|
322
|
+
const rawError = await readBoundedResponseText(response, options.maxErrorBytes ?? MAX_PROVIDER_ERROR_BYTES, { truncate: true, label: options.providerLabel }).catch(() => '');
|
|
323
|
+
const cleanError = redactProviderSecrets(rawError, options.secrets);
|
|
324
|
+
const retryAfterMs = parseRetryAfterMs(getHeaderCaseInsensitive(response, 'retry-after'));
|
|
325
|
+
if (options.onHttpError) {
|
|
326
|
+
options.onHttpError({
|
|
327
|
+
status: response.status,
|
|
328
|
+
errorText: cleanError,
|
|
329
|
+
retryAfterMs,
|
|
330
|
+
response
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
const retryNote = retryAfterMs !== undefined
|
|
334
|
+
? ` (retry after ${Math.ceil(retryAfterMs / 1000)}s)`
|
|
335
|
+
: '';
|
|
336
|
+
throw new ProviderHttpError(`${options.providerLabel} API Error (${response.status})${retryNote}: ${cleanError}`, { status: response.status, retryAfterMs });
|
|
337
|
+
}
|
|
338
|
+
// Minimal unit-test mocks may supply `.json()` without `.body` or `.text()`.
|
|
339
|
+
if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
|
|
340
|
+
return (await response.json());
|
|
341
|
+
}
|
|
342
|
+
const rawText = await readBoundedResponseText(response, options.maxBytes ?? MAX_PROVIDER_JSON_BYTES, { truncate: false, label: options.providerLabel });
|
|
343
|
+
try {
|
|
344
|
+
return JSON.parse(rawText);
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
const preview = redactProviderSecrets(rawText.slice(0, 240), options.secrets);
|
|
348
|
+
throw new Error(`${options.providerLabel} returned a non-JSON response (HTTP ${response.status}): ${preview}`);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
finally {
|
|
352
|
+
cleanup();
|
|
353
|
+
}
|
|
354
|
+
}
|