@saturn-universe/runtime-host 0.0.0-stage → 0.1.0

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 (116) hide show
  1. package/LICENSE +661 -0
  2. package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
  3. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
  4. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
  5. package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
  6. package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
  7. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
  8. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
  9. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
  10. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
  11. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
  12. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
  13. package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
  14. package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
  15. package/dist/command-dispatch.d.ts +10 -0
  16. package/dist/command-dispatch.js +65 -0
  17. package/dist/completion-judge.d.ts +10 -0
  18. package/dist/completion-judge.js +156 -0
  19. package/dist/composition.d.ts +108 -0
  20. package/dist/composition.js +1180 -0
  21. package/dist/configuration.d.ts +49 -0
  22. package/dist/configuration.js +51 -0
  23. package/dist/context-extensions.d.ts +681 -0
  24. package/dist/context-extensions.js +289 -0
  25. package/dist/cordis/context-core-plugin.d.ts +35 -0
  26. package/dist/cordis/context-core-plugin.js +296 -0
  27. package/dist/cordis/env-probe-plugin.d.ts +27 -0
  28. package/dist/cordis/env-probe-plugin.js +114 -0
  29. package/dist/cordis/host-context.d.ts +65 -0
  30. package/dist/cordis/host-context.js +199 -0
  31. package/dist/cordis/model-responses-plugin.d.ts +81 -0
  32. package/dist/cordis/model-responses-plugin.js +209 -0
  33. package/dist/cordis/plugin-contributions.d.ts +47 -0
  34. package/dist/cordis/plugin-contributions.js +119 -0
  35. package/dist/cordis/plugin-lifecycle.d.ts +57 -0
  36. package/dist/cordis/plugin-lifecycle.js +222 -0
  37. package/dist/cordis/plugin-loader.d.ts +18 -0
  38. package/dist/cordis/plugin-loader.js +310 -0
  39. package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
  40. package/dist/cordis/plugin-sdk-adapter.js +283 -0
  41. package/dist/cordis/required-host-plugin.d.ts +6 -0
  42. package/dist/cordis/required-host-plugin.js +1 -0
  43. package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
  44. package/dist/cordis/runtime-hooks-plugin.js +103 -0
  45. package/dist/cordis/sandbox-plugin.d.ts +18 -0
  46. package/dist/cordis/sandbox-plugin.js +21 -0
  47. package/dist/cordis/scoped-layers.d.ts +63 -0
  48. package/dist/cordis/scoped-layers.js +170 -0
  49. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
  50. package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
  51. package/dist/cordis/tools/index.d.ts +17 -0
  52. package/dist/cordis/tools/index.js +40 -0
  53. package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
  54. package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
  55. package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
  56. package/dist/cordis/tools/process-manager-plugin.js +39 -0
  57. package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
  58. package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
  59. package/dist/cordis/tools/tool-guidance.d.ts +4 -0
  60. package/dist/cordis/tools/tool-guidance.js +30 -0
  61. package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
  62. package/dist/cordis/tools/tools-core-plugin.js +486 -0
  63. package/dist/cordis/tools/web-fetch.d.ts +17 -0
  64. package/dist/cordis/tools/web-fetch.js +529 -0
  65. package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
  66. package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
  67. package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
  68. package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
  69. package/dist/env-probe.d.ts +8 -0
  70. package/dist/env-probe.js +172 -0
  71. package/dist/host-configuration.d.ts +27 -0
  72. package/dist/host-configuration.js +185 -0
  73. package/dist/host-tools.d.ts +19 -0
  74. package/dist/host-tools.js +30 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +140 -0
  77. package/dist/ipc.d.ts +24 -0
  78. package/dist/ipc.js +162 -0
  79. package/dist/logger.d.ts +11 -0
  80. package/dist/logger.js +84 -0
  81. package/dist/mcp-configuration.d.ts +17 -0
  82. package/dist/mcp-configuration.js +50 -0
  83. package/dist/modes.d.ts +27 -0
  84. package/dist/modes.js +472 -0
  85. package/dist/ownership.d.ts +7 -0
  86. package/dist/ownership.js +100 -0
  87. package/dist/plugin-configuration.d.ts +9 -0
  88. package/dist/plugin-configuration.js +21 -0
  89. package/dist/plugin-tool-grants.d.ts +18 -0
  90. package/dist/plugin-tool-grants.js +21 -0
  91. package/dist/process-workspaces.d.ts +4 -0
  92. package/dist/process-workspaces.js +28 -0
  93. package/dist/progress.d.ts +30 -0
  94. package/dist/progress.js +699 -0
  95. package/dist/provider-catalog.d.ts +754 -0
  96. package/dist/provider-catalog.js +471 -0
  97. package/dist/run-budget.d.ts +24 -0
  98. package/dist/run-budget.js +47 -0
  99. package/dist/run-checkpoint.d.ts +2 -0
  100. package/dist/run-checkpoint.js +52 -0
  101. package/dist/sandbox-manager.d.ts +111 -0
  102. package/dist/sandbox-manager.js +1519 -0
  103. package/dist/session-paths.d.ts +15 -0
  104. package/dist/session-paths.js +40 -0
  105. package/dist/side-question.d.ts +14 -0
  106. package/dist/side-question.js +89 -0
  107. package/dist/skills-runtime.d.ts +13 -0
  108. package/dist/skills-runtime.js +243 -0
  109. package/dist/token-estimator.d.ts +3 -0
  110. package/dist/token-estimator.js +73 -0
  111. package/dist/tool-result.d.ts +2 -0
  112. package/dist/tool-result.js +91 -0
  113. package/dist/user-config.d.ts +23 -0
  114. package/dist/user-config.js +36 -0
  115. package/package.json +28 -3
  116. package/README.md +0 -3
@@ -0,0 +1,529 @@
1
+ import { lookup } from 'node:dns/promises';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { request as httpsRequest } from 'node:https';
4
+ import { BlockList, isIP } from 'node:net';
5
+ import { Readable } from 'node:stream';
6
+ import { connect as tlsConnect } from 'node:tls';
7
+ import { aborted } from 'node:util';
8
+ const originalFetch = globalThis.fetch;
9
+ const maxResponseBytes = 2 * 1024 * 1024;
10
+ const maxRedirects = 5;
11
+ const redirectStatuses = new Set([301, 302, 303, 307, 308]);
12
+ const blocked = new BlockList();
13
+ for (const [address, prefix] of [
14
+ ['0.0.0.0', 8],
15
+ ['10.0.0.0', 8],
16
+ ['100.64.0.0', 10],
17
+ ['127.0.0.0', 8],
18
+ ['169.254.0.0', 16],
19
+ ['172.16.0.0', 12],
20
+ ['192.0.0.0', 24],
21
+ ['192.168.0.0', 16],
22
+ ['224.0.0.0', 4],
23
+ ['240.0.0.0', 4],
24
+ ])
25
+ blocked.addSubnet(address, prefix, 'ipv4');
26
+ const fakeIp = new BlockList();
27
+ fakeIp.addSubnet('198.18.0.0', 15, 'ipv4');
28
+ // Reject non-global IPv6 addresses plus transition ranges that embed IPv4 destinations.
29
+ for (const [address, prefix] of [
30
+ ['2001::', 32],
31
+ ['2001:db8::', 32],
32
+ ['2002::', 16],
33
+ ])
34
+ blocked.addSubnet(address, prefix, 'ipv6');
35
+ const globalIPv6 = new BlockList();
36
+ globalIPv6.addSubnet('2000::', 3, 'ipv6');
37
+ globalIPv6.addSubnet('::ffff:0:0', 96, 'ipv6');
38
+ function isBlockedAddress(entry, literalIp, allowFakeIp) {
39
+ if (entry.family === 4) {
40
+ return (blocked.check(entry.address, 'ipv4') ||
41
+ ((literalIp || !allowFakeIp) && fakeIp.check(entry.address, 'ipv4')));
42
+ }
43
+ if (entry.family !== 6 ||
44
+ !globalIPv6.check(entry.address, 'ipv6') ||
45
+ blocked.check(entry.address, 'ipv6')) {
46
+ return true;
47
+ }
48
+ return (literalIp || !allowFakeIp) && fakeIp.check(entry.address, 'ipv6');
49
+ }
50
+ export class WebFetchError extends Error {
51
+ }
52
+ export async function readWebResponse(response, maxBytes) {
53
+ if (Number(response.headers.get('content-length')) > maxBytes) {
54
+ await response.body?.cancel();
55
+ throw new WebFetchError('Response exceeded the byte limit');
56
+ }
57
+ const reader = response.body?.getReader();
58
+ if (!reader)
59
+ return '';
60
+ const decoder = new TextDecoder();
61
+ const parts = [];
62
+ let bytes = 0;
63
+ try {
64
+ while (true) {
65
+ const { done, value } = await reader.read();
66
+ if (done)
67
+ return parts.join('') + decoder.decode();
68
+ bytes += value.byteLength;
69
+ if (bytes > maxBytes) {
70
+ await reader.cancel();
71
+ throw new WebFetchError('Response exceeded the byte limit');
72
+ }
73
+ parts.push(decoder.decode(value, { stream: true }));
74
+ }
75
+ }
76
+ finally {
77
+ reader.releaseLock();
78
+ }
79
+ }
80
+ function validatePublicUrl(url) {
81
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
82
+ throw new WebFetchError('Expected a public HTTP or HTTPS URL without credentials');
83
+ }
84
+ const hostname = url.hostname.replace(/^\[|\]$/g, '').replace(/\.$/, '');
85
+ const family = isIP(hostname);
86
+ const literalIp = family !== 0;
87
+ if (literalIp) {
88
+ if (isBlockedAddress({ address: hostname, family }, true, false)) {
89
+ throw new WebFetchError(`Host is not a public address (${hostname})`);
90
+ }
91
+ }
92
+ else if (!hostname.includes('.') || /(?:^|\.)(?:localhost|local|internal)$/i.test(hostname)) {
93
+ throw new WebFetchError('Host is not a public address');
94
+ }
95
+ return { hostname, family, literalIp };
96
+ }
97
+ async function publicAddresses(url, signal, allowFakeIp) {
98
+ const { hostname, family, literalIp } = validatePublicUrl(url);
99
+ signal.throwIfAborted();
100
+ const pending = literalIp ? undefined : lookup(hostname, { all: true });
101
+ const addresses = pending
102
+ ? await Promise.race([pending, aborted(signal, pending).then(() => signal.throwIfAborted())])
103
+ : [{ address: hostname, family }];
104
+ signal.throwIfAborted();
105
+ if (!addresses?.length)
106
+ throw new WebFetchError('Host is not a public address');
107
+ const rejected = addresses.find((entry) => isBlockedAddress(entry, literalIp, allowFakeIp));
108
+ if (rejected)
109
+ throw new WebFetchError(`Host is not a public address (${rejected.address})`);
110
+ return addresses;
111
+ }
112
+ export function matchesNoProxy(url, noProxy) {
113
+ if (!noProxy?.trim())
114
+ return false;
115
+ const targetHost = url.hostname
116
+ .replace(/^\[|\]$/g, '')
117
+ .replace(/\.$/, '')
118
+ .toLowerCase();
119
+ const targetPort = url.port || (url.protocol === 'https:' ? '443' : '80');
120
+ for (const rawEntry of noProxy.split(',')) {
121
+ const entry = rawEntry.trim().toLowerCase();
122
+ if (!entry)
123
+ continue;
124
+ if (entry === '*')
125
+ return true;
126
+ let hostPattern = entry;
127
+ let portPattern;
128
+ if (entry.startsWith('[')) {
129
+ const closeBracket = entry.indexOf(']');
130
+ if (closeBracket > 0) {
131
+ hostPattern = entry.slice(1, closeBracket);
132
+ if (entry[closeBracket + 1] === ':')
133
+ portPattern = entry.slice(closeBracket + 2);
134
+ }
135
+ }
136
+ else {
137
+ const lastColon = entry.lastIndexOf(':');
138
+ if (lastColon > 0 && !entry.slice(0, lastColon).includes(':')) {
139
+ hostPattern = entry.slice(0, lastColon);
140
+ portPattern = entry.slice(lastColon + 1);
141
+ }
142
+ }
143
+ if (portPattern && portPattern !== targetPort)
144
+ continue;
145
+ const normalized = hostPattern.replace(/^\./, '').replace(/\.$/, '');
146
+ if (!normalized)
147
+ continue;
148
+ if (targetHost === normalized || targetHost.endsWith(`.${normalized}`))
149
+ return true;
150
+ }
151
+ return false;
152
+ }
153
+ export function resolveEnvProxy(url, env = process.env) {
154
+ const noProxy = (env.NO_PROXY ?? env.no_proxy ?? '').trim();
155
+ if (matchesNoProxy(url, noProxy))
156
+ return undefined;
157
+ const httpProxy = (env.HTTP_PROXY ?? env.http_proxy ?? '').trim();
158
+ const httpsProxy = (env.HTTPS_PROXY ?? env.https_proxy ?? '').trim();
159
+ const proxyUrl = url.protocol === 'https:' ? httpsProxy || httpProxy : httpProxy;
160
+ if (!proxyUrl)
161
+ return undefined;
162
+ const parsed = URL.parse(proxyUrl);
163
+ if (!parsed || !['http:', 'https:'].includes(parsed.protocol)) {
164
+ throw new WebFetchError('Invalid proxy configuration');
165
+ }
166
+ return { proxyUrl, httpProxy, httpsProxy, noProxy };
167
+ }
168
+ function collectProxySecrets(env) {
169
+ const secrets = [];
170
+ for (const key of ['HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY', 'https_proxy']) {
171
+ const raw = env[key]?.trim();
172
+ if (!raw)
173
+ continue;
174
+ const parsed = URL.parse(raw);
175
+ if (!parsed)
176
+ continue;
177
+ for (const part of [parsed.username, parsed.password]) {
178
+ if (!part)
179
+ continue;
180
+ secrets.push(part);
181
+ try {
182
+ const decoded = decodeURIComponent(part);
183
+ if (decoded && decoded !== part)
184
+ secrets.push(decoded);
185
+ }
186
+ catch {
187
+ // Ignore malformed percent-encoding.
188
+ }
189
+ }
190
+ }
191
+ return secrets;
192
+ }
193
+ function sanitizeErrorText(raw, redact, env) {
194
+ let text = raw;
195
+ for (const secret of collectProxySecrets(env)) {
196
+ if (secret)
197
+ text = text.replaceAll(secret, '[REDACTED]');
198
+ }
199
+ text = redact(text)
200
+ .replace(/(https?:\/\/)([^/@\s]+@)/gi, '$1[REDACTED]@')
201
+ .replace(/\b(Bearer|Basic)\s+[^\s,;]+/gi, '$1 [REDACTED]')
202
+ .replace(/\b((?:Proxy-)?Authorization)\s*:\s*[^\r\n,;]+/gi, '$1: [REDACTED]')
203
+ .replace(/\s+/g, ' ')
204
+ .trim();
205
+ return text.length > 240 ? `${text.slice(0, 239)}…` : text;
206
+ }
207
+ export function describeWebFetchError(error, redact = (text) => text, env = process.env) {
208
+ if (error instanceof WebFetchError) {
209
+ return sanitizeErrorText(error.message, redact, env) || 'Page request failed';
210
+ }
211
+ const seen = new Set();
212
+ const chain = [];
213
+ let current = error;
214
+ for (let depth = 0; depth < 5 && current && typeof current === 'object' && !seen.has(current); depth++) {
215
+ seen.add(current);
216
+ const rec = current;
217
+ chain.push({
218
+ ...(typeof rec.code === 'string' && rec.code.trim() ? { code: rec.code.trim() } : {}),
219
+ ...(typeof rec.name === 'string' && rec.name.trim() ? { name: rec.name.trim() } : {}),
220
+ ...(typeof rec.message === 'string' && rec.message.trim() ? { message: rec.message.trim() } : {}),
221
+ });
222
+ current = rec.cause;
223
+ }
224
+ if (!chain.length) {
225
+ return typeof error === 'string' && error.trim()
226
+ ? sanitizeErrorText(error, redact, env)
227
+ : 'Page request failed';
228
+ }
229
+ let deepestCode;
230
+ let deepestMessage;
231
+ let timeoutOrAbort;
232
+ for (const node of chain) {
233
+ if (node.code)
234
+ deepestCode = node.code;
235
+ if (node.message && node.message.toLowerCase() !== 'fetch failed') {
236
+ deepestMessage = node.message;
237
+ }
238
+ if (node.name === 'TimeoutError')
239
+ timeoutOrAbort = 'Request timed out';
240
+ else if (node.name === 'AbortError' && !timeoutOrAbort)
241
+ timeoutOrAbort = 'Request aborted';
242
+ }
243
+ if (deepestCode) {
244
+ const cleanMsg = deepestMessage ? sanitizeErrorText(deepestMessage, redact, env) : '';
245
+ if (cleanMsg && !cleanMsg.includes(deepestCode)) {
246
+ return sanitizeErrorText(`${deepestCode}: ${cleanMsg}`, redact, env);
247
+ }
248
+ return sanitizeErrorText(deepestCode, redact, env);
249
+ }
250
+ if (timeoutOrAbort)
251
+ return timeoutOrAbort;
252
+ if (deepestMessage)
253
+ return sanitizeErrorText(deepestMessage, redact, env);
254
+ const topMsg = chain[0]?.message;
255
+ return topMsg ? sanitizeErrorText(topMsg, redact, env) : 'Page request failed';
256
+ }
257
+ let NativeAgent;
258
+ let NativeGlobalKind;
259
+ async function ensureNativeDispatcherClass() {
260
+ if (!NativeAgent || !NativeGlobalKind) {
261
+ // Node 26 lazily initializes its bundled fetch dispatcher. Inspect it once
262
+ // without adding an external undici dependency.
263
+ const dispatcherKey = Symbol.for('undici.globalDispatcher.2');
264
+ const globals = globalThis;
265
+ if (!globals[dispatcherKey])
266
+ await originalFetch('data:,');
267
+ const agent = globals[dispatcherKey]?.constructor;
268
+ if (agent?.name !== 'Agent' && agent?.name !== 'EnvHttpProxyAgent')
269
+ throw new WebFetchError('Direct web connections are unavailable');
270
+ NativeAgent = agent;
271
+ NativeGlobalKind = agent.name;
272
+ }
273
+ return { Ctor: NativeAgent, kind: NativeGlobalKind };
274
+ }
275
+ async function pinnedDispatcher(addresses) {
276
+ const { Ctor } = await ensureNativeDispatcherClass();
277
+ return new Ctor({
278
+ connect: {
279
+ lookup(_hostname, options, callback) {
280
+ const candidates = addresses.filter(({ family }) => !options.family || family === options.family);
281
+ const first = candidates[0];
282
+ if (!first)
283
+ return callback(new Error('No validated address for this address family'));
284
+ if (options.all)
285
+ return callback(null, candidates);
286
+ callback(null, first.address, first.family);
287
+ },
288
+ },
289
+ httpProxy: '',
290
+ httpsProxy: '',
291
+ noProxy: '*',
292
+ });
293
+ }
294
+ function incomingHeaders(rawHeaders) {
295
+ const headers = new Headers();
296
+ for (const [key, value] of Object.entries(rawHeaders)) {
297
+ if (value === undefined)
298
+ continue;
299
+ if (Array.isArray(value)) {
300
+ for (const item of value)
301
+ headers.append(key, item);
302
+ }
303
+ else {
304
+ headers.set(key, value);
305
+ }
306
+ }
307
+ return headers;
308
+ }
309
+ function proxyAuthHeader(proxyUrl) {
310
+ if (!proxyUrl.username && !proxyUrl.password)
311
+ return undefined;
312
+ const user = decodeURIComponent(proxyUrl.username);
313
+ const pass = decodeURIComponent(proxyUrl.password);
314
+ return `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`;
315
+ }
316
+ async function fetchViaNodeProxy(url, proxyUrlStr, signal) {
317
+ const proxyUrl = new URL(proxyUrlStr);
318
+ const proxyHost = proxyUrl.hostname.replace(/^\[|\]$/g, '');
319
+ const proxyPort = Number(proxyUrl.port) || (proxyUrl.protocol === 'https:' ? 443 : 80);
320
+ const proxyAuth = proxyAuthHeader(proxyUrl);
321
+ const requestViaProxy = proxyUrl.protocol === 'https:' ? httpsRequest : httpRequest;
322
+ if (url.protocol === 'http:') {
323
+ return new Promise((resolve, reject) => {
324
+ const req = requestViaProxy({
325
+ hostname: proxyHost,
326
+ port: proxyPort,
327
+ method: 'GET',
328
+ path: url.href,
329
+ headers: {
330
+ host: url.host,
331
+ ...(proxyAuth ? { 'proxy-authorization': proxyAuth } : {}),
332
+ },
333
+ signal,
334
+ }, (res) => {
335
+ const status = res.statusCode ?? 502;
336
+ const headers = incomingHeaders(res.headers);
337
+ if (status === 204 || status === 205 || status === 304) {
338
+ res.resume();
339
+ resolve(new Response(null, { status, statusText: res.statusMessage ?? '', headers }));
340
+ return;
341
+ }
342
+ resolve(new Response(Readable.toWeb(res), {
343
+ status,
344
+ statusText: res.statusMessage ?? '',
345
+ headers,
346
+ }));
347
+ });
348
+ req.once('error', reject);
349
+ req.end();
350
+ });
351
+ }
352
+ const targetHost = url.hostname.replace(/^\[|\]$/g, '');
353
+ const targetPort = url.port || '443';
354
+ const targetAuthority = `${url.hostname.includes(':') ? `[${targetHost}]` : targetHost}:${targetPort}`;
355
+ const tunnelSocket = await new Promise((resolve, reject) => {
356
+ const connectReq = requestViaProxy({
357
+ hostname: proxyHost,
358
+ port: proxyPort,
359
+ method: 'CONNECT',
360
+ path: targetAuthority,
361
+ headers: {
362
+ host: targetAuthority,
363
+ ...(proxyAuth ? { 'proxy-authorization': proxyAuth } : {}),
364
+ },
365
+ signal,
366
+ });
367
+ connectReq.once('connect', (res, socket) => {
368
+ if ((res.statusCode ?? 0) !== 200) {
369
+ socket.destroy();
370
+ reject(new WebFetchError(`Proxy CONNECT failed with HTTP ${res.statusCode ?? 0}`));
371
+ return;
372
+ }
373
+ resolve(socket);
374
+ });
375
+ connectReq.once('error', reject);
376
+ connectReq.end();
377
+ });
378
+ const tlsSocket = tlsConnect({
379
+ socket: tunnelSocket,
380
+ servername: targetHost,
381
+ });
382
+ const onAbort = () => {
383
+ tlsSocket.destroy();
384
+ };
385
+ signal.addEventListener('abort', onAbort, { once: true });
386
+ return new Promise((resolve, reject) => {
387
+ let settled = false;
388
+ const fail = (err) => {
389
+ if (settled)
390
+ return;
391
+ settled = true;
392
+ signal.removeEventListener('abort', onAbort);
393
+ tlsSocket.destroy();
394
+ reject(err);
395
+ };
396
+ tlsSocket.once('error', fail);
397
+ const req = httpsRequest(url, {
398
+ method: 'GET',
399
+ agent: false,
400
+ createConnection: () => tlsSocket,
401
+ signal,
402
+ }, (res) => {
403
+ if (settled)
404
+ return;
405
+ settled = true;
406
+ signal.removeEventListener('abort', onAbort);
407
+ const status = res.statusCode ?? 502;
408
+ const headers = incomingHeaders(res.headers);
409
+ if (status === 204 || status === 205 || status === 304) {
410
+ res.resume();
411
+ resolve(new Response(null, { status, statusText: res.statusMessage ?? '', headers }));
412
+ return;
413
+ }
414
+ resolve(new Response(Readable.toWeb(res), {
415
+ status,
416
+ statusText: res.statusMessage ?? '',
417
+ headers,
418
+ }));
419
+ });
420
+ req.once('error', fail);
421
+ req.end();
422
+ });
423
+ }
424
+ const htmlEntities = {
425
+ amp: '&',
426
+ lt: '<',
427
+ gt: '>',
428
+ quot: '"',
429
+ apos: "'",
430
+ nbsp: ' ',
431
+ mdash: '—',
432
+ ndash: '–',
433
+ hellip: '…',
434
+ lsquo: '‘',
435
+ rsquo: '’',
436
+ ldquo: '“',
437
+ rdquo: '”',
438
+ };
439
+ function cleanHtml(html) {
440
+ return html
441
+ .replace(/<!--[\s\S]*?(?:-->|$)/g, ' ')
442
+ .replace(/<(script|style|noscript|head)\b(?:"[^"]*"|'[^']*'|[^'"<>])*>[\s\S]*?(?:<\/\1\s*>|$)/gi, ' ')
443
+ .replace(/<\/?[a-z!](?:"[^"]*"|'[^']*'|[^'"<>])*>/gi, ' ')
444
+ .replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (entity, name) => {
445
+ if (!name.startsWith('#'))
446
+ return Object.hasOwn(htmlEntities, name) ? htmlEntities[name] : entity;
447
+ const hex = name[1]?.toLowerCase() === 'x';
448
+ const code = Number.parseInt(name.slice(hex ? 2 : 1), hex ? 16 : 10);
449
+ return code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff)
450
+ ? String.fromCodePoint(code)
451
+ : '\uFFFD';
452
+ });
453
+ }
454
+ export function truncateWebText(text, limit) {
455
+ return text.slice(0, limit).replace(/[\uD800-\uDBFF]$/, '');
456
+ }
457
+ function escapeMarkup(text) {
458
+ return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
459
+ }
460
+ export async function fetchPublicPage(input, maxChars, signal, redact, options = {}) {
461
+ let url = new URL(input);
462
+ const env = options.env ?? process.env;
463
+ for (let redirects = 0;; redirects++) {
464
+ url.hash = '';
465
+ const proxy = resolveEnvProxy(url, env);
466
+ let dispatcher;
467
+ try {
468
+ let response;
469
+ if (proxy) {
470
+ validatePublicUrl(url);
471
+ if (globalThis.fetch === originalFetch) {
472
+ const { Ctor, kind } = await ensureNativeDispatcherClass();
473
+ if (kind === 'EnvHttpProxyAgent') {
474
+ dispatcher = new Ctor({
475
+ ...(proxy.httpProxy ? { httpProxy: proxy.httpProxy } : {}),
476
+ ...(proxy.httpsProxy ? { httpsProxy: proxy.httpsProxy } : {}),
477
+ ...(proxy.noProxy ? { noProxy: proxy.noProxy } : {}),
478
+ });
479
+ const init = { dispatcher, signal, redirect: 'manual' };
480
+ response = await fetch(url, init);
481
+ }
482
+ else {
483
+ response = await fetchViaNodeProxy(url, proxy.proxyUrl, signal);
484
+ }
485
+ }
486
+ else {
487
+ response = await fetch(url, { signal, redirect: 'manual' });
488
+ }
489
+ }
490
+ else {
491
+ const addresses = await publicAddresses(url, signal, options.allowFakeIp ?? true);
492
+ dispatcher = await pinnedDispatcher(addresses);
493
+ const init = { dispatcher, signal, redirect: 'manual' };
494
+ response = await fetch(url, init);
495
+ }
496
+ if (redirectStatuses.has(response.status)) {
497
+ const location = response.headers.get('location');
498
+ await response.body?.cancel();
499
+ if (!location || redirects >= maxRedirects)
500
+ throw new WebFetchError('Redirect limit or invalid redirect');
501
+ url = new URL(location, url);
502
+ continue;
503
+ }
504
+ if (!response.ok) {
505
+ await response.body?.cancel();
506
+ throw new WebFetchError(`HTTP ${response.status}`);
507
+ }
508
+ const type = response.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
509
+ if (type &&
510
+ !type.startsWith('text/') &&
511
+ !/^application\/(?:json|xml|[\w.+-]+\+(?:json|xml))$/.test(type)) {
512
+ await response.body?.cancel();
513
+ throw new WebFetchError('Page did not return a text response');
514
+ }
515
+ const raw = await readWebResponse(response, maxResponseBytes);
516
+ const text = type === 'text/html' || type === 'application/xhtml+xml' ? cleanHtml(raw) : raw;
517
+ const content = truncateWebText(redact(text.replace(/\s+/g, ' ').trim()), maxChars);
518
+ const source = escapeMarkup(redact(url.href)).replaceAll('"', '&quot;');
519
+ return ('<untrusted_web_content source="' +
520
+ source +
521
+ '">\n' +
522
+ escapeMarkup(content) +
523
+ '\n</untrusted_web_content>');
524
+ }
525
+ finally {
526
+ await dispatcher?.destroy();
527
+ }
528
+ }
529
+ }
@@ -0,0 +1,10 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { ToolBinding } from '@saturn-universe/core';
3
+ import type { WebSearchConfig } from '../../user-config.js';
4
+ export declare const webToolNames: Set<string>;
5
+ export declare function createWebToolBindings(config?: WebSearchConfig, apiKey?: string): readonly ToolBinding[];
6
+ export declare function createWebSearchToolsPlugin(config: WebSearchConfig, apiKey: string): {
7
+ name: string;
8
+ inject: string[];
9
+ apply(ctx: Context, startupSignal: AbortSignal): Promise<void>;
10
+ };