@qlairoslabs/acp-client 0.13.1-alpha.1 → 0.13.2-alpha.1

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 (105) hide show
  1. package/CONSUMER_GUIDE.md +60 -26
  2. package/package.json +5 -1
  3. package/src/agent/config.ts +2 -0
  4. package/src/agent/native-operations.ts +1 -0
  5. package/src/agent-session.ts +11 -2
  6. package/src/agent.ts +4 -1
  7. package/src/index.ts +2 -0
  8. package/src/native/capabilities.ts +2 -2
  9. package/src/native/connection.ts +1 -1
  10. package/src/native/controller.ts +2 -1
  11. package/src/native/host-config.ts +2 -0
  12. package/src/native/host.ts +10 -0
  13. package/src/native/mcp.ts +47 -0
  14. package/src/native/recovery.ts +8 -7
  15. package/src/native/reminders/routine-guard.ts +4 -3
  16. package/src/native/reminders/routine-wire.ts +1 -1
  17. package/src/native-harness/README.md +58 -1
  18. package/src/native-harness/package.json +4 -0
  19. package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
  20. package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
  21. package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
  22. package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
  23. package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
  24. package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
  25. package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
  26. package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
  27. package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
  28. package/src/native-harness/src/capabilities/context/build.ts +5 -0
  29. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
  30. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  31. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  32. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  33. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  34. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  35. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  36. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  37. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  38. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  39. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  40. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  41. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  42. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  43. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  44. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  45. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  46. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  47. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  48. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  49. package/src/native-harness/src/contracts/agent.ts +3 -1
  50. package/src/native-harness/src/contracts/attachments.ts +62 -0
  51. package/src/native-harness/src/contracts/config-permissions.ts +13 -4
  52. package/src/native-harness/src/contracts/context.ts +1 -1
  53. package/src/native-harness/src/contracts/events.ts +2 -2
  54. package/src/native-harness/src/contracts/loop.ts +3 -3
  55. package/src/native-harness/src/contracts/mcp.ts +22 -0
  56. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  57. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  58. package/src/native-harness/src/contracts/protocol.ts +20 -4
  59. package/src/native-harness/src/contracts/session-file.ts +2 -1
  60. package/src/native-harness/src/contracts/session.ts +6 -1
  61. package/src/native-harness/src/contracts/storage.ts +23 -5
  62. package/src/native-harness/src/contracts/tools.ts +2 -0
  63. package/src/native-harness/src/contracts/web.ts +16 -0
  64. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  65. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  66. package/src/native-harness/src/index.ts +43 -11
  67. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  68. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  69. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  70. package/src/native-harness/src/interfaces/client.ts +8 -2
  71. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  72. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  73. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  74. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  75. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  76. package/src/native-harness/src/interfaces/protocol/server.ts +93 -29
  77. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +1 -0
  78. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  79. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  80. package/src/native-harness/src/kernel/channels.ts +19 -11
  81. package/src/native-harness/src/kernel/loop.ts +1 -1
  82. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  83. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  84. package/src/native-harness/src/runtime/config/paths.ts +3 -2
  85. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  86. package/src/native-harness/src/state/storage/archive.ts +95 -12
  87. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  88. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  89. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  90. package/src/native-harness/src/state/storage/engine.ts +194 -34
  91. package/src/native-harness/src/state/storage/inference.ts +30 -2
  92. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  93. package/src/native-harness/src/state/storage/memory.ts +18 -3
  94. package/src/native-harness/src/state/storage/reminder-archive.ts +2 -2
  95. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  96. package/src/native-harness/src/state/storage/sqlite.ts +51 -10
  97. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  98. package/src/native-harness/src/testing.ts +150 -55
  99. package/src/native-harness/src/util/attachment-input.ts +42 -0
  100. package/src/native-harness/src/util/config.ts +59 -12
  101. package/src/native-harness/src/util/mcp-config.ts +102 -0
  102. package/src/native-harness/src/util/web-config.ts +34 -0
  103. package/src/native-harness/src/util/web-usage.ts +33 -0
  104. package/src/steering/combine.ts +1 -0
  105. package/src/steering/contracts.ts +3 -0
@@ -0,0 +1,28 @@
1
+ /** Lifetime is one connection. Values never leave this closure. */
2
+ export function mcpSecrets(values: readonly string[]) {
3
+ const secrets = [...new Set(values.filter(Boolean))].sort((a, b) => b.length - a.length);
4
+ const contains = (text: string) => secrets.some(secret => text.includes(secret));
5
+ const pattern = secrets.length ? new RegExp(secrets.map(secret => secret.replace(/[.*+?^$\{\}()|[\]\\]/g, "\\$&")).join("|"), "g") : undefined;
6
+ function text(value: string): string {
7
+ if (!pattern) return value;
8
+ const projected = value.replace(pattern, "[redacted]");
9
+ // Overlapping matches or short credentials can make the marker unsafe.
10
+ if (contains(projected)) throw new Error("MCP output could not be safely redacted");
11
+ return projected;
12
+ }
13
+ function tree(value: unknown, checkOnly = false, depth = 0): unknown {
14
+ if (depth > 64) throw new Error("MCP output nesting exceeds limit");
15
+ if (typeof value === "string") {
16
+ if (!checkOnly) return text(value);
17
+ if (contains(value)) throw new Error("MCP definition contains credential material");
18
+ return value;
19
+ }
20
+ if (Array.isArray(value)) return value.map(item => tree(item, checkOnly, depth + 1));
21
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
22
+ if (contains(key)) throw new Error("MCP output key contains credential material");
23
+ return [key, tree(entry, checkOnly, depth + 1)];
24
+ }));
25
+ return value;
26
+ }
27
+ return { contains, text, tree };
28
+ }
@@ -0,0 +1,105 @@
1
+ // Runner-owned streams implement the SDK transport interface without giving
2
+ // the SDK authority to launch or inherit the harness environment.
3
+ export interface McpStdioProcess {
4
+ stdout: ReadableStream<Uint8Array>;
5
+ write(frame: Uint8Array): Promise<void>;
6
+ close(): Promise<void>;
7
+ }
8
+
9
+ const frameLimit = 256 * 1024;
10
+
11
+ export class McpStdioTransport<Message> {
12
+ onmessage?: (message: Message) => void;
13
+ onerror?: (error: Error) => void;
14
+ onclose?: () => void;
15
+ #started = false;
16
+ #closing?: Promise<void>;
17
+ #sends = Promise.resolve();
18
+ readonly #process: McpStdioProcess;
19
+
20
+ constructor(process: McpStdioProcess, private readonly revisions?: ReadonlySet<string>,
21
+ private readonly parse?: (value: unknown) => Message) {
22
+ this.#process = process;
23
+ }
24
+
25
+ setProtocolVersion(version: string) {
26
+ if (this.revisions && !this.revisions.has(version)) throw new Error("Unsupported MCP protocol revision");
27
+ }
28
+
29
+ async start(): Promise<void> {
30
+ if (this.#started || this.#closing) throw new Error("MCP transport already started or closed");
31
+ this.#started = true;
32
+ void this.#receive();
33
+ }
34
+
35
+ async #receive() {
36
+ const reader = this.#process.stdout.getReader();
37
+ const frame = new Uint8Array(frameLimit);
38
+ const decoder = new TextDecoder("utf-8", { fatal: true });
39
+ let size = 0;
40
+ try {
41
+ while (!this.#closing) {
42
+ const read = await reader.read();
43
+ if (read.done) {
44
+ if (size) throw new Error("Incomplete MCP frame");
45
+ break;
46
+ }
47
+ const chunk = read.value;
48
+ for (let start = 0; start < chunk.length;) {
49
+ const newline = chunk.indexOf(10, start);
50
+ const end = newline < 0 ? chunk.length : newline;
51
+ const length = end - start;
52
+ if (size + length > frameLimit) throw new Error("MCP frame too large");
53
+ frame.set(chunk.subarray(start, end), size);
54
+ size += length;
55
+ if (newline >= 0) {
56
+ const message: unknown = JSON.parse(decoder.decode(frame.subarray(0, size)));
57
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
58
+ throw new Error("Invalid MCP message");
59
+ }
60
+ this.onmessage?.(this.parse ? this.parse(message) : message as Message);
61
+ size = 0;
62
+ }
63
+ start = end + 1;
64
+ }
65
+ }
66
+ } catch {
67
+ if (!this.#closing) this.onerror?.(new Error("Invalid MCP stdio stream"));
68
+ } finally {
69
+ reader.releaseLock();
70
+ await this.close().catch(() => this.onerror?.(new Error("MCP stdio cleanup failed")));
71
+ }
72
+ }
73
+
74
+ send(message: Message): Promise<void> {
75
+ const frame = new TextEncoder().encode(JSON.stringify(message) + "\n");
76
+ if (frame.length > frameLimit + 1) return Promise.reject(new Error("MCP frame too large"));
77
+ const write = this.#sends.then(async () => {
78
+ if (!this.#started || this.#closing) throw new Error("MCP transport is closed");
79
+ const stop = AbortSignal.timeout(250);
80
+ const writeDeadline = new Promise<never>((_, reject) => {
81
+ stop.addEventListener("abort", () => reject(new Error("MCP stdio write timed out")), { once: true });
82
+ });
83
+ try {
84
+ await Promise.race([this.#process.write(frame), writeDeadline]);
85
+ } catch (error) {
86
+ void this.close().catch(() => {});
87
+ throw error;
88
+ }
89
+ });
90
+ this.#sends = write.catch(() => {});
91
+ return write;
92
+ }
93
+
94
+ async drain(): Promise<void> { await this.#sends; }
95
+
96
+ close(): Promise<void> {
97
+ return this.#closing ??= Promise.resolve().then(async () => {
98
+ try {
99
+ await this.#process.close();
100
+ } finally {
101
+ this.onclose?.();
102
+ }
103
+ });
104
+ }
105
+ }
@@ -1,3 +1,4 @@
1
+ import { webUsageView } from "../../../util/web-usage.ts";
1
2
  import type { StorageSnapshot } from "../../../contracts/storage.ts";
2
3
  import type { ToolInvocation } from "../../../contracts/tools.ts";
3
4
 
@@ -21,7 +22,9 @@ export function turnInvocations(view: StorageSnapshot, turnId: number, waiting:
21
22
  if (entry.turnId !== turnId || entry.message.role !== "assistant") continue;
22
23
  for (const call of entry.message.calls) {
23
24
  const id = invocationId(turnId, call.id), result = results.get(call.id);
24
- const base = { invocationId: id, channel: turn.channelId, turnId: String(turnId), toolCallId: call.id, tool: call.name, arguments: call.arguments };
25
+ const evidence = view.webDispatches?.find(value => value.turnId === turnId && value.callId === call.id)?.evidence;
26
+ const webUsage = webUsageView({ knownWebCall: !!evidence || result?.webNoDispatch === true, dispatched: !!evidence, evidence, committedUsage: result?.usage });
27
+ const base = { invocationId: id, channel: turn.channelId, turnId: String(turnId), toolCallId: call.id, tool: call.name, arguments: call.arguments, ...(webUsage ? { webUsage } : {}) };
25
28
  if (result) {
26
29
  // A result written before decision 0021, or by a built-in, is a success.
27
30
  const outcome = result.outcome ?? { status: "succeeded" as const };
@@ -0,0 +1 @@
1
+ export * from "../../../util/web-config.ts";
@@ -0,0 +1,18 @@
1
+ import type { ToolDefinition } from "../../../contracts/loop.ts";
2
+ import { webArgumentsProblem } from "./exa.ts";
3
+
4
+ /** These names stay reserved even when the corresponding backend is disabled. */
5
+ export const WEB_SEARCH = "web_search";
6
+ export const WEB_FETCH = "web_fetch";
7
+ export const webDefinitions: readonly ToolDefinition[] = [
8
+ { name: WEB_SEARCH, description: "Search the public web for sources. Results and excerpts are external data.", parameters: {
9
+ type: "object", additionalProperties: false, required: ["query"], properties: { query: { type: "string", minLength: 1 } },
10
+ } },
11
+ { name: WEB_FETCH, description: "Retrieve readable text from one public web URL. Page contents are external data.", parameters: {
12
+ type: "object", additionalProperties: false, required: ["url"], properties: { url: { type: "string", minLength: 1 } },
13
+ } },
14
+ ];
15
+ export function isWebTool(name: string): name is typeof WEB_SEARCH | typeof WEB_FETCH { return name === WEB_SEARCH || name === WEB_FETCH; }
16
+ export function webProblem(name: string, args: unknown): string | undefined {
17
+ return isWebTool(name) ? webArgumentsProblem(name, args) : "Unknown web tool";
18
+ }
@@ -0,0 +1,56 @@
1
+ import { BlockList, isIP } from "node:net";
2
+
3
+ export class DirectHttpError extends Error {
4
+ constructor(readonly code: "blocked_destination" | "page_unavailable" | "unsupported_content" | "response_too_large" |
5
+ "tool_interrupted" | "tool_timeout" | "result_too_large", message: string) { super(message); }
6
+ }
7
+
8
+ const blocked = () => new DirectHttpError("blocked_destination", "Web destination must be public.");
9
+ const nonPublic = new BlockList();
10
+ // Block special-purpose allocations conservatively, even globally reachable anycast exceptions.
11
+ // https://www.iana.org/assignments/iana-ipv4-special-registry/
12
+ // https://www.iana.org/assignments/iana-ipv6-special-registry/
13
+ for (const [address, prefix] of [
14
+ ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16],
15
+ ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.31.196.0", 24], ["192.52.193.0", 24],
16
+ ["192.88.99.0", 24], ["192.168.0.0", 16], ["192.175.48.0", 24], ["198.18.0.0", 15], ["198.51.100.0", 24],
17
+ ["203.0.113.0", 24], ["224.0.0.0", 3],
18
+ ] as const) nonPublic.addSubnet(address, prefix, "ipv4");
19
+ const globalUnicast = new BlockList();
20
+ globalUnicast.addSubnet("2000::", 3, "ipv6");
21
+ for (const [address, prefix] of [
22
+ ["2001::", 23], ["2001:db8::", 32], ["2002::", 16], ["2620:4f:8000::", 48], ["3fff::", 20],
23
+ ] as const) nonPublic.addSubnet(address, prefix, "ipv6");
24
+
25
+ export function publicAddress(address: string): 4 | 6 {
26
+ const family = isIP(address);
27
+ if (family === 4 && !nonPublic.check(address, "ipv4")) return family;
28
+ if (family === 6 && globalUnicast.check(address, "ipv6") && !nonPublic.check(address, "ipv6")) return family;
29
+ throw blocked();
30
+ }
31
+
32
+ export function directHostname(url: URL) {
33
+ return url.hostname.replace(/^\[|\]$/g, "");
34
+ }
35
+
36
+ export function directUrl(input: string, previous?: URL): URL {
37
+ if (!input || Buffer.byteLength(input) > 2048 || /[\x00-\x20\x7f\s\\#]/.test(input)) throw blocked();
38
+ const authority = /^(?:https?:)?\/\/([^/?]+)/i.exec(input)?.[1];
39
+ if ((!previous && !/^https?:\/\//i.test(input)) || (authority === undefined && /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(input))
40
+ || authority?.includes("@") || authority?.includes("%")) throw blocked();
41
+ let url: URL;
42
+ try { url = new URL(input, previous); } catch { throw blocked(); }
43
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password || url.hash ||
44
+ (previous?.protocol === "https:" && url.protocol !== "https:") || Buffer.byteLength(url.href) > 2048) throw blocked();
45
+ const host = directHostname(url);
46
+ const family = isIP(host);
47
+ if (family) {
48
+ const rawHost = authority?.replace(/:\d+$/, "");
49
+ if (family === 4 && authority !== undefined && rawHost !== host) throw blocked();
50
+ if (family === 6 && authority !== undefined && !rawHost?.startsWith("[")) throw blocked();
51
+ publicAddress(host);
52
+ } else if (!host.includes(".") || /(?:^|\.)(?:localhost|local|internal|onion|test|invalid|example|home\.arpa)\.?$/i.test(host)) {
53
+ throw blocked();
54
+ }
55
+ return url;
56
+ }
@@ -0,0 +1,235 @@
1
+ import { Resolver } from "node:dns/promises";
2
+ import { Readable } from "node:stream";
3
+ import { BlockList, connect, isIP, type Socket } from "node:net";
4
+ import { checkServerIdentity, connect as connectTls, type TLSSocket } from "node:tls";
5
+ import { DirectHttpError, directHostname, publicAddress } from "./direct-address.ts";
6
+
7
+ export interface DirectSocketTarget {
8
+ address: string;
9
+ family: 4 | 6;
10
+ port: number;
11
+ hostname: string;
12
+ secure: boolean;
13
+ }
14
+
15
+ /** The fixture seam supplies candidates, not a bypass around destination checks. */
16
+ export interface DirectTransportDependencies {
17
+ resolve(hostname: string, signal: AbortSignal): Promise<readonly string[]>;
18
+ connect(target: DirectSocketTarget, signal: AbortSignal): Promise<Socket>;
19
+ }
20
+
21
+ async function resolve(hostname: string, signal: AbortSignal): Promise<string[]> {
22
+ signal.throwIfAborted();
23
+ const resolver = new Resolver();
24
+ const stop = () => resolver.cancel();
25
+ const missing = (error: NodeJS.ErrnoException): string[] => {
26
+ if (error.code === "ENODATA" || error.code === "ENOTFOUND") return [];
27
+ throw error;
28
+ };
29
+ signal.addEventListener("abort", stop, { once: true });
30
+ try {
31
+ const [a, aaaa] = await Promise.all([resolver.resolve4(hostname).catch(missing), resolver.resolve6(hostname).catch(missing)]);
32
+ return [...a, ...aaaa];
33
+ } finally { signal.removeEventListener("abort", stop); resolver.cancel(); }
34
+ }
35
+
36
+ function closeSocket(socket: Socket): Promise<void> {
37
+ if (socket.closed) return Promise.resolve();
38
+ return new Promise(resolve => {
39
+ socket.once("close", resolve);
40
+ socket.destroy();
41
+ });
42
+ }
43
+
44
+ export function dialDirect(target: DirectSocketTarget, signal: AbortSignal, trustedCa?: string): Promise<Socket> {
45
+ signal.throwIfAborted();
46
+ return new Promise((resolve, reject) => {
47
+ const options = { host: target.address, family: target.family, port: target.port };
48
+ const socket = target.secure ? connectTls({
49
+ ...options, ...(isIP(target.hostname) ? {} : { servername: target.hostname }),
50
+ ALPNProtocols: ["http/1.1"], ca: trustedCa,
51
+ rejectUnauthorized: true, checkServerIdentity: (_hostname, certificate) => checkServerIdentity(target.hostname, certificate),
52
+ }) : connect(options);
53
+ const event = target.secure ? "secureConnect" : "connect";
54
+ const cleanup = () => {
55
+ socket.removeListener(event, ready);
56
+ socket.removeListener("error", failed);
57
+ signal.removeEventListener("abort", stop);
58
+ };
59
+ const ready = () => {
60
+ if (target.secure) {
61
+ const tls = socket as TLSSocket;
62
+ try {
63
+ if (!tls.authorized || checkServerIdentity(target.hostname, tls.getPeerCertificate())) {
64
+ throw new Error("Web TLS verification failed.");
65
+ }
66
+ } catch {
67
+ failed(new Error("Web TLS verification failed."));
68
+ return;
69
+ }
70
+ }
71
+ cleanup();
72
+ resolve(socket);
73
+ };
74
+ const failed = (error: Error) => {
75
+ cleanup();
76
+ void closeSocket(socket).then(() => reject(error));
77
+ };
78
+ const stop = () => failed(signal.reason);
79
+ socket.once(event, ready);
80
+ socket.once("error", failed);
81
+ signal.addEventListener("abort", stop, { once: true });
82
+ });
83
+ }
84
+
85
+ export const directTransport: DirectTransportDependencies = { resolve, connect: dialDirect };
86
+
87
+ export async function requestDirect(url: URL, signal: AbortSignal, dependencies = directTransport): Promise<DirectResponse> {
88
+ signal.throwIfAborted();
89
+ const hostname = directHostname(url);
90
+ const addresses = isIP(hostname) ? [hostname] : await dependencies.resolve(hostname, signal);
91
+ signal.throwIfAborted();
92
+ if (!addresses.length) throw new DirectHttpError("page_unavailable", "Web hostname had no addresses.");
93
+ const families = addresses.map(publicAddress);
94
+ const address = addresses[0]!, family = families[0]!, secure = url.protocol === "https:";
95
+ const port = url.port ? Number(url.port) : secure ? 443 : 80;
96
+ const socket = await dependencies.connect({ address, family, port, hostname, secure }, signal);
97
+ try {
98
+ signal.throwIfAborted();
99
+ const peer = socket.remoteAddress, type = family === 4 ? "ipv4" : "ipv6";
100
+ const exact = new BlockList();
101
+ exact.addAddress(address, type);
102
+ if (!peer || publicAddress(peer) !== family || !exact.check(peer, type) || socket.remotePort !== port)
103
+ throw new DirectHttpError("blocked_destination", "Connected peer did not match the validated destination.");
104
+ return await readPinnedResponse(socket, url, signal);
105
+ } catch (error) { await closeSocket(socket); throw error; }
106
+ }
107
+
108
+ // This stage takes ownership of the already-connected and verified socket.
109
+ export async function readPinnedResponse(socket: Socket, url: URL, signal: AbortSignal): Promise<DirectResponse> {
110
+ try {
111
+ signal.throwIfAborted();
112
+ const stop = () => socket.destroy(new Error("Web request aborted."));
113
+ signal.addEventListener("abort", stop, { once: true });
114
+ socket.once("close", () => signal.removeEventListener("abort", stop));
115
+ const reader = new ResponseReader(socket);
116
+ socket.write(`GET ${url.pathname}${url.search} HTTP/1.1\r\nHost: ${url.host}\r\nAccept: text/plain, text/html\r\nAccept-Encoding: gzip, deflate, br\r\nConnection: close\r\n\r\n`);
117
+ return await reader.response();
118
+ } catch (error) { await closeSocket(socket); throw error; }
119
+ }
120
+
121
+ interface DirectResponse {
122
+ statusCode: number;
123
+ headers: Record<string, string | undefined>;
124
+ body: Readable;
125
+ close(): Promise<void>;
126
+ }
127
+
128
+ const malformed = () => new DirectHttpError("page_unavailable", "Malformed web response.");
129
+
130
+ // Parse only the response framing required by a one-shot HTTP/1.x GET.
131
+ class ResponseReader {
132
+ readonly #iterator: AsyncIterator<Buffer>;
133
+ #buffer: Buffer = Buffer.alloc(0);
134
+ #offset = 0;
135
+
136
+ constructor(readonly socket: Socket) {
137
+ this.#iterator = socket[Symbol.asyncIterator]();
138
+ }
139
+
140
+ async #fill() {
141
+ const next = await this.#iterator.next();
142
+ this.#buffer = next.done ? Buffer.alloc(0) : next.value;
143
+ this.#offset = 0;
144
+ return !next.done;
145
+ }
146
+
147
+ async #line(limit: number): Promise<string> {
148
+ const chunks: Buffer[] = [];
149
+ let length = 0;
150
+ while (this.#offset < this.#buffer.length || await this.#fill()) {
151
+ const lf = this.#buffer.indexOf(10, this.#offset);
152
+ const end = lf < 0 ? this.#buffer.length : lf + 1;
153
+ const part = this.#buffer.subarray(this.#offset, end);
154
+ length += part.length;
155
+ if (length > limit) throw malformed();
156
+ chunks.push(part);
157
+ this.#offset = end;
158
+ if (lf >= 0) {
159
+ const line = Buffer.concat(chunks, length);
160
+ if (line.length < 2 || line[line.length - 2] !== 13) throw malformed();
161
+ return line.subarray(0, -2).toString("latin1");
162
+ }
163
+ }
164
+ throw malformed();
165
+ }
166
+
167
+ async *#bytes(count?: number) {
168
+ while (count !== 0) {
169
+ if (this.#offset === this.#buffer.length && !await this.#fill()) {
170
+ if (count !== undefined) throw malformed();
171
+ return;
172
+ }
173
+ const take = Math.min(count ?? Infinity, this.#buffer.length - this.#offset);
174
+ const part = this.#buffer.subarray(this.#offset, this.#offset + take);
175
+ this.#offset += take;
176
+ if (count !== undefined) count -= take;
177
+ yield part;
178
+ }
179
+ }
180
+
181
+ async *#body(mode: "chunked" | "fixed", size?: number) {
182
+ try {
183
+ if (mode === "fixed") { yield* this.#bytes(size); return; }
184
+ let framing = 0;
185
+ for (;;) {
186
+ const line = await this.#line(1024);
187
+ framing += line.length + 4;
188
+ if (framing > 64 * 1024) throw malformed();
189
+ const hex = /^([0-9a-f]+)(?:;[^\x00-\x1f\x7f]*)?$/i.exec(line)?.[1];
190
+ const bytes = hex === undefined ? NaN : parseInt(hex, 16);
191
+ if (!Number.isSafeInteger(bytes)) throw malformed();
192
+ if (bytes === 0) { await this.#headers(); return; }
193
+ yield* this.#bytes(bytes);
194
+ if (await this.#line(2) !== "") throw malformed();
195
+ }
196
+ } finally { await closeSocket(this.socket); }
197
+ }
198
+
199
+ async #headers() {
200
+ const headers: Record<string, string | undefined> = Object.create(null);
201
+ let remaining = 16 * 1024;
202
+ for (;;) {
203
+ const line = await this.#line(remaining);
204
+ remaining -= line.length + 2;
205
+ if (line === "") return headers;
206
+ const match = /^([!#$%&'*+.^_`|~\w-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(line);
207
+ if (!match) throw malformed();
208
+ const name = match[1]!.toLowerCase();
209
+ if (headers[name] !== undefined && ["content-length", "transfer-encoding", "location", "content-encoding", "content-type"].includes(name)) throw malformed();
210
+ headers[name] = match[2]!.trim();
211
+ }
212
+ }
213
+
214
+ async response(): Promise<DirectResponse> {
215
+ let statusCode: number;
216
+ let headers: Record<string, string | undefined>;
217
+ for (let informational = 0; ; informational++) {
218
+ const status = /^HTTP\/1\.[01] ([1-5][0-9]{2})(?: [^\r\n]*)?$/.exec(await this.#line(1024));
219
+ if (!status || informational === 5) throw malformed();
220
+ statusCode = Number(status[1]);
221
+ headers = await this.#headers();
222
+ if (statusCode >= 200) break;
223
+ if (statusCode === 101) throw malformed();
224
+ }
225
+ const transfer = headers["transfer-encoding"]?.toLowerCase();
226
+ const length = headers["content-length"];
227
+ if (transfer !== undefined && (transfer !== "chunked" || length !== undefined)) throw malformed();
228
+ if (length !== undefined && (!/^\d+$/.test(length) || !Number.isSafeInteger(Number(length)))) throw malformed();
229
+ const empty = statusCode === 204 || statusCode === 304;
230
+ const body = Readable.from(this.#body(!empty && transfer === "chunked" ? "chunked" : "fixed",
231
+ empty ? 0 : length === undefined ? undefined : Number(length)), { objectMode: false });
232
+ body.once("close", () => this.socket.destroy());
233
+ return { statusCode, headers, body, close: () => closeSocket(this.socket) };
234
+ }
235
+ }
@@ -0,0 +1,149 @@
1
+ import { PassThrough, Transform, Writable } from "node:stream";
2
+ import { pipeline } from "node:stream/promises";
3
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
4
+ import { DirectHttpError, directUrl } from "./direct-address.ts";
5
+ import { requestDirect, type DirectTransportDependencies } from "./direct-transport.ts";
6
+
7
+ const rawLimit = 2 * 1024 * 1024, decodedLimit = 4 * 1024 * 1024, previewLimit = 2048;
8
+ const tooLarge = () => new DirectHttpError("response_too_large", "Web response exceeded the transfer limit.");
9
+
10
+ async function boundedBody(response: Awaited<ReturnType<typeof requestDirect>>, signal: AbortSignal, discard: boolean): Promise<Buffer> {
11
+ let received = 0, decoded = 0;
12
+ const chunks: Buffer[] = [];
13
+ const encoding = response.headers["content-encoding"]?.trim().toLowerCase();
14
+ const decoder = encoding === "gzip" ? createGunzip() : encoding === "deflate" ? createInflate()
15
+ : encoding === "br" ? createBrotliDecompress() : encoding === undefined || encoding === "identity" ? new PassThrough() : undefined;
16
+ if (!decoder) {
17
+ response.body.destroy();
18
+ await response.close();
19
+ throw new DirectHttpError("unsupported_content", "Unsupported response encoding.");
20
+ }
21
+ const count = new Transform({ transform(chunk: Buffer, _encoding, callback) {
22
+ received += chunk.length;
23
+ callback(received > rawLimit ? tooLarge() : null, chunk);
24
+ } });
25
+ const collect = new Writable({ write(chunk: Buffer, _encoding, callback) {
26
+ decoded += chunk.length;
27
+ if (decoded > decodedLimit) { callback(tooLarge()); return; }
28
+ if (!discard) chunks.push(chunk);
29
+ callback();
30
+ } });
31
+ try {
32
+ await pipeline(response.body, count, decoder, collect, { signal });
33
+ } finally {
34
+ await response.close();
35
+ }
36
+ return Buffer.concat(chunks, discard ? 0 : decoded);
37
+ }
38
+
39
+ const entity = (text: string) => text.replace(/&(#x[\da-fA-F]{1,6}|#\d{1,7}|amp|lt|gt|quot|apos|nbsp);/g, (raw, code: string) => {
40
+ if (code.startsWith("#")) {
41
+ const scalar = code[1] === "x" ? parseInt(code.slice(2), 16) : Number(code.slice(1));
42
+ return scalar > 0 && scalar <= 0x10ffff && (scalar < 0xd800 || scalar > 0xdfff) ? String.fromCodePoint(scalar) : "�";
43
+ }
44
+ return ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " } as Record<string, string>)[code] ?? raw;
45
+ });
46
+
47
+ function readableHtml(input: string) {
48
+ const output: string[] = [], title: string[] = [];
49
+ const excluded = new Set(["script", "style", "head", "nav", "footer", "noscript", "template", "svg"]);
50
+ const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[a-z][^<>]*>/gi;
51
+ let hidden: string | undefined, inTitle = false, offset = 0;
52
+ for (const match of input.matchAll(tags)) {
53
+ const text = input.slice(offset, match.index);
54
+ if (inTitle) title.push(text);
55
+ else if (!hidden) output.push(text);
56
+ const name = /^<(\/?)([a-z][\w:-]*)/i.exec(match[0]);
57
+ const tag = name?.[2]?.toLowerCase();
58
+ if (tag === "title") inTitle = !name?.[1];
59
+ if (tag && excluded.has(tag) && !name?.[1] && !hidden) hidden = tag;
60
+ if (tag === hidden && name?.[1]) hidden = undefined;
61
+ if (!hidden && ["br", "p", "div", "li", "section", "article", "h1", "h2", "h3", "tr"].includes(tag ?? "")) output.push("\n");
62
+ offset = match.index + match[0].length;
63
+ }
64
+ if (!hidden) output.push(input.slice(offset));
65
+ const clean = (text: string) => entity(text).replace(/[^\S\n]+/g, " ").replace(/\n(?:\s*\n)+/g, "\n").trim();
66
+ return { title: clean(title.join("")) || null, text: clean(output.join("")) };
67
+ }
68
+
69
+ interface DirectPage { url: string; title: string | null; text: string; truncated: boolean; coverage: "full" | "unknown" }
70
+
71
+ function preview(page: DirectPage): string {
72
+ const fits = () => Buffer.byteLength(JSON.stringify(page)) <= previewLimit;
73
+ if (fits()) return JSON.stringify(page);
74
+ page.truncated = true;
75
+ function shorten(field: "title" | "text") {
76
+ const units: string[] = [];
77
+ for (const scalar of page[field] ?? "") {
78
+ if (units.length === previewLimit) break;
79
+ units.push(scalar);
80
+ }
81
+ const set = (count: number) => { const value = units.slice(0, count).join("");
82
+ if (field === "title") page.title = value || null;
83
+ else page.text = value; };
84
+ set(0);
85
+ if (!fits()) return;
86
+ let lower = 0, upper = units.length;
87
+ while (lower < upper) {
88
+ const mid = Math.ceil((lower + upper) / 2);
89
+ set(mid);
90
+ if (fits()) lower = mid; else upper = mid - 1;
91
+ }
92
+ set(lower);
93
+ }
94
+ if (page.title !== null) shorten("title");
95
+ if (!fits()) shorten("text");
96
+ if (!fits()) throw new DirectHttpError("result_too_large", "The source URL does not fit the result budget.");
97
+ return JSON.stringify(page);
98
+ }
99
+
100
+ export async function fetchDirect(input: string, deadlineMs: number, signal: AbortSignal, dependencies?: DirectTransportDependencies): Promise<string> {
101
+ const expiresAt = performance.now() + deadlineMs;
102
+ const deadline = AbortSignal.timeout(deadlineMs);
103
+ const stop = AbortSignal.any([signal, deadline]);
104
+ try {
105
+ let url = directUrl(input);
106
+ const source = url.href;
107
+ const seen = new Set<string>();
108
+ for (let hops = 0; ; hops++) {
109
+ if (seen.has(url.href)) throw new DirectHttpError("blocked_destination", "Web redirect loop refused.");
110
+ seen.add(url.href);
111
+ const response = await requestDirect(url, stop, dependencies);
112
+ const status = response.statusCode ?? 0;
113
+ if ([301, 302, 303, 307, 308].includes(status)) {
114
+ await boundedBody(response, stop, true);
115
+ if (hops === 5 || !response.headers.location) throw new DirectHttpError("blocked_destination", "Web redirect refused.");
116
+ url = directUrl(response.headers.location, url);
117
+ continue;
118
+ }
119
+ if (status < 200 || status >= 300 || status === 206) {
120
+ await boundedBody(response, stop, true);
121
+ throw new DirectHttpError("page_unavailable", "Web server did not return a successful page.");
122
+ }
123
+ const [mime, ...parameters] = (response.headers["content-type"] ?? "").toLowerCase().split(";");
124
+ const charset = parameters.map(part => part.trim()).find(part => part.startsWith("charset="))?.slice(8).replace(/^"|"$/g, "") ?? "utf-8";
125
+ const bytes = await boundedBody(response, stop, false);
126
+ if (!["text/html", "text/plain"].includes(mime!.trim()) || !["utf-8", "utf8", "us-ascii", "iso-8859-1", "windows-1252"].includes(charset))
127
+ throw new DirectHttpError("unsupported_content", "Only HTML and plain text in supported charsets are readable.");
128
+ let decoded: string;
129
+ try {
130
+ if (charset === "us-ascii" && bytes.some(byte => byte > 127)) throw new Error();
131
+ decoded = new TextDecoder(charset === "windows-1252" || charset === "iso-8859-1" ? "windows-1252" : "utf-8", { fatal: true }).decode(bytes);
132
+ } catch { throw new DirectHttpError("unsupported_content", "Web response cannot be decoded."); }
133
+ const html = mime!.trim() === "text/html";
134
+ const result = html ? readableHtml(decoded) : { title: null, text: decoded.trim() };
135
+ if (!result.text) throw new DirectHttpError("page_unavailable", "Web page has no readable text.");
136
+ const framed = response.headers["content-length"] !== undefined || response.headers["transfer-encoding"] !== undefined;
137
+ const coverage = html || !framed ? "unknown" : "full";
138
+ const output = preview({ ...result, url: source, truncated: false, coverage });
139
+ stop.throwIfAborted();
140
+ if (performance.now() >= expiresAt) throw new DirectHttpError("tool_timeout", "Web fetch deadline exceeded.");
141
+ return output;
142
+ }
143
+ } catch (error) {
144
+ if (signal.aborted) throw new DirectHttpError("tool_interrupted", "Web fetch interrupted.");
145
+ if (deadline.aborted) throw new DirectHttpError("tool_timeout", "Web fetch deadline exceeded.");
146
+ if (error instanceof DirectHttpError) throw error;
147
+ throw new DirectHttpError("page_unavailable", "Web destination could not be read.");
148
+ }
149
+ }
@@ -0,0 +1,41 @@
1
+ import { request } from "node:https";
2
+ import { Transform, Writable, type TransformCallback } from "node:stream";
3
+ import { pipeline } from "node:stream/promises";
4
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
5
+ import type { ExaTransport } from "./exa.ts";
6
+
7
+ const cap = 2 * 1024 * 1024;
8
+ export class ExaResponseLimit extends Error {}
9
+ /** Streaming transform limits input before any decompressing allocation. */
10
+ export function boundedBytes(max: number): Transform {
11
+ let total = 0;
12
+ return new Transform({ transform(chunk: Buffer, _encoding: BufferEncoding, done: TransformCallback) {
13
+ total += chunk.length;
14
+ if (total > max) done(new ExaResponseLimit("Exa response exceeds size limit")); else done(null, chunk);
15
+ } });
16
+ }
17
+ /** Fixed Exa origin: no redirects, proxy forwarding, cookies or source-site secrets. */
18
+ /** Injection is an assembly-only offline test seam, not managed configuration. */
19
+ export function createExaHttpsTransport(send: typeof request = request): ExaTransport {
20
+ return ({ path, key, body, signal }) => new Promise((resolve, reject) => {
21
+ const payload = JSON.stringify(body);
22
+ const req = send({ protocol: "https:", hostname: "api.exa.ai", port: 443, method: "POST", path, signal,
23
+ headers: { "content-type": "application/json", "accept": "application/json", "accept-encoding": "gzip, deflate, br", "content-length": Buffer.byteLength(payload), "x-api-key": key } }, async response => {
24
+ const status = response.statusCode ?? 0;
25
+ const encoding = response.headers["content-encoding"]?.trim().toLowerCase() ?? "identity";
26
+ const decoder = encoding === "gzip" ? createGunzip() : encoding === "deflate" ? createInflate() : encoding === "br" ? createBrotliDecompress() : undefined;
27
+ if (!decoder && encoding !== "identity") { response.destroy(); reject(new Error("Unsupported Exa content encoding")); return; }
28
+ const chunks: Buffer[] = [];
29
+ const sink = new Writable({ write(chunk: Buffer, _encoding, done) { chunks.push(chunk); done(); } });
30
+ try {
31
+ if (decoder) await pipeline(response, boundedBytes(cap), decoder, boundedBytes(cap), sink, { signal });
32
+ else await pipeline(response, boundedBytes(cap), boundedBytes(cap), sink, { signal });
33
+ let parsed: unknown; try { parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { parsed = undefined; }
34
+ resolve({ status, body: parsed });
35
+ } catch (error) { reject(error); }
36
+ });
37
+ req.on("error", reject);
38
+ req.end(payload);
39
+ });
40
+ }
41
+ export const exaHttpsTransport = createExaHttpsTransport();