@causyne/agent 1.20.117 → 1.20.120

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +20 -4
  13. package/src/commands.js +12 -14
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/plugins/pluginManager.js +74 -0
  19. package/src/providers/anthropic.js +33 -17
  20. package/src/providers/base.js +14 -0
  21. package/src/providers/dashscope-byok.js +13 -7
  22. package/src/providers/deepseek.js +13 -18
  23. package/src/providers/gemini.js +33 -25
  24. package/src/providers/moonshot.js +13 -12
  25. package/src/providers/ollama.js +21 -21
  26. package/src/providers/openai-compatible.js +12 -19
  27. package/src/providers/openrouter.js +20 -90
  28. package/src/providers/openrouter.ts +31 -94
  29. package/src/providers/qwen-byok.js +13 -7
  30. package/src/providers/toolContracts.js +9 -3
  31. package/src/providers/toolContracts.ts +9 -3
  32. package/src/providers/wireNormalizer.js +238 -0
  33. package/src/providers/wireNormalizer.ts +279 -0
  34. package/src/providers/xai.js +13 -12
  35. package/src/reporting.js +12 -4
  36. package/src/skillsManager.js +3 -2
  37. package/src/skillsManager.ts +3 -2
  38. package/src/tools/browserAutomator.js +13 -1
  39. package/src/tools/browserAutomator.ts +13 -0
  40. package/src/tools/creativeApps.js +2 -1
  41. package/src/tools/creativeApps.ts +2 -1
  42. package/src/tools/gameAssetFetcher.js +130 -26
  43. package/src/tools/gameAssetHarvester.js +80 -58
  44. package/src/tools/nativeEngine.js +1 -1
  45. package/src/tools/nativeEngine.ts +1 -1
  46. package/src/tools/pluginManager.js +17 -2
  47. package/src/tools/registry.js +13 -0
  48. package/src/tools/toolScanner.js +596 -140
  49. package/src/tools/toolScanner.ts +665 -147
  50. package/src/tools/toolSelfRepair.js +243 -114
  51. package/src/tools/toolSelfRepair.ts +262 -111
  52. package/src/tools/webFetch.js +161 -24
  53. package/src/tools/webFetch.ts +157 -22
  54. package/src/tools/webSearch.js +33 -4
  55. package/src/tools/webSearch.ts +27 -4
  56. package/src/tui/composerControls.js +16 -3
  57. package/src/tui/composerControls.ts +14 -3
  58. package/src/tui/prompt.js +122 -16
  59. package/src/tui/sessionPicker.js +132 -35
  60. package/src/tui/sessionPicker.ts +153 -32
  61. package/src/tui/sessionPickerView.js +277 -34
  62. package/src/tui/sessionPickerView.ts +328 -34
  63. package/src/tui/statusLine.js +3 -0
  64. package/src/tui/statusLine.ts +5 -0
  65. package/src/tui/usageCard.js +119 -47
  66. package/src/tui/usageCard.ts +133 -49
  67. package/src/tui/workspaceIdentity.js +133 -0
  68. package/src/tui/workspaceIdentity.ts +146 -0
  69. package/src/tui/workspaceSwitch.js +2 -0
  70. package/src/tui/workspaceSwitch.ts +1 -0
  71. package/src/verification/boundedExplorer.js +119 -0
  72. package/src/verification/cliProbe.js +116 -0
  73. package/src/verification/featureMap.js +78 -0
  74. package/src/verification/interactivePty.js +188 -0
  75. package/src/verification/propertyProbe.js +121 -0
  76. package/src/verification/ptyProbe.js +125 -0
  77. package/src/verification/skillCatalog.d.ts +1 -0
  78. package/src/verification/skillCatalog.js +60 -0
  79. package/src/verification/statechart.js +143 -0
  80. package/src/verification/uiRuntime.js +57 -0
  81. package/src/verificationPlan.js +1 -1
  82. package/src/verificationPlan.ts +1 -1
@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { BrowserCapabilityError, causyneBrowser } from '../browser/causyneBrowser.js';
5
5
  import { assertPublicWebUrl } from '../browser/urlPolicy.js';
6
+ import { ensureSafeWorkspaceOutputPath } from '../browser/workspacePathSafety.js';
6
7
  const MAX_REDIRECTS = 5;
7
8
  const MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
8
9
  const MAX_OUTPUT_CHARS = 80_000;
@@ -10,11 +11,14 @@ const REQUEST_TIMEOUT_MS = 30_000;
10
11
  function decodeEntities(text) {
11
12
  const named = { amp: '&', apos: "'", gt: '>', lt: '<', nbsp: ' ', quot: '"' };
12
13
  return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (full, entity) => {
13
- if (entity.startsWith('#x'))
14
- return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
15
- if (entity.startsWith('#'))
16
- return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
17
- return named[entity.toLowerCase()] ?? full;
14
+ const normalized = entity.toLowerCase();
15
+ const codePoint = normalized.startsWith('#x') ? Number.parseInt(normalized.slice(2), 16)
16
+ : normalized.startsWith('#') ? Number.parseInt(normalized.slice(1), 10) : null;
17
+ if (codePoint !== null) {
18
+ return Number.isInteger(codePoint) && codePoint > 0 && codePoint <= 0x10ffff &&
19
+ !(codePoint >= 0xd800 && codePoint <= 0xdfff) ? String.fromCodePoint(codePoint) : full;
20
+ }
21
+ return named[normalized] ?? full;
18
22
  });
19
23
  }
20
24
  export function htmlToReadableText(html) {
@@ -28,10 +32,28 @@ export function htmlToReadableText(html) {
28
32
  .replace(/\n{3,}/g, '\n\n')
29
33
  .trim();
30
34
  }
35
+ export function isBinaryResponseContentType(contentType) {
36
+ const mediaType = contentType.split(';', 1)[0]?.trim().toLowerCase() ?? '';
37
+ if (mediaType === 'image/svg+xml' || mediaType.startsWith('text/'))
38
+ return false;
39
+ if (/^application\/(?:json|xml|javascript|ecmascript|x-javascript|x-www-form-urlencoded|graphql|sql|yaml|x-yaml|x-ndjson)$/.test(mediaType))
40
+ return false;
41
+ if (/^application\/.+\+(?:json|xml)$/.test(mediaType))
42
+ return false;
43
+ return /^(?:application|image|audio|video|font)\//.test(mediaType);
44
+ }
45
+ export function looksLikeBinaryContent(bytes) {
46
+ if (bytes.length === 0)
47
+ return false;
48
+ const magic = bytes.subarray(0, 8).toString('hex');
49
+ return /^(?:89504e470d0a1a0a|504b0304|504b0506|25504446|1f8b|ffd8ff|0061736d)/i.test(magic)
50
+ || bytes.subarray(0, 512).includes(0);
51
+ }
31
52
  function isWithin(root, candidate) {
32
53
  const relative = path.relative(root, candidate);
33
54
  return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
34
55
  }
56
+ const FORBIDDEN_REQUEST_HEADERS = new Set(['host', 'connection', 'proxy-connection', 'proxy-authorization', 'content-length', 'transfer-encoding', 'upgrade', 'te', 'trailer', 'keep-alive']);
35
57
  function validatedHeaders(value) {
36
58
  if (value === undefined)
37
59
  return {};
@@ -39,7 +61,7 @@ function validatedHeaders(value) {
39
61
  throw new Error('headers must be an object');
40
62
  const result = {};
41
63
  for (const [key, item] of Object.entries(value)) {
42
- if (typeof item !== 'string' || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(key) || /[\r\n]/.test(item)) {
64
+ if (typeof item !== 'string' || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(key) || /[\r\n]/.test(item) || FORBIDDEN_REQUEST_HEADERS.has(key.toLowerCase())) {
43
65
  throw new Error('headers contain an invalid name or value');
44
66
  }
45
67
  result[key] = item;
@@ -53,14 +75,31 @@ async function fetchFollowingSafeRedirects(urlValue, options) {
53
75
  const response = await fetch(url, { ...request, redirect: 'manual' });
54
76
  if (![301, 302, 303, 307, 308].includes(response.status))
55
77
  return { response, finalUrl: url };
78
+ const location = response.headers.get('location');
79
+ await response.body?.cancel().catch(() => { });
56
80
  if (redirect === MAX_REDIRECTS)
57
81
  throw new Error(`Too many redirects (maximum ${MAX_REDIRECTS})`);
58
- const location = response.headers.get('location');
59
82
  if (!location)
60
83
  throw new Error(`HTTP ${response.status} redirect has no Location header`);
61
- await response.body?.cancel().catch(() => { });
62
- url = await assertPublicWebUrl(new URL(location, url).href);
63
- if (response.status === 303 || ([301, 302].includes(response.status) && request.method === 'POST')) {
84
+ const nextUrl = await assertPublicWebUrl(new URL(location, url).href);
85
+ if (url.protocol === 'https:' && nextUrl.protocol !== 'https:') {
86
+ throw new Error('HTTPS to HTTP redirect downgrade is not allowed');
87
+ }
88
+ if (nextUrl.origin !== url.origin && request.method !== 'GET' && request.method !== 'HEAD') {
89
+ throw new Error('Cross-origin redirect blocked for state-changing HTTP request');
90
+ }
91
+ if (nextUrl.origin !== url.origin) {
92
+ const forwardedHeaders = new Headers();
93
+ const currentHeaders = new Headers(request.headers);
94
+ for (const name of ['accept', 'accept-language', 'user-agent']) {
95
+ const value = currentHeaders.get(name);
96
+ if (value !== null)
97
+ forwardedHeaders.set(name, value);
98
+ }
99
+ request = { ...request, headers: forwardedHeaders };
100
+ }
101
+ url = nextUrl;
102
+ if ((response.status === 303 && request.method !== 'HEAD') || ([301, 302].includes(response.status) && request.method === 'POST')) {
64
103
  const redirectedHeaders = new Headers(request.headers);
65
104
  redirectedHeaders.delete('content-length');
66
105
  redirectedHeaders.delete('content-type');
@@ -94,6 +133,48 @@ async function readBoundedBody(response) {
94
133
  }
95
134
  return Buffer.concat(chunks.map(chunk => Buffer.from(chunk)), size);
96
135
  }
136
+ export async function writeResponseBodyAtomically(response, workspace, target, maxBytes = MAX_RESPONSE_BYTES) {
137
+ await ensureSafeWorkspaceOutputPath(workspace, target);
138
+ const temporary = `${target}.part-${crypto.randomUUID()}`;
139
+ let handle;
140
+ const reader = response.body?.getReader();
141
+ let received = 0;
142
+ try {
143
+ handle = await fs.open(temporary, 'wx', 0o600);
144
+ if (reader) {
145
+ while (true) {
146
+ const { done, value } = await reader.read();
147
+ if (done)
148
+ break;
149
+ if (!value || value.byteLength === 0)
150
+ continue;
151
+ if (received + value.byteLength > maxBytes)
152
+ throw new Error(`Response exceeds ${maxBytes} bytes`);
153
+ let offset = 0;
154
+ while (offset < value.byteLength) {
155
+ const { bytesWritten } = await handle.write(value, offset, value.byteLength - offset, null);
156
+ if (bytesWritten <= 0)
157
+ throw new Error('Download made no write progress');
158
+ offset += bytesWritten;
159
+ }
160
+ received += value.byteLength;
161
+ }
162
+ }
163
+ await handle.close();
164
+ handle = undefined;
165
+ await fs.rename(temporary, target);
166
+ return received;
167
+ }
168
+ catch (error) {
169
+ await reader?.cancel().catch(() => { });
170
+ throw error;
171
+ }
172
+ finally {
173
+ reader?.releaseLock();
174
+ await handle?.close().catch(() => { });
175
+ await fs.unlink(temporary).catch(() => { });
176
+ }
177
+ }
97
178
  async function browserFallback(url, workspace) {
98
179
  try {
99
180
  const results = await causyneBrowser(workspace ? { workspace } : undefined).run([{ type: 'goto', url }, { type: 'extract', selector: 'body' }], workspace ? { workspace } : undefined);
@@ -131,18 +212,67 @@ export const webFetch = {
131
212
  if (!args.url)
132
213
  return { success: false, error: 'url is required' };
133
214
  const workspace = path.resolve(sandbox?.workspacePaths?.[0] ?? sandbox?.workspaceRoot ?? process.cwd());
215
+ if (args.method !== undefined && typeof args.method !== 'string') {
216
+ return { success: false, error: 'HTTP method must be a string' };
217
+ }
134
218
  const method = (args.method ?? 'GET').toUpperCase();
219
+ if (!['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
220
+ return { success: false, error: 'Unsupported HTTP method' };
221
+ }
222
+ if (args.outputFile !== undefined && (typeof args.outputFile !== 'string' || !args.outputFile.trim())) {
223
+ return { success: false, error: 'Download outputFile must be a non-empty string' };
224
+ }
225
+ if (method === 'HEAD' && args.outputFile) {
226
+ return { success: false, error: 'HEAD responses cannot be downloaded as resource files' };
227
+ }
135
228
  const headers = {
136
229
  'User-Agent': 'Causyne-Agent/1.10 (+https://causyne.com)',
137
230
  Accept: 'text/html,application/xhtml+xml,application/json,text/plain,*/*;q=0.8',
138
231
  ...validatedHeaders(args.headers)
139
232
  };
140
233
  const request = { method, headers, signal: controller.signal };
141
- if (args.body !== undefined && method !== 'GET' && method !== 'HEAD')
234
+ if (args.body !== undefined) {
235
+ if (typeof args.body !== 'string')
236
+ return { success: false, error: 'HTTP request body must be a string' };
237
+ if (method === 'GET' || method === 'HEAD')
238
+ return { success: false, error: `${method} requests cannot contain a body` };
142
239
  request.body = args.body;
240
+ }
143
241
  const { response, finalUrl } = await fetchFollowingSafeRedirects(args.url, request);
144
242
  const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
145
- if (!response.ok && !args.outputFile && contentType.includes('text/html') && [401, 403, 429, 503].includes(response.status)) {
243
+ if (response.status === 401) {
244
+ await response.body?.cancel().catch(() => { });
245
+ return {
246
+ success: false, status: 401, finalUrl: finalUrl.href,
247
+ failureKind: 'authentication_required', error: 'HTTP 401: this resource requires authentication'
248
+ };
249
+ }
250
+ if (response.status === 503 && response.headers.has('retry-after')) {
251
+ const retryAfter = response.headers.get('retry-after');
252
+ await response.body?.cancel().catch(() => { });
253
+ return { success: false, status: 503, finalUrl: finalUrl.href, failureKind: 'service_unavailable',
254
+ ...(retryAfter ? { retryAfter } : {}),
255
+ error: 'HTTP 503: respect the Retry-After window before requesting this resource again' };
256
+ }
257
+ if (response.status === 429) {
258
+ const retryAfter = response.headers.get('retry-after');
259
+ await response.body?.cancel().catch(() => { });
260
+ return {
261
+ success: false, status: 429, finalUrl: finalUrl.href, failureKind: 'rate_limited',
262
+ ...(retryAfter ? { retryAfter } : {}),
263
+ error: 'HTTP 429 rate limit: respect the Retry-After window before retrying'
264
+ };
265
+ }
266
+ if (args.outputFile && response.status === 206 && !(new Headers(headers)).has('range')) {
267
+ await response.body?.cancel().catch(() => { });
268
+ return { success: false, status: 206, finalUrl: finalUrl.href, error: 'Server returned partial content without a requested Range' };
269
+ }
270
+ if (args.outputFile && response.status === 204) {
271
+ await response.body?.cancel().catch(() => { });
272
+ return { success: false, status: 204, finalUrl: finalUrl.href, error: 'No downloadable content was returned (HTTP 204)' };
273
+ }
274
+ if (!response.ok && method === 'GET' && !args.outputFile && contentType.includes('text/html') && [401, 403, 429, 503].includes(response.status)) {
275
+ await response.body?.cancel().catch(() => { });
146
276
  const fallback = await browserFallback(finalUrl.href, workspace);
147
277
  if (fallback.success)
148
278
  return { ...fallback, status: response.status, finalUrl: finalUrl.href, via: 'causyne-browser' };
@@ -162,27 +292,34 @@ export const webFetch = {
162
292
  requiresConsent: fallback.requiresConsent
163
293
  };
164
294
  }
165
- if (!response.ok)
295
+ if (!response.ok) {
296
+ await response.body?.cancel().catch(() => { });
166
297
  return { success: false, error: `HTTP ${response.status} ${response.statusText}`.trim(), status: response.status, finalUrl: finalUrl.href };
298
+ }
299
+ if (!args.outputFile && isBinaryResponseContentType(contentType)) {
300
+ await response.body?.cancel().catch(() => { });
301
+ return { success: false, error: 'Binary content requires outputFile to download without corrupting bytes', status: response.status, finalUrl: finalUrl.href, contentType };
302
+ }
167
303
  const declaredLength = Number(response.headers.get('content-length') ?? '0');
168
304
  if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
305
+ await response.body?.cancel().catch(() => { });
169
306
  return { success: false, error: `Response exceeds ${MAX_RESPONSE_BYTES} bytes` };
170
307
  }
171
- const bytes = await readBoundedBody(response);
172
308
  if (args.outputFile) {
173
309
  const target = path.resolve(workspace, args.outputFile);
174
- if (!isWithin(workspace, target))
310
+ if (!isWithin(workspace, target)) {
311
+ await response.body?.cancel().catch(() => { });
175
312
  return { success: false, error: 'Download target must stay inside the selected workspace' };
176
- const temporary = `${target}.part-${crypto.randomUUID()}`;
177
- await fs.mkdir(path.dirname(target), { recursive: true });
178
- try {
179
- await fs.writeFile(temporary, bytes, { mode: 0o600 });
180
- await fs.rename(temporary, target);
181
- }
182
- finally {
183
- await fs.unlink(temporary).catch(() => { });
184
313
  }
185
- return { success: true, output: `Downloaded ${bytes.length} bytes to ${target}`, status: response.status, finalUrl: finalUrl.href };
314
+ const received = await writeResponseBodyAtomically(response, workspace, target);
315
+ const partial = response.status === 206;
316
+ return { success: true, output: `Downloaded ${partial ? 'partial content: ' : ''}${received} bytes to ${target}`,
317
+ status: response.status, finalUrl: finalUrl.href, ...(partial ? { partial: true } : {}) };
318
+ }
319
+ const bytes = await readBoundedBody(response);
320
+ if (looksLikeBinaryContent(bytes)) {
321
+ return { success: false, error: 'Binary content requires outputFile to download without corrupting bytes',
322
+ status: response.status, finalUrl: finalUrl.href, contentType };
186
323
  }
187
324
  const decoded = bytes.toString('utf8');
188
325
  const readable = contentType.includes('text/html') ? htmlToReadableText(decoded) : decoded;
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
 
5
5
  import { BrowserCapabilityError, causyneBrowser } from '../browser/causyneBrowser.js';
6
6
  import { assertPublicWebUrl } from '../browser/urlPolicy.js';
7
+ import { ensureSafeWorkspaceOutputPath } from '../browser/workspacePathSafety.js';
7
8
 
8
9
  const MAX_REDIRECTS = 5;
9
10
  const MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
@@ -13,9 +14,14 @@ const REQUEST_TIMEOUT_MS = 30_000;
13
14
  function decodeEntities(text: string): string {
14
15
  const named: Record<string, string> = { amp: '&', apos: "'", gt: '>', lt: '<', nbsp: ' ', quot: '"' };
15
16
  return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (full, entity: string) => {
16
- if (entity.startsWith('#x')) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
17
- if (entity.startsWith('#')) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
18
- return named[entity.toLowerCase()] ?? full;
17
+ const normalized = entity.toLowerCase();
18
+ const codePoint = normalized.startsWith('#x') ? Number.parseInt(normalized.slice(2), 16)
19
+ : normalized.startsWith('#') ? Number.parseInt(normalized.slice(1), 10) : null;
20
+ if (codePoint !== null) {
21
+ return Number.isInteger(codePoint) && codePoint > 0 && codePoint <= 0x10ffff &&
22
+ !(codePoint >= 0xd800 && codePoint <= 0xdfff) ? String.fromCodePoint(codePoint) : full;
23
+ }
24
+ return named[normalized] ?? full;
19
25
  });
20
26
  }
21
27
 
@@ -31,17 +37,34 @@ export function htmlToReadableText(html: string): string {
31
37
  .trim();
32
38
  }
33
39
 
40
+ export function isBinaryResponseContentType(contentType: string): boolean {
41
+ const mediaType = contentType.split(';', 1)[0]?.trim().toLowerCase() ?? '';
42
+ if (mediaType === 'image/svg+xml' || mediaType.startsWith('text/')) return false;
43
+ if (/^application\/(?:json|xml|javascript|ecmascript|x-javascript|x-www-form-urlencoded|graphql|sql|yaml|x-yaml|x-ndjson)$/.test(mediaType)) return false;
44
+ if (/^application\/.+\+(?:json|xml)$/.test(mediaType)) return false;
45
+ return /^(?:application|image|audio|video|font)\//.test(mediaType);
46
+ }
47
+
48
+ export function looksLikeBinaryContent(bytes: Buffer): boolean {
49
+ if (bytes.length === 0) return false;
50
+ const magic = bytes.subarray(0, 8).toString('hex');
51
+ return /^(?:89504e470d0a1a0a|504b0304|504b0506|25504446|1f8b|ffd8ff|0061736d)/i.test(magic)
52
+ || bytes.subarray(0, 512).includes(0);
53
+ }
54
+
34
55
  function isWithin(root: string, candidate: string): boolean {
35
56
  const relative = path.relative(root, candidate);
36
57
  return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
37
58
  }
38
59
 
60
+ const FORBIDDEN_REQUEST_HEADERS = new Set(['host', 'connection', 'proxy-connection', 'proxy-authorization', 'content-length', 'transfer-encoding', 'upgrade', 'te', 'trailer', 'keep-alive']);
61
+
39
62
  function validatedHeaders(value: unknown): Record<string, string> {
40
63
  if (value === undefined) return {};
41
64
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('headers must be an object');
42
65
  const result: Record<string, string> = {};
43
66
  for (const [key, item] of Object.entries(value)) {
44
- if (typeof item !== 'string' || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(key) || /[\r\n]/.test(item)) {
67
+ if (typeof item !== 'string' || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(key) || /[\r\n]/.test(item) || FORBIDDEN_REQUEST_HEADERS.has(key.toLowerCase())) {
45
68
  throw new Error('headers contain an invalid name or value');
46
69
  }
47
70
  result[key] = item;
@@ -55,12 +78,28 @@ async function fetchFollowingSafeRedirects(urlValue: string, options: RequestIni
55
78
  for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect++) {
56
79
  const response = await fetch(url, { ...request, redirect: 'manual' });
57
80
  if (![301, 302, 303, 307, 308].includes(response.status)) return { response, finalUrl: url };
58
- if (redirect === MAX_REDIRECTS) throw new Error(`Too many redirects (maximum ${MAX_REDIRECTS})`);
59
81
  const location = response.headers.get('location');
60
- if (!location) throw new Error(`HTTP ${response.status} redirect has no Location header`);
61
82
  await response.body?.cancel().catch(() => {});
62
- url = await assertPublicWebUrl(new URL(location, url).href);
63
- if (response.status === 303 || ([301, 302].includes(response.status) && request.method === 'POST')) {
83
+ if (redirect === MAX_REDIRECTS) throw new Error(`Too many redirects (maximum ${MAX_REDIRECTS})`);
84
+ if (!location) throw new Error(`HTTP ${response.status} redirect has no Location header`);
85
+ const nextUrl = await assertPublicWebUrl(new URL(location, url).href);
86
+ if (url.protocol === 'https:' && nextUrl.protocol !== 'https:') {
87
+ throw new Error('HTTPS to HTTP redirect downgrade is not allowed');
88
+ }
89
+ if (nextUrl.origin !== url.origin && request.method !== 'GET' && request.method !== 'HEAD') {
90
+ throw new Error('Cross-origin redirect blocked for state-changing HTTP request');
91
+ }
92
+ if (nextUrl.origin !== url.origin) {
93
+ const forwardedHeaders = new Headers();
94
+ const currentHeaders = new Headers(request.headers);
95
+ for (const name of ['accept', 'accept-language', 'user-agent']) {
96
+ const value = currentHeaders.get(name);
97
+ if (value !== null) forwardedHeaders.set(name, value);
98
+ }
99
+ request = { ...request, headers: forwardedHeaders };
100
+ }
101
+ url = nextUrl;
102
+ if ((response.status === 303 && request.method !== 'HEAD') || ([301, 302].includes(response.status) && request.method === 'POST')) {
64
103
  const redirectedHeaders = new Headers(request.headers);
65
104
  redirectedHeaders.delete('content-length');
66
105
  redirectedHeaders.delete('content-type');
@@ -93,6 +132,45 @@ async function readBoundedBody(response: Response): Promise<Buffer> {
93
132
  return Buffer.concat(chunks.map(chunk => Buffer.from(chunk)), size);
94
133
  }
95
134
 
135
+ export async function writeResponseBodyAtomically(
136
+ response: Response, workspace: string, target: string, maxBytes = MAX_RESPONSE_BYTES
137
+ ): Promise<number> {
138
+ await ensureSafeWorkspaceOutputPath(workspace, target);
139
+ const temporary = `${target}.part-${crypto.randomUUID()}`;
140
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
141
+ const reader = response.body?.getReader();
142
+ let received = 0;
143
+ try {
144
+ handle = await fs.open(temporary, 'wx', 0o600);
145
+ if (reader) {
146
+ while (true) {
147
+ const { done, value } = await reader.read();
148
+ if (done) break;
149
+ if (!value || value.byteLength === 0) continue;
150
+ if (received + value.byteLength > maxBytes) throw new Error(`Response exceeds ${maxBytes} bytes`);
151
+ let offset = 0;
152
+ while (offset < value.byteLength) {
153
+ const { bytesWritten } = await handle.write(value, offset, value.byteLength - offset, null);
154
+ if (bytesWritten <= 0) throw new Error('Download made no write progress');
155
+ offset += bytesWritten;
156
+ }
157
+ received += value.byteLength;
158
+ }
159
+ }
160
+ await handle.close();
161
+ handle = undefined;
162
+ await fs.rename(temporary, target);
163
+ return received;
164
+ } catch (error) {
165
+ await reader?.cancel().catch(() => {});
166
+ throw error;
167
+ } finally {
168
+ reader?.releaseLock();
169
+ await handle?.close().catch(() => {});
170
+ await fs.unlink(temporary).catch(() => {});
171
+ }
172
+ }
173
+
96
174
  async function browserFallback(url: string, workspace?: string): Promise<{ success: boolean; output?: string; error?: string; requiresConsent?: boolean }> {
97
175
  try {
98
176
  const results = await causyneBrowser(workspace ? { workspace } : undefined).run(
@@ -136,18 +214,66 @@ export const webFetch = {
136
214
  try {
137
215
  if (!args.url) return { success: false, error: 'url is required' };
138
216
  const workspace = path.resolve(sandbox?.workspacePaths?.[0] ?? sandbox?.workspaceRoot ?? process.cwd());
217
+ if (args.method !== undefined && typeof args.method !== 'string') {
218
+ return { success: false, error: 'HTTP method must be a string' };
219
+ }
139
220
  const method = (args.method ?? 'GET').toUpperCase();
221
+ if (!['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
222
+ return { success: false, error: 'Unsupported HTTP method' };
223
+ }
224
+ if (args.outputFile !== undefined && (typeof args.outputFile !== 'string' || !args.outputFile.trim())) {
225
+ return { success: false, error: 'Download outputFile must be a non-empty string' };
226
+ }
227
+ if (method === 'HEAD' && args.outputFile) {
228
+ return { success: false, error: 'HEAD responses cannot be downloaded as resource files' };
229
+ }
140
230
  const headers = {
141
231
  'User-Agent': 'Causyne-Agent/1.10 (+https://causyne.com)',
142
232
  Accept: 'text/html,application/xhtml+xml,application/json,text/plain,*/*;q=0.8',
143
233
  ...validatedHeaders(args.headers)
144
234
  };
145
235
  const request: RequestInit = { method, headers, signal: controller.signal };
146
- if (args.body !== undefined && method !== 'GET' && method !== 'HEAD') request.body = args.body;
236
+ if (args.body !== undefined) {
237
+ if (typeof args.body !== 'string') return { success: false, error: 'HTTP request body must be a string' };
238
+ if (method === 'GET' || method === 'HEAD') return { success: false, error: `${method} requests cannot contain a body` };
239
+ request.body = args.body;
240
+ }
147
241
  const { response, finalUrl } = await fetchFollowingSafeRedirects(args.url, request);
148
242
  const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
149
243
 
150
- if (!response.ok && !args.outputFile && contentType.includes('text/html') && [401, 403, 429, 503].includes(response.status)) {
244
+ if (response.status === 401) {
245
+ await response.body?.cancel().catch(() => {});
246
+ return {
247
+ success: false, status: 401, finalUrl: finalUrl.href,
248
+ failureKind: 'authentication_required', error: 'HTTP 401: this resource requires authentication'
249
+ };
250
+ }
251
+ if (response.status === 503 && response.headers.has('retry-after')) {
252
+ const retryAfter = response.headers.get('retry-after');
253
+ await response.body?.cancel().catch(() => {});
254
+ return { success: false, status: 503, finalUrl: finalUrl.href, failureKind: 'service_unavailable',
255
+ ...(retryAfter ? { retryAfter } : {}),
256
+ error: 'HTTP 503: respect the Retry-After window before requesting this resource again' };
257
+ }
258
+ if (response.status === 429) {
259
+ const retryAfter = response.headers.get('retry-after');
260
+ await response.body?.cancel().catch(() => {});
261
+ return {
262
+ success: false, status: 429, finalUrl: finalUrl.href, failureKind: 'rate_limited',
263
+ ...(retryAfter ? { retryAfter } : {}),
264
+ error: 'HTTP 429 rate limit: respect the Retry-After window before retrying'
265
+ };
266
+ }
267
+ if (args.outputFile && response.status === 206 && !(new Headers(headers)).has('range')) {
268
+ await response.body?.cancel().catch(() => {});
269
+ return { success: false, status: 206, finalUrl: finalUrl.href, error: 'Server returned partial content without a requested Range' };
270
+ }
271
+ if (args.outputFile && response.status === 204) {
272
+ await response.body?.cancel().catch(() => {});
273
+ return { success: false, status: 204, finalUrl: finalUrl.href, error: 'No downloadable content was returned (HTTP 204)' };
274
+ }
275
+ if (!response.ok && method === 'GET' && !args.outputFile && contentType.includes('text/html') && [401, 403, 429, 503].includes(response.status)) {
276
+ await response.body?.cancel().catch(() => {});
151
277
  const fallback = await browserFallback(finalUrl.href, workspace);
152
278
  if (fallback.success) return { ...fallback, status: response.status, finalUrl: finalUrl.href, via: 'causyne-browser' };
153
279
  const nextStep = response.status === 403
@@ -166,26 +292,35 @@ export const webFetch = {
166
292
  requiresConsent: fallback.requiresConsent
167
293
  };
168
294
  }
169
- if (!response.ok) return { success: false, error: `HTTP ${response.status} ${response.statusText}`.trim(), status: response.status, finalUrl: finalUrl.href };
295
+ if (!response.ok) {
296
+ await response.body?.cancel().catch(() => {});
297
+ return { success: false, error: `HTTP ${response.status} ${response.statusText}`.trim(), status: response.status, finalUrl: finalUrl.href };
298
+ }
170
299
 
300
+ if (!args.outputFile && isBinaryResponseContentType(contentType)) {
301
+ await response.body?.cancel().catch(() => {});
302
+ return { success: false, error: 'Binary content requires outputFile to download without corrupting bytes', status: response.status, finalUrl: finalUrl.href, contentType };
303
+ }
171
304
  const declaredLength = Number(response.headers.get('content-length') ?? '0');
172
305
  if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
306
+ await response.body?.cancel().catch(() => {});
173
307
  return { success: false, error: `Response exceeds ${MAX_RESPONSE_BYTES} bytes` };
174
308
  }
175
- const bytes = await readBoundedBody(response);
176
-
177
309
  if (args.outputFile) {
178
310
  const target = path.resolve(workspace, args.outputFile);
179
- if (!isWithin(workspace, target)) return { success: false, error: 'Download target must stay inside the selected workspace' };
180
- const temporary = `${target}.part-${crypto.randomUUID()}`;
181
- await fs.mkdir(path.dirname(target), { recursive: true });
182
- try {
183
- await fs.writeFile(temporary, bytes, { mode: 0o600 });
184
- await fs.rename(temporary, target);
185
- } finally {
186
- await fs.unlink(temporary).catch(() => {});
311
+ if (!isWithin(workspace, target)) {
312
+ await response.body?.cancel().catch(() => {});
313
+ return { success: false, error: 'Download target must stay inside the selected workspace' };
187
314
  }
188
- return { success: true, output: `Downloaded ${bytes.length} bytes to ${target}`, status: response.status, finalUrl: finalUrl.href };
315
+ const received = await writeResponseBodyAtomically(response, workspace, target);
316
+ const partial = response.status === 206;
317
+ return { success: true, output: `Downloaded ${partial ? 'partial content: ' : ''}${received} bytes to ${target}`,
318
+ status: response.status, finalUrl: finalUrl.href, ...(partial ? { partial: true } : {}) };
319
+ }
320
+ const bytes = await readBoundedBody(response);
321
+ if (looksLikeBinaryContent(bytes)) {
322
+ return { success: false, error: 'Binary content requires outputFile to download without corrupting bytes',
323
+ status: response.status, finalUrl: finalUrl.href, contentType };
189
324
  }
190
325
 
191
326
  const decoded = bytes.toString('utf8');
@@ -1,5 +1,28 @@
1
1
  import { BrowserCapabilityError, causyneBrowser } from '../browser/causyneBrowser.js';
2
- import { searchPublicWeb } from '../browser/searchProviders.js';
2
+ import { publicResultUrl, searchPublicWeb } from '../browser/searchProviders.js';
3
+ export function normalizeSearchResults(results) {
4
+ const safe = [];
5
+ const clean = (value, length) => value
6
+ .replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ')
7
+ .replace(/\s+/g, ' ').trim().slice(0, length);
8
+ for (const item of results) {
9
+ if (!item || typeof item.title !== 'string' || typeof item.url !== 'string')
10
+ continue;
11
+ const url = publicResultUrl(item.url);
12
+ if (!url)
13
+ continue;
14
+ const title = clean(item.title, 300);
15
+ if (!title)
16
+ continue;
17
+ safe.push({
18
+ title, url, snippet: clean(typeof item.snippet === 'string' ? item.snippet : '', 500),
19
+ engine: clean(typeof item.engine === 'string' ? item.engine : 'unknown', 40)
20
+ });
21
+ if (safe.length === 10)
22
+ break;
23
+ }
24
+ return safe;
25
+ }
3
26
  function renderResults(query, results) {
4
27
  const lines = [`Search results for "${query}"`, ''];
5
28
  for (const [index, result] of results.entries()) {
@@ -25,19 +48,25 @@ export const webSearch = {
25
48
  }
26
49
  },
27
50
  async execute(args) {
28
- const query = String(args.query ?? '').trim();
51
+ if (typeof args?.query !== 'string')
52
+ return { success: false, error: 'Search query must be a string' };
53
+ const query = args.query.trim();
29
54
  if (!query || query.length > 1_000)
30
55
  return { success: false, error: 'Search query must contain 1-1000 characters' };
31
56
  let lightweightFailure = '';
32
57
  try {
33
- const results = await searchPublicWeb(query);
58
+ const results = normalizeSearchResults(await searchPublicWeb(query));
59
+ if (results.length === 0)
60
+ throw new Error('Public search returned no safe results');
34
61
  return { success: true, output: renderResults(query, results), results };
35
62
  }
36
63
  catch (error) {
37
64
  lightweightFailure = error instanceof Error ? error.message : String(error);
38
65
  }
39
66
  try {
40
- const results = await causyneBrowser().search(query);
67
+ const results = normalizeSearchResults(await causyneBrowser().search(query, { skipPublicFallback: true }));
68
+ if (results.length === 0)
69
+ throw new Error('Rendered search returned no safe results');
41
70
  return { success: true, output: renderResults(query, results), results };
42
71
  }
43
72
  catch (error) {
@@ -1,5 +1,25 @@
1
1
  import { BrowserCapabilityError, causyneBrowser } from '../browser/causyneBrowser.js';
2
- import { searchPublicWeb, type SearchResult } from '../browser/searchProviders.js';
2
+ import { publicResultUrl, searchPublicWeb, type SearchResult } from '../browser/searchProviders.js';
3
+
4
+ export function normalizeSearchResults(results: SearchResult[]): SearchResult[] {
5
+ const safe: SearchResult[] = [];
6
+ const clean = (value: string, length: number) => value
7
+ .replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ')
8
+ .replace(/\s+/g, ' ').trim().slice(0, length);
9
+ for (const item of results) {
10
+ if (!item || typeof item.title !== 'string' || typeof item.url !== 'string') continue;
11
+ const url = publicResultUrl(item.url);
12
+ if (!url) continue;
13
+ const title = clean(item.title, 300);
14
+ if (!title) continue;
15
+ safe.push({
16
+ title, url, snippet: clean(typeof item.snippet === 'string' ? item.snippet : '', 500),
17
+ engine: clean(typeof item.engine === 'string' ? item.engine : 'unknown', 40)
18
+ });
19
+ if (safe.length === 10) break;
20
+ }
21
+ return safe;
22
+ }
3
23
 
4
24
  function renderResults(query: string, results: SearchResult[]): string {
5
25
  const lines = [`Search results for "${query}"`, ''];
@@ -27,17 +47,20 @@ export const webSearch = {
27
47
  },
28
48
 
29
49
  async execute(args: { query?: string }) {
30
- const query = String(args.query ?? '').trim();
50
+ if (typeof args?.query !== 'string') return { success: false, error: 'Search query must be a string' };
51
+ const query = args.query.trim();
31
52
  if (!query || query.length > 1_000) return { success: false, error: 'Search query must contain 1-1000 characters' };
32
53
  let lightweightFailure = '';
33
54
  try {
34
- const results = await searchPublicWeb(query);
55
+ const results = normalizeSearchResults(await searchPublicWeb(query));
56
+ if (results.length === 0) throw new Error('Public search returned no safe results');
35
57
  return { success: true, output: renderResults(query, results), results };
36
58
  } catch (error) {
37
59
  lightweightFailure = error instanceof Error ? error.message : String(error);
38
60
  }
39
61
  try {
40
- const results = await causyneBrowser().search(query);
62
+ const results = normalizeSearchResults(await causyneBrowser().search(query, { skipPublicFallback: true }));
63
+ if (results.length === 0) throw new Error('Rendered search returned no safe results');
41
64
  return { success: true, output: renderResults(query, results), results };
42
65
  } catch (error) {
43
66
  if (error instanceof BrowserCapabilityError) {