code60-transmission-server 0.1.0-staging.6 → 0.1.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.
- package/INTENT.md +47 -0
- package/README.md +87 -308
- package/dist/src/acp.js +130 -0
- package/dist/src/contract.js +133 -0
- package/dist/src/engine.js +650 -0
- package/dist/src/linux.js +84 -0
- package/dist/src/main.js +81 -25
- package/dist/src/repository.js +94 -0
- package/dist/src/service.js +196 -0
- package/package.json +19 -35
- package/reference/openapi.json +1073 -0
- package/README.engine.md +0 -463
- package/dist/src/broker/filesystem.js +0 -385
- package/dist/src/broker/index.js +0 -734
- package/dist/src/broker/native/README.md +0 -207
- package/dist/src/broker/native/build.js +0 -46
- package/dist/src/broker/native/command-helper.c +0 -93
- package/dist/src/broker/native/fs-helper.c +0 -529
- package/dist/src/broker/native/git-helper.c +0 -205
- package/dist/src/broker/policy.js +0 -149
- package/dist/src/broker/startup-lock.js +0 -14
- package/dist/src/broker/types.js +0 -11
- package/dist/src/cli/configure.js +0 -193
- package/dist/src/cli/daemon.js +0 -369
- package/dist/src/cli/helpers.js +0 -112
- package/dist/src/cli/main.js +0 -189
- package/dist/src/cli/runtime-build.js +0 -38
- package/dist/src/config/coding-policy.js +0 -4
- package/dist/src/config/deployment.js +0 -182
- package/dist/src/config/documents.js +0 -29
- package/dist/src/config/profile-validation.js +0 -123
- package/dist/src/config/schema-graph.js +0 -237
- package/dist/src/config/schema-loader.js +0 -185
- package/dist/src/config/validation-pool.js +0 -105
- package/dist/src/config/validation-protocol.js +0 -1
- package/dist/src/config/validation-worker.js +0 -106
- package/dist/src/config/workflow-language.js +0 -9
- package/dist/src/config/workflow-schema.json +0 -545
- package/dist/src/config/workflow-types.js +0 -1
- package/dist/src/config/workflow-validation.js +0 -95
- package/dist/src/engine/budgets.js +0 -50
- package/dist/src/engine/clocks.js +0 -27
- package/dist/src/engine/commands.js +0 -472
- package/dist/src/engine/contracts.js +0 -11
- package/dist/src/engine/drain-state.js +0 -31
- package/dist/src/engine/effective-permissions.js +0 -120
- package/dist/src/engine/instruction-pins.js +0 -205
- package/dist/src/engine/retries.js +0 -50
- package/dist/src/engine/state.js +0 -1
- package/dist/src/engine/timing.js +0 -23
- package/dist/src/engine/tool-observations.js +0 -87
- package/dist/src/engine/workflow-engine.js +0 -1862
- package/dist/src/mcp/catalog.js +0 -71
- package/dist/src/mcp/main.js +0 -26
- package/dist/src/mcp/server.js +0 -147
- package/dist/src/runtime/codex-app-server.js +0 -91
- package/dist/src/runtime/containment.js +0 -82
- package/dist/src/runtime/engine-driver.js +0 -221
- package/dist/src/runtime/json-line-writer.js +0 -192
- package/dist/src/runtime/pinned-instruction-sources.js +0 -24
- package/dist/src/runtime/protocol-client.js +0 -264
- package/dist/src/runtime/protocol-pool.js +0 -183
- package/dist/src/runtime/protocol-projection.js +0 -393
- package/dist/src/runtime/protocol-types.js +0 -1
- package/dist/src/runtime/protocol-worker.js +0 -18
- package/dist/src/runtime/provider-bridge.js +0 -290
- package/dist/src/runtime/provider-credentials.js +0 -41
- package/dist/src/runtime/provider-transport.js +0 -406
- package/dist/src/runtime/runtime-broker.js +0 -213
- package/dist/src/runtime/workspace-instructions.js +0 -120
- package/dist/src/runtime/workspace-view.js +0 -74
- package/dist/src/server/api-contract.json +0 -11614
- package/dist/src/server/api-types.js +0 -1
- package/dist/src/server/application.js +0 -44
- package/dist/src/server/auth.js +0 -67
- package/dist/src/server/broker-handlers.js +0 -242
- package/dist/src/server/coding.js +0 -254
- package/dist/src/server/control-plane.js +0 -50
- package/dist/src/server/deployment.js +0 -249
- package/dist/src/server/errors.js +0 -22
- package/dist/src/server/history-handlers.js +0 -127
- package/dist/src/server/http.js +0 -124
- package/dist/src/server/paging.js +0 -56
- package/dist/src/server/publication.js +0 -119
- package/dist/src/server/tool-event-handler.js +0 -77
- package/dist/src/server/workspace-handlers.js +0 -34
- package/dist/src/storage/coordinator.js +0 -224
- package/dist/src/storage/startup-lock.js +0 -71
- package/dist/src/storage/store.js +0 -167
- package/dist/src/tools/check-worker.js +0 -81
- package/dist/src/tools/checks.js +0 -117
- package/dist/src/tools/command-check.js +0 -34
- package/dist/src/tools/commands.js +0 -310
- package/dist/src/tools/developer.js +0 -351
- package/dist/src/tools/dns.js +0 -248
- package/dist/src/tools/http-contract.js +0 -38
- package/dist/src/tools/http.js +0 -358
- package/dist/src/tools/index.js +0 -194
- package/dist/src/tools/worker-check.js +0 -73
- package/dist/src/workspaces/git.js +0 -227
- package/dist/src/workspaces/index.js +0 -937
- package/dist/src/workspaces/source.js +0 -295
- package/examples/deployment.local.json +0 -22
- package/scripts/postinstall.mjs +0 -26
package/dist/src/tools/http.js
DELETED
|
@@ -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
|
-
}
|
package/dist/src/tools/index.js
DELETED
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
import { filesystemToolDefinitions } from "../broker/filesystem.js";
|
|
2
|
-
import { canonical, digest, jsonCopy } from "../broker/policy.js";
|
|
3
|
-
import { BrokerError } from "../broker/types.js";
|
|
4
|
-
import { WorkspaceService } from "../workspaces/index.js";
|
|
5
|
-
import { HttpTool, HTTP_TOOL_CONFIGURATION_SCHEMA } from "./http.js";
|
|
6
|
-
export * from "./checks.js";
|
|
7
|
-
export * from "./worker-check.js";
|
|
8
|
-
export * from "./http.js";
|
|
9
|
-
export * from "./http-contract.js";
|
|
10
|
-
export const FILE_TOOL_CONFIGURATION_SCHEMA = { type: "object", properties: {
|
|
11
|
-
root: { enum: ["workspace", "scratch", "deployment"] }, rootId: { type: "string", minLength: 1, maxLength: 200 },
|
|
12
|
-
scratchIndex: { type: "integer", minimum: 0, maximum: 63 },
|
|
13
|
-
}, additionalProperties: false, allOf: [
|
|
14
|
-
{ if: { properties: { root: { const: "deployment" } }, required: ["root"] }, then: { required: ["rootId"] },
|
|
15
|
-
else: { not: { required: ["rootId"] } } },
|
|
16
|
-
] };
|
|
17
|
-
const contextScope = (context) => ({ workspaceId: context.workspaceId, leaseId: context.leaseId,
|
|
18
|
-
instructionSnapshotId: context.instructionSnapshotId, workspaceRevisionId: context.workspaceRevisionId ?? null });
|
|
19
|
-
/** Server-private context selects all FDs and credentials. Model root labels are
|
|
20
|
-
* selectors among already assigned capabilities, never authority or host paths. */
|
|
21
|
-
export class ToolFactory {
|
|
22
|
-
options;
|
|
23
|
-
http;
|
|
24
|
-
constructor(options) {
|
|
25
|
-
this.options = options;
|
|
26
|
-
const provider = options.http?.credentials;
|
|
27
|
-
if (provider?.resolve.constructor.name === "AsyncFunction" || provider?.describe.constructor.name === "AsyncFunction") {
|
|
28
|
-
throw new BrokerError("async_credential_provider_unsupported", 422);
|
|
29
|
-
}
|
|
30
|
-
this.http = new HttpTool({ ...options.http, validateBinding: binding => {
|
|
31
|
-
const context = this.context(binding);
|
|
32
|
-
this.options.http?.validateBinding?.(binding);
|
|
33
|
-
this.configuration(context, "http_request");
|
|
34
|
-
}, ...(provider === undefined ? {} : { credentials: {
|
|
35
|
-
describe: (binding, origin) => {
|
|
36
|
-
const context = this.context(binding), reference = this.configuration(context, "http_request").credentialRefs?.authorization;
|
|
37
|
-
if (!reference)
|
|
38
|
-
return undefined;
|
|
39
|
-
const descriptor = provider.describe(binding, origin);
|
|
40
|
-
if (!descriptor || descriptor.referenceId !== reference)
|
|
41
|
-
throw new BrokerError("unauthorized_credential_reference", 422);
|
|
42
|
-
return descriptor;
|
|
43
|
-
},
|
|
44
|
-
resolve: (binding, credential) => provider.resolve(binding, credential),
|
|
45
|
-
} }) });
|
|
46
|
-
}
|
|
47
|
-
context(binding, expected) {
|
|
48
|
-
const context = this.options.resolveContext(binding);
|
|
49
|
-
for (const key of ["runId", "stepExecutionId", "sessionId", "epoch", "profileVersionId", "role"]) {
|
|
50
|
-
if (context.binding[key] !== binding[key])
|
|
51
|
-
throw new BrokerError("stale_tool_context");
|
|
52
|
-
}
|
|
53
|
-
if (expected && canonical(contextScope(context)) !== canonical(contextScope(expected)))
|
|
54
|
-
throw new BrokerError("stale_tool_context");
|
|
55
|
-
if (!context.instructionSnapshotId)
|
|
56
|
-
throw new BrokerError("instruction_snapshot_required");
|
|
57
|
-
this.options.workspaces.assertContext(context);
|
|
58
|
-
return { ...context, binding: Object.freeze(jsonCopy(binding)) };
|
|
59
|
-
}
|
|
60
|
-
configuration(context, name) {
|
|
61
|
-
const tool = this.options.resolveConfiguration?.(context, name) ?? { configuration: {} };
|
|
62
|
-
const value = tool.configuration;
|
|
63
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
64
|
-
throw new BrokerError("invalid_tool_configuration", 422);
|
|
65
|
-
const configuration = value;
|
|
66
|
-
const refs = tool.credentialRefs ?? {};
|
|
67
|
-
if (name === "http_request") {
|
|
68
|
-
if (Object.keys(configuration).length || Object.keys(refs).some(slot => slot !== "authorization") ||
|
|
69
|
-
(refs.authorization !== undefined && (!refs.authorization || !this.options.http?.credentials)))
|
|
70
|
-
throw new BrokerError("unsupported_tool_configuration", 422);
|
|
71
|
-
}
|
|
72
|
-
else if (this.options.extensions?.has(name) && !filesystemToolDefinitions().has(name)) {
|
|
73
|
-
if (Object.keys(configuration).length || Object.keys(refs).length)
|
|
74
|
-
throw new BrokerError('unsupported_tool_configuration', 422);
|
|
75
|
-
}
|
|
76
|
-
else {
|
|
77
|
-
if (Object.keys(refs).length || Object.keys(configuration).some(key => !["root", "rootId", "scratchIndex"].includes(key)) ||
|
|
78
|
-
(configuration.root !== undefined && !["workspace", "scratch", "deployment"].includes(String(configuration.root))) ||
|
|
79
|
-
(configuration.scratchIndex !== undefined && (!Number.isInteger(configuration.scratchIndex) ||
|
|
80
|
-
Number(configuration.scratchIndex) < 0 || Number(configuration.scratchIndex) > 63)) ||
|
|
81
|
-
(configuration.root === "deployment" ? typeof configuration.rootId !== "string" || !configuration.rootId ||
|
|
82
|
-
!this.options.workspaces.deploymentRootIds().includes(configuration.rootId) : configuration.rootId !== undefined)) {
|
|
83
|
-
throw new BrokerError("unsupported_tool_configuration", 422);
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
return jsonCopy(tool);
|
|
87
|
-
}
|
|
88
|
-
toolConfigurations() {
|
|
89
|
-
const extensions = [...(this.options.extensions?.keys() ?? [])].filter(name => !filesystemToolDefinitions().has(name)).map(toolId => ({ toolId, configurationSchema: { type: 'object', additionalProperties: false }, credentialSlots: [] }));
|
|
90
|
-
return extensions.concat([...filesystemToolDefinitions().keys()].map(toolId => ({ toolId, configurationSchema: jsonCopy(FILE_TOOL_CONFIGURATION_SCHEMA), credentialSlots: [] }))
|
|
91
|
-
.concat([{ toolId: this.http.name, configurationSchema: jsonCopy(HTTP_TOOL_CONFIGURATION_SCHEMA),
|
|
92
|
-
credentialSlots: this.options.http?.credentials ? ["authorization"] : [] }]));
|
|
93
|
-
}
|
|
94
|
-
/** Pure registry for the global broker, available before a session exists. */
|
|
95
|
-
registry() { return this.create(); }
|
|
96
|
-
catalog(context) {
|
|
97
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
98
|
-
this.context(context.binding, context);
|
|
99
|
-
for (const name of context.binding.configuredTools) {
|
|
100
|
-
if (!this.create().has(name))
|
|
101
|
-
throw new BrokerError("unsupported_tool", 422);
|
|
102
|
-
this.configuration(context, name);
|
|
103
|
-
}
|
|
104
|
-
return new Map([...this.create(context)].filter(([name]) => context.binding.configuredTools.includes(name)));
|
|
105
|
-
}
|
|
106
|
-
create(expected) {
|
|
107
|
-
const tools = new Map();
|
|
108
|
-
for (const [name, metadata] of filesystemToolDefinitions()) {
|
|
109
|
-
const schema = metadata.inputSchema, properties = schema.properties;
|
|
110
|
-
tools.set(name, { ...metadata, inputSchema: { ...schema, properties: { ...properties, root: { enum: ["workspace", "scratch", "deployment"] } } },
|
|
111
|
-
prepare: (input, binding) => {
|
|
112
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
113
|
-
if (!binding || !input || typeof input !== "object" || Array.isArray(input))
|
|
114
|
-
throw new BrokerError("invalid_tool_arguments", 400);
|
|
115
|
-
const context = this.context(binding, expected), config = this.configuration(context, name).configuration;
|
|
116
|
-
if (!binding.configuredTools.includes(name))
|
|
117
|
-
throw new BrokerError("unsupported_tool", 422);
|
|
118
|
-
const kind = input.root ?? config.root ?? "workspace";
|
|
119
|
-
if (!["workspace", "scratch", "deployment"].includes(String(kind)) || (config.root !== undefined && kind !== config.root) ||
|
|
120
|
-
(kind === "deployment" && config.root !== "deployment"))
|
|
121
|
-
throw new BrokerError("unassigned_tool_root", 403);
|
|
122
|
-
const files = kind === "deployment" ? this.options.workspaces.toolDeploymentRoot(context, String(config.rootId)) :
|
|
123
|
-
this.options.workspaces.toolRoot(context, kind, Number(config.scratchIndex ?? 0));
|
|
124
|
-
try {
|
|
125
|
-
const { root: _root, ...arguments_ } = jsonCopy(input), tool = files.catalog().get(name);
|
|
126
|
-
if (!tool)
|
|
127
|
-
throw new BrokerError("unsupported_tool", 422);
|
|
128
|
-
const prepared = tool.prepare(arguments_, binding);
|
|
129
|
-
if (prepared && "then" in prepared)
|
|
130
|
-
throw new BrokerError("async_native_prepare", 500);
|
|
131
|
-
const mutation = name === "write_file" ? { kind: "write", path: String(arguments_.path), content: Buffer.from(String(arguments_.content)) } :
|
|
132
|
-
name === "delete_file" ? { kind: "delete", path: String(arguments_.path) } :
|
|
133
|
-
name === "move_file" ? { kind: "move", path: String(arguments_.path), destination: String(arguments_.destination) } : undefined;
|
|
134
|
-
return this.wrap(prepared, binding, context, () => files.close(), kind === "workspace" ? mutation : undefined);
|
|
135
|
-
}
|
|
136
|
-
catch (error) {
|
|
137
|
-
files.close();
|
|
138
|
-
throw error;
|
|
139
|
-
}
|
|
140
|
-
} });
|
|
141
|
-
}
|
|
142
|
-
tools.set(this.http.name, { name: this.http.name, description: this.http.description, inputSchema: this.http.inputSchema,
|
|
143
|
-
prepare: (input, binding) => {
|
|
144
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
145
|
-
if (!binding)
|
|
146
|
-
throw new BrokerError("missing_trusted_binding");
|
|
147
|
-
const context = this.context(binding, expected);
|
|
148
|
-
this.configuration(context, this.http.name);
|
|
149
|
-
return this.wrap(this.http.prepare(input, binding), binding, context);
|
|
150
|
-
} });
|
|
151
|
-
for (const [name, extension] of this.options.extensions ?? []) {
|
|
152
|
-
const legacy = tools.get(name);
|
|
153
|
-
tools.set(name, { ...extension, prepare: (input, binding) => {
|
|
154
|
-
if (!binding)
|
|
155
|
-
throw new BrokerError('missing_trusted_binding');
|
|
156
|
-
const context = this.context(binding, expected), configuration = this.configuration(context, name).configuration;
|
|
157
|
-
const root = input && typeof input === 'object' && !Array.isArray(input) ? input.root : undefined;
|
|
158
|
-
if (legacy && (!this.options.workspaces.sourceRepository(binding.runId) || root && root !== 'workspace' || configuration.root && configuration.root !== 'workspace'))
|
|
159
|
-
return legacy.prepare(input, binding);
|
|
160
|
-
return extension.prepare(input, binding);
|
|
161
|
-
} });
|
|
162
|
-
}
|
|
163
|
-
return tools;
|
|
164
|
-
}
|
|
165
|
-
wrap(prepared, binding, context, close, mutation) {
|
|
166
|
-
let disposed = false, used = false;
|
|
167
|
-
const resources = (actual) => actual.map(resource => ({ ...resource,
|
|
168
|
-
identityDigest: digest({ resourceIdentity: resource.identityDigest, context: contextScope(context) }) }));
|
|
169
|
-
const validate = () => {
|
|
170
|
-
if (disposed)
|
|
171
|
-
throw new BrokerError("tool_effect_disposed");
|
|
172
|
-
this.context(binding, context);
|
|
173
|
-
};
|
|
174
|
-
return { resources: resources(prepared.resources), revalidate: () => { validate(); return resources(prepared.revalidate()); },
|
|
175
|
-
execute: dispatchId => {
|
|
176
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
177
|
-
validate();
|
|
178
|
-
if (used)
|
|
179
|
-
throw new BrokerError("tool_effect_reused");
|
|
180
|
-
used = true;
|
|
181
|
-
return mutation ? this.options.workspaces.applyMutation(context, mutation, () => prepared.execute(dispatchId)) : prepared.execute(dispatchId);
|
|
182
|
-
},
|
|
183
|
-
dispose: () => { if (!disposed) {
|
|
184
|
-
disposed = true;
|
|
185
|
-
try {
|
|
186
|
-
prepared.dispose?.();
|
|
187
|
-
}
|
|
188
|
-
finally {
|
|
189
|
-
close?.();
|
|
190
|
-
}
|
|
191
|
-
} },
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
}
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import { Worker } from "node:worker_threads";
|
|
2
|
-
import { canonical, jsonCopy } from "../broker/policy.js";
|
|
3
|
-
import { CheckRegistryError } from "./checks.js";
|
|
4
|
-
/** Only deployment registrations select fixed predicates. No workflow/model
|
|
5
|
-
* command, inline function, arbitrary script/module path or shell is accepted.
|
|
6
|
-
* Actual predicate execution and Ajv compilation are OFF the coordinator.
|
|
7
|
-
* This promise settles only AFTER the Worker physically exits. */
|
|
8
|
-
export function createPureArtifactCheck(definition, options) {
|
|
9
|
-
const spec = jsonCopy(definition), predicate = spec.predicate;
|
|
10
|
-
if ([spec.id, spec.description, spec.version].some(value => typeof value !== "string" || !value || value.length > 4096) ||
|
|
11
|
-
Object.keys(spec).some(key => !["id", "description", "version", "predicate"].includes(key)) ||
|
|
12
|
-
Object.keys(predicate).some(key => !(predicate.kind === "text_includes" ? ["kind", "needle"] :
|
|
13
|
-
predicate.kind === "json_pointer_equals" ? ["kind", "pointer", "expected"] : ["kind", "schema"]).includes(key)) ||
|
|
14
|
-
canonical(predicate).length > 65536 ||
|
|
15
|
-
(predicate.kind === "text_includes" ? typeof predicate.needle !== "string" || !predicate.needle || predicate.needle.length > 4096 :
|
|
16
|
-
predicate.kind === "json_pointer_equals" ? typeof predicate.pointer !== "string" || !/^(?:|\/(?:[^~]|~[01])*)$/.test(predicate.pointer) :
|
|
17
|
-
predicate.kind === "json_schema" ? !(typeof predicate.schema === "boolean" ||
|
|
18
|
-
!!predicate.schema && typeof predicate.schema === "object" && !Array.isArray(predicate.schema)) : true)) {
|
|
19
|
-
throw new CheckRegistryError("invalid_pure_check_registration");
|
|
20
|
-
}
|
|
21
|
-
return Object.freeze({ id: spec.id, description: spec.description, version: spec.version,
|
|
22
|
-
execute: (request, signal) => {
|
|
23
|
-
options.coordinator.assertOutsideTransaction();
|
|
24
|
-
if (signal.aborted || request.deadlineAt <= Date.now())
|
|
25
|
-
return Promise.resolve({ status: "infrastructure_error", code: "check_aborted",
|
|
26
|
-
retryable: true, explanation: "Registered check was cancelled before execution." });
|
|
27
|
-
return new Promise(resolve => {
|
|
28
|
-
const entry = new URL(import.meta.url.endsWith(".ts") ? "./check-worker.ts" : "./check-worker.js", import.meta.url);
|
|
29
|
-
const worker = new Worker(entry, { workerData: { artifact: request.artifact, predicate }, execArgv: [],
|
|
30
|
-
env: { PATH: "/usr/bin:/bin", LC_ALL: "C" }, resourceLimits: { maxOldGenerationSizeMb: 64, maxYoungGenerationSizeMb: 16, stackSizeMb: 4 } });
|
|
31
|
-
let result, aborted = false, timer;
|
|
32
|
-
const abort = () => { aborted = true; void worker.terminate().catch(() => { }); };
|
|
33
|
-
const arm = () => {
|
|
34
|
-
const remaining = request.deadlineAt - Date.now();
|
|
35
|
-
if (remaining <= 0)
|
|
36
|
-
abort();
|
|
37
|
-
else {
|
|
38
|
-
timer = setTimeout(arm, Math.min(2_147_483_647, Math.ceil(remaining)));
|
|
39
|
-
timer.unref();
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
worker.on("message", (value) => {
|
|
43
|
-
if ("event" in value) {
|
|
44
|
-
try {
|
|
45
|
-
options.onWorkerReady?.();
|
|
46
|
-
}
|
|
47
|
-
catch {
|
|
48
|
-
abort();
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
else
|
|
52
|
-
result = value;
|
|
53
|
-
});
|
|
54
|
-
worker.on("error", () => {
|
|
55
|
-
result = { status: "infrastructure_error", code: "check_worker_error", retryable: true,
|
|
56
|
-
explanation: "Registered pure check worker failed." };
|
|
57
|
-
});
|
|
58
|
-
worker.on("exit", code => {
|
|
59
|
-
if (timer)
|
|
60
|
-
clearTimeout(timer);
|
|
61
|
-
signal.removeEventListener("abort", abort);
|
|
62
|
-
resolve(aborted ? { status: "infrastructure_error", code: "check_worker_aborted", retryable: true,
|
|
63
|
-
explanation: "Registered pure check worker was cancelled or exceeded its deadline." } :
|
|
64
|
-
code === 0 && result ? result : { status: "infrastructure_error", code: "check_worker_failed", retryable: true,
|
|
65
|
-
explanation: "Registered pure check did not produce a completed result." });
|
|
66
|
-
});
|
|
67
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
68
|
-
arm();
|
|
69
|
-
if (signal.aborted)
|
|
70
|
-
abort();
|
|
71
|
-
});
|
|
72
|
-
} });
|
|
73
|
-
}
|