code60-transmission-server 0.1.0-staging.2 → 0.1.0-staging.20

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 (94) hide show
  1. package/INTENT.md +47 -0
  2. package/README.md +58 -253
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +108 -0
  5. package/dist/src/engine.js +596 -0
  6. package/dist/src/main.js +72 -22
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +188 -0
  9. package/package.json +16 -32
  10. package/reference/openapi.json +834 -0
  11. package/README.engine.md +0 -401
  12. package/dist/src/broker/filesystem.js +0 -385
  13. package/dist/src/broker/index.js +0 -734
  14. package/dist/src/broker/native/README.md +0 -192
  15. package/dist/src/broker/native/build.js +0 -43
  16. package/dist/src/broker/native/fs-helper.c +0 -529
  17. package/dist/src/broker/native/git-helper.c +0 -205
  18. package/dist/src/broker/policy.js +0 -149
  19. package/dist/src/broker/startup-lock.js +0 -14
  20. package/dist/src/broker/types.js +0 -11
  21. package/dist/src/cli/daemon.js +0 -365
  22. package/dist/src/cli/helpers.js +0 -104
  23. package/dist/src/cli/main.js +0 -180
  24. package/dist/src/config/deployment.js +0 -163
  25. package/dist/src/config/documents.js +0 -29
  26. package/dist/src/config/profile-validation.js +0 -123
  27. package/dist/src/config/schema-graph.js +0 -237
  28. package/dist/src/config/schema-loader.js +0 -185
  29. package/dist/src/config/validation-pool.js +0 -105
  30. package/dist/src/config/validation-protocol.js +0 -1
  31. package/dist/src/config/validation-worker.js +0 -106
  32. package/dist/src/config/workflow-language.js +0 -9
  33. package/dist/src/config/workflow-schema.json +0 -534
  34. package/dist/src/config/workflow-types.js +0 -1
  35. package/dist/src/config/workflow-validation.js +0 -95
  36. package/dist/src/engine/budgets.js +0 -50
  37. package/dist/src/engine/clocks.js +0 -27
  38. package/dist/src/engine/commands.js +0 -441
  39. package/dist/src/engine/contracts.js +0 -11
  40. package/dist/src/engine/drain-state.js +0 -31
  41. package/dist/src/engine/effective-permissions.js +0 -120
  42. package/dist/src/engine/instruction-pins.js +0 -205
  43. package/dist/src/engine/retries.js +0 -50
  44. package/dist/src/engine/state.js +0 -1
  45. package/dist/src/engine/timing.js +0 -23
  46. package/dist/src/engine/tool-observations.js +0 -87
  47. package/dist/src/engine/workflow-engine.js +0 -1807
  48. package/dist/src/mcp/catalog.js +0 -71
  49. package/dist/src/mcp/main.js +0 -24
  50. package/dist/src/mcp/server.js +0 -104
  51. package/dist/src/runtime/codex-app-server.js +0 -91
  52. package/dist/src/runtime/containment.js +0 -82
  53. package/dist/src/runtime/engine-driver.js +0 -212
  54. package/dist/src/runtime/json-line-writer.js +0 -192
  55. package/dist/src/runtime/pinned-instruction-sources.js +0 -24
  56. package/dist/src/runtime/protocol-client.js +0 -264
  57. package/dist/src/runtime/protocol-pool.js +0 -183
  58. package/dist/src/runtime/protocol-projection.js +0 -393
  59. package/dist/src/runtime/protocol-types.js +0 -1
  60. package/dist/src/runtime/protocol-worker.js +0 -18
  61. package/dist/src/runtime/provider-bridge.js +0 -288
  62. package/dist/src/runtime/provider-credentials.js +0 -41
  63. package/dist/src/runtime/provider-transport.js +0 -404
  64. package/dist/src/runtime/runtime-broker.js +0 -213
  65. package/dist/src/runtime/workspace-instructions.js +0 -120
  66. package/dist/src/runtime/workspace-view.js +0 -74
  67. package/dist/src/server/api-contract.json +0 -11078
  68. package/dist/src/server/api-types.js +0 -1
  69. package/dist/src/server/application.js +0 -38
  70. package/dist/src/server/auth.js +0 -67
  71. package/dist/src/server/broker-handlers.js +0 -242
  72. package/dist/src/server/control-plane.js +0 -50
  73. package/dist/src/server/deployment.js +0 -237
  74. package/dist/src/server/errors.js +0 -22
  75. package/dist/src/server/history-handlers.js +0 -113
  76. package/dist/src/server/http.js +0 -124
  77. package/dist/src/server/paging.js +0 -56
  78. package/dist/src/server/publication.js +0 -119
  79. package/dist/src/server/tool-event-handler.js +0 -77
  80. package/dist/src/server/workspace-handlers.js +0 -34
  81. package/dist/src/storage/coordinator.js +0 -224
  82. package/dist/src/storage/startup-lock.js +0 -71
  83. package/dist/src/storage/store.js +0 -167
  84. package/dist/src/tools/check-worker.js +0 -81
  85. package/dist/src/tools/checks.js +0 -106
  86. package/dist/src/tools/dns.js +0 -248
  87. package/dist/src/tools/http-contract.js +0 -38
  88. package/dist/src/tools/http.js +0 -358
  89. package/dist/src/tools/index.js +0 -177
  90. package/dist/src/tools/worker-check.js +0 -73
  91. package/dist/src/workspaces/git.js +0 -227
  92. package/dist/src/workspaces/index.js +0 -715
  93. package/examples/deployment.local.json +0 -22
  94. package/scripts/postinstall.mjs +0 -25
@@ -1,248 +0,0 @@
1
- import { randomBytes } from "node:crypto";
2
- import { createSocket } from "node:dgram";
3
- import { connect, isIP } from "node:net";
4
- import { normalizeHost } from "../broker/policy.js";
5
- export class NetworkToolError extends Error {
6
- code;
7
- constructor(code) {
8
- super(code);
9
- this.code = code;
10
- }
11
- }
12
- const denied = () => { throw new NetworkToolError("invalid_dns_response"); };
13
- export function numericAddress(value) {
14
- const normalized = normalizeHost(value);
15
- if (!isIP(normalized) || normalized.startsWith("::ffff:"))
16
- throw new NetworkToolError("unsupported_numeric_address");
17
- return normalized;
18
- }
19
- function question(host, type) {
20
- const id = randomBytes(2).readUInt16BE(), header = Buffer.alloc(12);
21
- header.writeUInt16BE(id);
22
- header.writeUInt16BE(0x100, 2);
23
- header.writeUInt16BE(1, 4);
24
- const labels = host.split(".").flatMap(label => [Buffer.from([Buffer.byteLength(label)]), Buffer.from(label, "ascii")]);
25
- const suffix = Buffer.from([0, 0, type, 0, 1]);
26
- return { id, packet: Buffer.concat([header, ...labels, suffix]) };
27
- }
28
- function answer(packet, host, type, id) {
29
- if (packet.length < 12 || packet.length > 65535 || packet.readUInt16BE() !== id)
30
- return denied();
31
- const flags = packet.readUInt16BE(2);
32
- if (!(flags & 0x8000) || flags & 0x7800 || flags & 0xf || packet.readUInt16BE(4) !== 1)
33
- return denied();
34
- let offset = 12;
35
- const name = (start) => {
36
- const seen = new Set(), labels = [];
37
- let at = start, next = -1;
38
- for (let depth = 0; depth < 128; depth++) {
39
- if (at >= packet.length || seen.has(at))
40
- return denied();
41
- seen.add(at);
42
- const length = packet[at++];
43
- if ((length & 0xc0) === 0xc0) {
44
- if (at >= packet.length)
45
- return denied();
46
- const target = ((length & 0x3f) << 8) | packet[at++];
47
- if (target < 12 || target >= at - 2)
48
- return denied();
49
- if (next < 0)
50
- next = at;
51
- at = target;
52
- continue;
53
- }
54
- if (length & 0xc0 || length > 63 || at + length > packet.length)
55
- return denied();
56
- if (!length)
57
- return { value: labels.join(".").toLowerCase(), next: next < 0 ? at : next };
58
- if (packet.subarray(at, at + length).some(byte => byte >= 128))
59
- return denied();
60
- const label = packet.subarray(at, at + length).toString("ascii");
61
- if (!/^[a-zA-Z0-9_-]+$/.test(label))
62
- return denied();
63
- labels.push(label);
64
- at += length;
65
- if (labels.join(".").length > 253)
66
- return denied();
67
- }
68
- return denied();
69
- };
70
- const qname = name(offset);
71
- offset = qname.next;
72
- if (qname.value !== host || offset + 4 > packet.length || packet.readUInt16BE(offset) !== type || packet.readUInt16BE(offset + 2) !== 1)
73
- return denied();
74
- offset += 4;
75
- if (flags & 0x200)
76
- return { truncated: true, addresses: [], ttl: 0 };
77
- const answers = packet.readUInt16BE(6), total = answers + packet.readUInt16BE(8) + packet.readUInt16BE(10);
78
- if (total > 128)
79
- return denied();
80
- const aliases = new Map(), records = [];
81
- for (let index = 0; index < total; index++) {
82
- const owner = name(offset);
83
- offset = owner.next;
84
- if (offset + 10 > packet.length)
85
- return denied();
86
- const kind = packet.readUInt16BE(offset), klass = packet.readUInt16BE(offset + 2), ttl = packet.readUInt32BE(offset + 4);
87
- const size = packet.readUInt16BE(offset + 8);
88
- offset += 10;
89
- const end = offset + size;
90
- if (end > packet.length)
91
- return denied();
92
- if (index < answers && klass === 1) {
93
- if (kind === 5) {
94
- const target = name(offset);
95
- if (target.next !== end || aliases.has(owner.value))
96
- return denied();
97
- aliases.set(owner.value, { target: normalizeHost(target.value), ttl });
98
- }
99
- else if (kind === type && ((type === 1 && size === 4) || (type === 28 && size === 16))) {
100
- const raw = type === 1 ? [...packet.subarray(offset, end)].join(".") :
101
- Array.from({ length: 8 }, (_, i) => packet.readUInt16BE(offset + 2 * i).toString(16)).join(":");
102
- records.push({ owner: owner.value, address: numericAddress(raw), ttl });
103
- }
104
- }
105
- offset = end;
106
- }
107
- if (offset !== packet.length)
108
- return denied();
109
- let target = host, ttl = Infinity;
110
- const seen = new Set();
111
- while (aliases.has(target)) {
112
- if (seen.has(target) || seen.size >= 8 || records.some(record => record.owner === target))
113
- return denied();
114
- seen.add(target);
115
- const alias = aliases.get(target);
116
- target = alias.target;
117
- ttl = Math.min(ttl, alias.ttl);
118
- }
119
- const selected = records.filter(record => record.owner === target);
120
- if (selected.length > 16)
121
- return denied();
122
- return { truncated: false, addresses: selected.map(record => record.address),
123
- ttl: Math.min(ttl, ...selected.map(record => record.ttl)) };
124
- }
125
- /** Only call from an already claimed resolve effect. Constructor/parsing never
126
- * use system DNS, ambient resolver configuration, proxy or implicit fallback. */
127
- export class PinnedDnsResolver {
128
- endpoint;
129
- constructor(endpoint) {
130
- this.endpoint = Object.freeze({ address: numericAddress(endpoint.address), port: endpoint.port });
131
- if (!Number.isInteger(endpoint.port) || endpoint.port < 1 || endpoint.port > 65535)
132
- throw new NetworkToolError("invalid_dns_endpoint");
133
- }
134
- async resolve(hostname, signal) {
135
- const host = normalizeHost(hostname);
136
- if (isIP(host))
137
- throw new NetworkToolError("dns_requires_hostname");
138
- const addresses = new Set();
139
- let ttl = Infinity;
140
- for (const type of [1, 28]) {
141
- const query = question(host, type);
142
- let response = answer(await this.udp(query.packet, signal), host, type, query.id);
143
- if (response.truncated)
144
- response = answer(await this.tcp(query.packet, signal), host, type, query.id);
145
- if (response.truncated)
146
- throw new NetworkToolError("truncated_tcp_dns_response");
147
- for (const address of response.addresses)
148
- addresses.add(address);
149
- if (response.addresses.length)
150
- ttl = Math.min(ttl, response.ttl * 1000);
151
- }
152
- if (!addresses.size || addresses.size > 16 || !Number.isFinite(ttl) || ttl <= 0)
153
- throw new NetworkToolError("unusable_dns_answer");
154
- return { addresses: [...addresses].sort(), ttlMs: ttl };
155
- }
156
- udp(packet, signal) {
157
- return new Promise((resolve, reject) => {
158
- const family = isIP(this.endpoint.address), wildcard = family === 4 ? "0.0.0.0" : "::";
159
- const socket = createSocket({ type: family === 4 ? "udp4" : "udp6",
160
- lookup: (host, _options, callback) => {
161
- // Node uses this hook for its implicit local bind as well as connect.
162
- // Preserve the wildcard bind; the remote endpoint is not a local address.
163
- if (host !== wildcard && host !== this.endpoint.address)
164
- callback(new NetworkToolError("unsupported_numeric_address"), "", family);
165
- else
166
- callback(null, host, family);
167
- } });
168
- let done = false;
169
- const finish = (error, value) => {
170
- if (done)
171
- return;
172
- done = true;
173
- signal.removeEventListener("abort", abort);
174
- const settle = () => { error ? reject(error) : resolve(value); };
175
- socket.once("close", settle);
176
- try {
177
- socket.close();
178
- }
179
- catch {
180
- // An already-aborted unbound socket has no descriptor or close event.
181
- socket.removeListener("close", settle);
182
- settle();
183
- }
184
- };
185
- const abort = () => finish(new NetworkToolError("dns_aborted"));
186
- socket.on("error", error => finish(error));
187
- socket.on("message", (message, remote) => {
188
- if (numericAddress(remote.address) !== this.endpoint.address || remote.port !== this.endpoint.port)
189
- return finish(new NetworkToolError("dns_socket_changed"));
190
- finish(undefined, message);
191
- });
192
- if (signal.aborted) {
193
- finish(new NetworkToolError("dns_aborted"));
194
- return;
195
- }
196
- signal.addEventListener("abort", abort, { once: true });
197
- socket.connect(this.endpoint.port, this.endpoint.address, () => { if (!done)
198
- socket.send(packet, error => { if (error)
199
- finish(error); }); });
200
- });
201
- }
202
- tcp(packet, signal) {
203
- return new Promise((resolve, reject) => {
204
- const socket = connect({ host: this.endpoint.address, port: this.endpoint.port, family: isIP(this.endpoint.address), autoSelectFamily: false });
205
- let done = false, bytes = Buffer.alloc(0);
206
- const finish = (error, value) => {
207
- if (done)
208
- return;
209
- done = true;
210
- signal.removeEventListener("abort", abort);
211
- socket.once("close", () => { error ? reject(error) : resolve(value); });
212
- socket.destroy();
213
- };
214
- const abort = () => finish(new NetworkToolError("dns_aborted"));
215
- socket.on("error", error => finish(error));
216
- socket.on("end", () => finish(new NetworkToolError("short_dns_response")));
217
- socket.on("connect", () => {
218
- if (done)
219
- return;
220
- if (!socket.remoteAddress || numericAddress(socket.remoteAddress) !== this.endpoint.address || socket.remotePort !== this.endpoint.port) {
221
- finish(new NetworkToolError("dns_socket_changed"));
222
- return;
223
- }
224
- const prefix = Buffer.alloc(2);
225
- prefix.writeUInt16BE(packet.length);
226
- socket.write(Buffer.concat([prefix, packet]));
227
- });
228
- socket.on("data", chunk => {
229
- if (!Buffer.isBuffer(chunk))
230
- return finish(new NetworkToolError("invalid_dns_encoding"));
231
- if (bytes.length + chunk.length > 65537)
232
- return finish(new NetworkToolError("oversized_dns_response"));
233
- bytes = Buffer.concat([bytes, chunk]);
234
- if (bytes.length < 2)
235
- return;
236
- const length = bytes.readUInt16BE();
237
- if (length < 12 || bytes.length > length + 2)
238
- return finish(new NetworkToolError("invalid_dns_frame"));
239
- if (bytes.length === length + 2)
240
- finish(undefined, bytes.subarray(2));
241
- });
242
- if (signal.aborted)
243
- abort();
244
- else
245
- signal.addEventListener("abort", abort, { once: true });
246
- });
247
- }
248
- }
@@ -1,38 +0,0 @@
1
- import { digest } from "../broker/policy.js";
2
- export const HTTP_DEPLOYMENT_SCHEMA = {
3
- type: "object", properties: {
4
- dnsResolvers: { type: "array", maxItems: 1, items: { type: "object", properties: {
5
- address: { type: "string", minLength: 1 }, port: { type: "integer", minimum: 1, maximum: 65535 },
6
- }, required: ["address", "port"], additionalProperties: false } },
7
- timeoutMs: { type: "integer", minimum: 1, maximum: 30000 },
8
- maxBodyBytes: { type: "integer", minimum: 1, maximum: 1048576 },
9
- maxResponseBytes: { type: "integer", minimum: 1, maximum: 1048576 },
10
- resolutionTtlMs: { type: "integer", minimum: 1, maximum: 60000 },
11
- }, additionalProperties: false,
12
- };
13
- /** No new wire fields or protocol enums. Arguments bind HTTP semantics; existing
14
- * network resources bind original authority and every numeric socket target. */
15
- export function httpContractExamples() {
16
- const request = { url: "https://example.test/v1/items", method: "POST", body: '{"item":"owned"}' };
17
- const scope = { runId: "run_example", stepExecutionId: "step_example", sessionId: "session_example", epoch: 1,
18
- profileVersionId: "profile_example" };
19
- const resource = (protocol, host, port) => ({
20
- kind: "network", protocol, host, port, identityDigest: digest({ scope, request, protocol, host, port }),
21
- });
22
- const origin = resource("https", "example.test", 443);
23
- const action = (phase, resources, extra = {}) => ({
24
- clientActionId: `${phase}_example`, action: { toolId: "http_request", arguments: { phase, ...request, ...extra }, resources },
25
- });
26
- return {
27
- resolve: action("resolve", [origin, resource("udp", "127.0.0.1", 53053), resource("tcp", "127.0.0.1", 53053)]),
28
- send: action("send", [origin, resource("https", "192.0.2.10", 443), resource("https", "2001:db8::10", 443)], { resolutionId: "resolution_example" }),
29
- policy: { defaultEffect: "deny", rules: [
30
- { kind: "tool", toolId: "http_request", effect: "allow" },
31
- { kind: "network", protocol: "https", host: "example.test", port: 443, effect: "require_approval" },
32
- { kind: "network", protocol: "udp", host: "127.0.0.1", port: 53053, effect: "allow" },
33
- { kind: "network", protocol: "tcp", host: "127.0.0.1", port: 53053, effect: "allow" },
34
- { kind: "network", protocol: "https", host: "192.0.2.10", port: 443, effect: "allow" },
35
- { kind: "network", protocol: "https", host: "2001:db8::10", port: 443, effect: "allow" },
36
- ] },
37
- };
38
- }
@@ -1,358 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { Agent, request as httpRequest } from "node:http";
3
- import { connect, isIP } from "node:net";
4
- import { connect as tlsConnect, TLSSocket, checkServerIdentity } from "node:tls";
5
- import { isUtf8 } from "node:buffer";
6
- import { canonical, digest, evaluate, evaluatePolicy, jsonCopy, normalizeHost, validatePolicy } from "../broker/policy.js";
7
- import { NetworkToolError, numericAddress, PinnedDnsResolver } from "./dns.js";
8
- export { HTTP_DEPLOYMENT_SCHEMA } from "./http-contract.js";
9
- const METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
10
- const FORBIDDEN_HEADERS = new Set(["authorization", "cookie", "host", "content-length", "transfer-encoding",
11
- "connection", "upgrade", "expect", "trailer", "te", "accept-encoding"]);
12
- const ADMIN_TIMEOUT = Symbol("admin_timeout");
13
- function administrativeDeadline(timeout, external) {
14
- const controller = new AbortController(), started = performance.now();
15
- let timer;
16
- const close = () => { if (timer)
17
- clearTimeout(timer); external?.removeEventListener("abort", abort); };
18
- const abort = () => { close(); controller.abort(); };
19
- const arm = () => {
20
- const remaining = timeout - (performance.now() - started);
21
- if (remaining <= 0) {
22
- abort();
23
- return;
24
- }
25
- // Node clamps oversized timeouts to 1ms. Chunk instead, without silently
26
- // imposing the agent tool's 30s policy on administrator schema fetching.
27
- timer = setTimeout(arm, Math.min(2_147_483_647, Math.ceil(remaining)));
28
- timer.unref();
29
- };
30
- if (external?.aborted)
31
- abort();
32
- else {
33
- external?.addEventListener("abort", abort, { once: true });
34
- arm();
35
- }
36
- return { signal: controller.signal, close };
37
- }
38
- export const HTTP_TOOL_CONFIGURATION_SCHEMA = { type: "object", properties: {}, additionalProperties: false };
39
- export const HTTP_INPUT_SCHEMA = { type: "object", properties: {
40
- phase: { enum: ["resolve", "send"] }, url: { type: "string", minLength: 1, maxLength: 8192 },
41
- method: { enum: METHODS }, body: { type: "string", maxLength: 1048576 },
42
- headers: { type: "object", maxProperties: 32, additionalProperties: { type: "string", maxLength: 4096 } },
43
- resolutionId: { type: "string", minLength: 1, maxLength: 100 },
44
- }, required: ["phase", "url"], additionalProperties: false };
45
- /** Two distinct single-use broker actions. DNS results are bounded data, never
46
- * a dispatch right. Every send reauthorizes original authority AND ALL IPs. */
47
- export class HttpTool {
48
- options;
49
- name = "http_request";
50
- description = "Resolve through an explicitly configured authorized numeric DNS endpoint, then separately authorize/send one pinned HTTP(S) request. No redirects, proxies, ambient credentials or automatic retry.";
51
- inputSchema = HTTP_INPUT_SCHEMA;
52
- resolutions = new Map();
53
- resolver;
54
- timeout;
55
- requestLimit;
56
- responseLimit;
57
- ttl;
58
- now;
59
- constructor(options = {}, internal) {
60
- this.options = options;
61
- if (options.credentials?.resolve.constructor.name === "AsyncFunction" || options.credentials?.describe.constructor.name === "AsyncFunction") {
62
- throw new NetworkToolError("async_credential_provider_unsupported");
63
- }
64
- const bounded = (value, fallback, maximum) => {
65
- const n = value ?? fallback;
66
- if (!Number.isSafeInteger(n) || n < 1 || n > maximum)
67
- throw new NetworkToolError("invalid_http_configuration");
68
- return n;
69
- };
70
- this.timeout = bounded(options.timeoutMs, internal === ADMIN_TIMEOUT ? 30000 : 10000, internal === ADMIN_TIMEOUT ? Number.MAX_SAFE_INTEGER : 30000);
71
- this.requestLimit = bounded(options.maxBodyBytes, 262144, 1048576);
72
- this.responseLimit = bounded(options.maxResponseBytes, 262144, 1048576);
73
- this.ttl = bounded(options.resolutionTtlMs, 30000, 60000);
74
- if (options.dnsResolvers && options.dnsResolvers.length > 1)
75
- throw new NetworkToolError("invalid_dns_configuration");
76
- this.resolver = options.dnsResolvers?.[0] ? new PinnedDnsResolver(options.dnsResolvers[0]) : undefined;
77
- this.now = options.now ?? Date.now;
78
- }
79
- arguments(value) {
80
- if (!value || Array.isArray(value) || typeof value !== "object" || Object.keys(value).some(key => !["phase", "url", "method", "body", "headers", "resolutionId"].includes(key)) || !["resolve", "send"].includes(String(value.phase)) ||
81
- typeof value.url !== "string" || value.url.length > 8192 || /[\\\u0000-\u0020\u007f]/u.test(value.url))
82
- throw new NetworkToolError("invalid_http_arguments");
83
- const url = new URL(value.url), authority = /^https?:\/\/([^/?#]+)/i.exec(value.url)?.[1];
84
- if (!authority || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash)
85
- throw new NetworkToolError("unsupported_http_url");
86
- const rawHost = authority.startsWith("[") ? authority.slice(0, authority.indexOf("]") + 1) : authority.split(":")[0];
87
- const host = normalizeHost(rawHost);
88
- if (host !== normalizeHost(url.hostname))
89
- throw new NetworkToolError("ambiguous_http_authority");
90
- if (isIP(host))
91
- numericAddress(host);
92
- const method = value.method ?? "GET", body = value.body ?? "";
93
- if (typeof method !== "string" || !METHODS.includes(method) || typeof body !== "string" || Buffer.byteLength(body) > this.requestLimit ||
94
- ((method === "GET" || method === "HEAD") && body !== ""))
95
- throw new NetworkToolError("invalid_http_body_or_method");
96
- const headers = {};
97
- if (value.headers !== undefined) {
98
- if (!value.headers || typeof value.headers !== "object" || Array.isArray(value.headers) || Object.keys(value.headers).length > 32)
99
- throw new NetworkToolError("invalid_http_headers");
100
- for (const [name, content] of Object.entries(value.headers)) {
101
- const key = name.toLowerCase();
102
- if (!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(key) || FORBIDDEN_HEADERS.has(key) || key.startsWith("proxy-") ||
103
- Object.hasOwn(headers, key) || typeof content !== "string" || content.length > 4096 || /[\u0000-\u001f\u007f]/u.test(content)) {
104
- throw new NetworkToolError("invalid_http_headers");
105
- }
106
- headers[key] = content;
107
- }
108
- }
109
- if (Buffer.byteLength(canonical(headers)) > 16384 || (value.resolutionId !== undefined &&
110
- (typeof value.resolutionId !== "string" || !value.resolutionId || value.resolutionId.length > 100)))
111
- throw new NetworkToolError("invalid_http_arguments");
112
- const args = { phase: value.phase, url: url.href, method, body, headers,
113
- ...(value.resolutionId === undefined ? {} : { resolutionId: value.resolutionId }) };
114
- return { args, url, host, protocol: url.protocol === "https:" ? "https" : "http", port: Number(url.port || (url.protocol === "https:" ? 443 : 80)) };
115
- }
116
- prepare(input, supplied) {
117
- if (!supplied)
118
- throw new NetworkToolError("missing_trusted_binding");
119
- const binding = Object.freeze(jsonCopy(supplied)), parsed = this.arguments(input), { args, host, protocol, port, url } = parsed;
120
- this.options.validateBinding?.(binding);
121
- const credential = this.options.credentials?.describe(binding, url.origin);
122
- if (credential && (protocol !== "https" || credential.origin !== url.origin || !credential.referenceId || !credential.version))
123
- throw new NetworkToolError("invalid_credential_binding");
124
- const scope = digest({ runId: binding.runId, stepExecutionId: binding.stepExecutionId, sessionId: binding.sessionId, epoch: binding.epoch,
125
- profileVersionId: binding.profileVersionId, request: { url: args.url, method: args.method, headers: args.headers, body: args.body }, credential: credential ?? null });
126
- const resource = (networkProtocol, address, destinationPort) => ({
127
- kind: "network", protocol: networkProtocol, host: address, port: destinationPort,
128
- identityDigest: digest({ scope, protocol: networkProtocol, host: address, port: destinationPort }),
129
- });
130
- const origin = resource(protocol, host, port);
131
- // Pure requested-scope rejection always precedes any resolver access.
132
- if (evaluate(binding, this.name, [origin]) === "deny")
133
- throw new NetworkToolError("network_policy_denied");
134
- for (const [id, value] of this.resolutions)
135
- if (value.expiresAt <= this.now())
136
- this.resolutions.delete(id);
137
- let resolution;
138
- let resources;
139
- if (args.phase === "resolve") {
140
- if (args.resolutionId)
141
- throw new NetworkToolError("unexpected_resolution_id");
142
- if (!isIP(host) && !this.resolver)
143
- throw new NetworkToolError("dns_not_configured");
144
- resources = [origin, ...(!isIP(host) ? [
145
- resource("udp", this.resolver.endpoint.address, this.resolver.endpoint.port),
146
- resource("tcp", this.resolver.endpoint.address, this.resolver.endpoint.port),
147
- ] : [])];
148
- }
149
- else if (isIP(host) && !args.resolutionId) {
150
- resolution = { id: "", scope, addresses: [host], expiresAt: Number.MAX_SAFE_INTEGER };
151
- resources = [origin];
152
- }
153
- else {
154
- resolution = this.resolutions.get(args.resolutionId ?? "");
155
- if (!resolution || resolution.scope !== scope || resolution.expiresAt <= this.now())
156
- throw new NetworkToolError("stale_resolution");
157
- resources = [origin, ...resolution.addresses.map(address => resource(protocol, address, port))];
158
- }
159
- if (evaluate(binding, this.name, resources) === "deny")
160
- throw new NetworkToolError("network_policy_denied");
161
- const pinned = jsonCopy(resources), expectedCredential = canonical(credential ?? null);
162
- let used = false;
163
- const validate = () => {
164
- this.options.validateBinding?.(binding);
165
- if (canonical(this.options.credentials?.describe(binding, url.origin) ?? null) !== expectedCredential ||
166
- (resolution && resolution.expiresAt <= this.now()))
167
- throw new NetworkToolError("http_target_changed");
168
- return jsonCopy(pinned);
169
- };
170
- return { resources: pinned, revalidate: validate, execute: async () => {
171
- if (used)
172
- throw new NetworkToolError("http_effect_reused");
173
- used = true;
174
- validate();
175
- const signal = AbortSignal.timeout(this.timeout);
176
- if (args.phase === "resolve") {
177
- const resolved = isIP(host) ? { addresses: [host], ttlMs: this.ttl } : await this.resolver.resolve(host, signal);
178
- if (signal.aborted)
179
- throw new NetworkToolError("http_deadline");
180
- const entry = { id: randomUUID(), scope, addresses: [...resolved.addresses], expiresAt: this.now() + Math.min(this.ttl, resolved.ttlMs) };
181
- if (this.resolutions.size >= 1024)
182
- throw new NetworkToolError("resolution_capacity");
183
- this.resolutions.set(entry.id, entry);
184
- return { success: true, text: JSON.stringify({ resolutionId: entry.id, addresses: entry.addresses, expiresAt: entry.expiresAt }) };
185
- }
186
- return this.send(parsed, resolution.addresses[0], binding, credential, signal);
187
- } };
188
- }
189
- async send(parsed, address, binding, credential, signal) {
190
- const { args, protocol, host, port, url } = parsed;
191
- if (signal.aborted)
192
- throw new NetworkToolError("http_deadline");
193
- const socket = await new Promise((resolve, reject) => {
194
- const connection = protocol === "https" ? tlsConnect({ host: address, port,
195
- servername: isIP(host) ? "" : host, rejectUnauthorized: true, ALPNProtocols: ["http/1.1"],
196
- ...(this.options.ca === undefined ? {} : { ca: this.options.ca }) }) :
197
- connect({ host: address, port, family: isIP(address), autoSelectFamily: false });
198
- const abort = () => connection.destroy(new NetworkToolError("http_deadline"));
199
- const ready = () => {
200
- try {
201
- if (signal.aborted || !connection.remoteAddress || numericAddress(connection.remoteAddress) !== address || connection.remotePort !== port)
202
- throw new NetworkToolError("http_socket_changed");
203
- if (protocol === "https" && (!(connection instanceof TLSSocket) || !connection.authorized ||
204
- checkServerIdentity(host, connection.getPeerCertificate()) || (connection.alpnProtocol && connection.alpnProtocol !== "http/1.1")))
205
- throw new NetworkToolError("http_tls_identity");
206
- resolve(connection);
207
- }
208
- catch (error) {
209
- connection.destroy();
210
- reject(error);
211
- }
212
- };
213
- connection.once("error", reject);
214
- connection.once(protocol === "https" ? "secureConnect" : "connect", ready);
215
- connection.once("close", () => signal.removeEventListener("abort", abort));
216
- if (signal.aborted)
217
- abort();
218
- else
219
- signal.addEventListener("abort", abort, { once: true });
220
- });
221
- let secret;
222
- try {
223
- if (credential) {
224
- if (!binding)
225
- throw new NetworkToolError("missing_credential_scope");
226
- secret = this.options.credentials.resolve(binding, credential);
227
- if (typeof secret !== "string" || !/^[\x21-\x7e]{1,8192}$/.test(secret) ||
228
- canonical(this.options.credentials.describe(binding, url.origin) ?? null) !== canonical(credential))
229
- throw new NetworkToolError("credential_changed");
230
- }
231
- if (signal.aborted || socket.destroyed)
232
- throw new NetworkToolError("http_deadline");
233
- const agent = new Agent({ keepAlive: false, maxSockets: 1 });
234
- agent.createConnection = () => socket;
235
- return await new Promise((resolve, reject) => {
236
- let done = false;
237
- const finish = (error, result) => {
238
- if (done)
239
- return;
240
- done = true;
241
- agent.destroy();
242
- signal.removeEventListener("abort", abort);
243
- error ? reject(error) : resolve(result);
244
- };
245
- const abort = () => finish(new NetworkToolError("http_deadline"));
246
- const request = httpRequest({ host: address, port, method: args.method, path: `${url.pathname}${url.search}`, agent,
247
- maxHeaderSize: 16384, headers: { ...args.headers, host: url.host, connection: "close", "accept-encoding": "identity",
248
- ...(args.body ? { "content-length": Buffer.byteLength(args.body) } : {}), ...(secret ? { authorization: `Bearer ${secret}` } : {}) },
249
- }, response => {
250
- let count = 0;
251
- const chunks = [];
252
- response.on("error", () => finish(new NetworkToolError("http_response_error")));
253
- response.on("aborted", () => finish(new NetworkToolError("http_response_aborted")));
254
- response.on("data", (chunk) => {
255
- count += chunk.length;
256
- if (count > this.responseLimit) {
257
- finish(new NetworkToolError("http_response_too_large"));
258
- response.destroy();
259
- return;
260
- }
261
- chunks.push(chunk);
262
- });
263
- response.on("end", () => {
264
- const bytes = Buffer.concat(chunks), containsSecret = secret !== undefined && bytes.includes(Buffer.from(secret));
265
- const headers = {};
266
- for (const key of ["content-type", "content-length", "location"]) {
267
- const value = response.headers[key];
268
- if (typeof value === "string")
269
- headers[key] = secret ? value.replaceAll(secret, "[REDACTED]") : value;
270
- }
271
- finish(undefined, { success: (response.statusCode ?? 0) >= 200 && (response.statusCode ?? 0) < 300, text: JSON.stringify({
272
- status: response.statusCode, headers, redirected: false,
273
- ...(containsSecret ? { body: "[REDACTED: response contained credential material]" } :
274
- isUtf8(bytes) ? { body: bytes.toString("utf8") } : { bodyBase64: bytes.toString("base64") }),
275
- }) });
276
- });
277
- });
278
- request.maxHeadersCount = 64;
279
- request.on("error", () => finish(new NetworkToolError("http_request_error")));
280
- request.on("upgrade", (_response, upgraded) => { upgraded.destroy(); finish(new NetworkToolError("http_upgrade_refused")); });
281
- request.once("socket", actual => {
282
- if (actual !== socket || signal.aborted || socket.destroyed || !socket.remoteAddress ||
283
- numericAddress(socket.remoteAddress) !== address || socket.remotePort !== port) {
284
- request.destroy();
285
- finish(new NetworkToolError("http_socket_changed"));
286
- return;
287
- }
288
- request.end(args.body);
289
- });
290
- if (signal.aborted)
291
- abort();
292
- else
293
- signal.addEventListener("abort", abort, { once: true });
294
- });
295
- }
296
- finally {
297
- socket.destroy();
298
- }
299
- }
300
- }
301
- /** Trusted ADMIN schema transport, not a session tool or an approval bypass.
302
- * Root API authorization precedes this call. No profile/session, credentials,
303
- * proxy, redirect, ambient DNS, automatic retry or response decompression.
304
- * It shares the exact DNS, parser, TLS and pinned-socket sender above. */
305
- export class AdminHttpFetcher extends HttpTool {
306
- networkPolicy;
307
- constructor(options) {
308
- super(options, ADMIN_TIMEOUT);
309
- validatePolicy(options.networkPolicy);
310
- if (options.networkPolicy.rules.some(rule => rule.kind !== "network"))
311
- throw new NetworkToolError("admin_network_rules_only");
312
- this.networkPolicy = jsonCopy(options.networkPolicy);
313
- }
314
- prepare(_input, _binding) { throw new NetworkToolError("admin_transport_not_agent_tool"); }
315
- async fetch(url, externalSignal) {
316
- const parsed = this.arguments({ phase: "send", url, method: "GET" }), { host, port, protocol } = parsed;
317
- const deadline = administrativeDeadline(this.timeout, externalSignal), { signal } = deadline;
318
- try {
319
- if (signal.aborted)
320
- throw new NetworkToolError("http_deadline");
321
- const resource = (transport, target, targetPort) => ({
322
- kind: "network", protocol: transport, host: target, port: targetPort,
323
- identityDigest: digest({ administrativeSchemaFetch: parsed.args.url, protocol: transport, host: target, port: targetPort }),
324
- });
325
- const origin = resource(protocol, host, port);
326
- const allow = (resources) => {
327
- // The synthetic tool clause merely permits this fixed internal operation.
328
- // There is NO synthetic profile/session and it grants NO network target.
329
- const policy = { defaultEffect: "deny", rules: [
330
- { kind: "tool", toolId: "admin_schema_fetch", effect: "allow" }, ...this.networkPolicy.rules,
331
- ] };
332
- if (evaluatePolicy(policy, "admin_schema_fetch", resources) !== "allow")
333
- throw new NetworkToolError("admin_network_denied");
334
- };
335
- allow([origin]);
336
- let addresses = [host];
337
- if (!isIP(host)) {
338
- if (!this.resolver)
339
- throw new NetworkToolError("dns_not_configured");
340
- allow([origin, resource("udp", this.resolver.endpoint.address, this.resolver.endpoint.port),
341
- resource("tcp", this.resolver.endpoint.address, this.resolver.endpoint.port)]);
342
- addresses = (await this.resolver.resolve(host, signal)).addresses;
343
- }
344
- allow([origin, ...addresses.map(address => resource(protocol, address, port))]);
345
- if (signal.aborted)
346
- throw new NetworkToolError("http_deadline");
347
- const result = await this.send(parsed, addresses[0], undefined, undefined, signal);
348
- const response = JSON.parse(result.text);
349
- if (response.status >= 300 && response.status <= 399)
350
- throw new NetworkToolError("http_redirect_refused");
351
- return { status: response.status, headers: response.headers,
352
- body: response.bodyBase64 === undefined ? Buffer.from(response.body ?? "", "utf8") : Buffer.from(response.bodyBase64, "base64") };
353
- }
354
- finally {
355
- deadline.close();
356
- }
357
- }
358
- }