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
|
@@ -1,406 +0,0 @@
|
|
|
1
|
-
import { Agent, request as httpRequest } from "node:http";
|
|
2
|
-
import { isIP } from "node:net";
|
|
3
|
-
import { checkServerIdentity, connect as tlsConnect } from "node:tls";
|
|
4
|
-
import { digest, evaluatePolicy, jsonCopy, normalizeHost, validatePolicy } from "../broker/policy.js";
|
|
5
|
-
import { numericAddress, PinnedDnsResolver } from "../tools/dns.js";
|
|
6
|
-
const codes = new Set(["configuration", "closed", "capacity", "aborted", "timeout", "denied", "dns", "tls",
|
|
7
|
-
"authentication", "rate_limited", "admission", "credential", "upstream", "content_type", "secret_echo", "body", "callback", "io"]);
|
|
8
|
-
export class ProviderTransportError extends Error {
|
|
9
|
-
failure;
|
|
10
|
-
upstreamStatus;
|
|
11
|
-
code;
|
|
12
|
-
constructor(failure, upstreamStatus) {
|
|
13
|
-
super(`provider_transport_${failure}`);
|
|
14
|
-
this.failure = failure;
|
|
15
|
-
this.upstreamStatus = upstreamStatus;
|
|
16
|
-
this.code = this.message;
|
|
17
|
-
this.name = "ProviderTransportError";
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
const failure = (value, status) => new ProviderTransportError(value, status);
|
|
21
|
-
const safe = (error, fallback) => error instanceof ProviderTransportError && codes.has(error.failure) && error.code === `provider_transport_${error.failure}`
|
|
22
|
-
&& error.message === error.code ? failure(error.failure, error.upstreamStatus) : failure(fallback);
|
|
23
|
-
const thenable = (value) => value !== null && (typeof value === "object" || typeof value === "function")
|
|
24
|
-
&& typeof value.then === "function";
|
|
25
|
-
function synchronous(callback, code, ...args) {
|
|
26
|
-
if (callback.constructor.name === "AsyncFunction")
|
|
27
|
-
throw failure(code);
|
|
28
|
-
let value;
|
|
29
|
-
try {
|
|
30
|
-
value = callback(...args);
|
|
31
|
-
}
|
|
32
|
-
catch {
|
|
33
|
-
throw failure(code);
|
|
34
|
-
}
|
|
35
|
-
if (thenable(value)) {
|
|
36
|
-
void Promise.resolve(value).catch(() => { });
|
|
37
|
-
throw failure(code);
|
|
38
|
-
}
|
|
39
|
-
return value;
|
|
40
|
-
}
|
|
41
|
-
/** Fixed administrative Responses transport, not an agent HTTP tool. No ambient
|
|
42
|
-
* DNS, proxies, cookies, redirects, connection pool, retry or body parsing. */
|
|
43
|
-
export class ProviderTransport {
|
|
44
|
-
options;
|
|
45
|
-
url;
|
|
46
|
-
host;
|
|
47
|
-
port;
|
|
48
|
-
policy;
|
|
49
|
-
resolver;
|
|
50
|
-
ca;
|
|
51
|
-
timeout;
|
|
52
|
-
concurrency;
|
|
53
|
-
work = new Set();
|
|
54
|
-
closed = false;
|
|
55
|
-
constructor(options) {
|
|
56
|
-
this.options = options;
|
|
57
|
-
try {
|
|
58
|
-
if (typeof options.endpoint !== "string" || /[\u0000-\u0020\u007f\\?#]/u.test(options.endpoint))
|
|
59
|
-
throw failure("configuration");
|
|
60
|
-
const url = new URL(options.endpoint);
|
|
61
|
-
if (url.protocol !== "https:" || url.username || url.password || !url.pathname.endsWith("/responses"))
|
|
62
|
-
throw failure("configuration");
|
|
63
|
-
const authority = /^https:\/\/([^/]+)/iu.exec(options.endpoint)?.[1];
|
|
64
|
-
const rawHost = authority?.startsWith("[") ? authority.slice(0, authority.indexOf("]") + 1) : authority?.split(":")[0];
|
|
65
|
-
this.host = normalizeHost(url.hostname);
|
|
66
|
-
if (!rawHost || normalizeHost(rawHost) !== this.host)
|
|
67
|
-
throw failure("configuration");
|
|
68
|
-
this.url = url;
|
|
69
|
-
this.port = Number(url.port || 443);
|
|
70
|
-
validatePolicy(options.networkPolicy);
|
|
71
|
-
if (options.networkPolicy.rules.some(rule => rule.kind !== "network"))
|
|
72
|
-
throw failure("configuration");
|
|
73
|
-
this.policy = jsonCopy(options.networkPolicy);
|
|
74
|
-
if ((options.dnsResolvers?.length ?? 0) > 1)
|
|
75
|
-
throw failure("configuration");
|
|
76
|
-
this.resolver = options.dnsResolvers?.[0] === undefined ? undefined : new PinnedDnsResolver(options.dnsResolvers[0]);
|
|
77
|
-
this.ca = Buffer.isBuffer(options.ca) ? Buffer.from(options.ca) : options.ca;
|
|
78
|
-
this.timeout = options.timeoutMs ?? 30_000;
|
|
79
|
-
this.concurrency = options.maxConcurrent ?? 2;
|
|
80
|
-
if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 2_147_483_647 ||
|
|
81
|
-
!Number.isSafeInteger(this.concurrency) || this.concurrency < 1)
|
|
82
|
-
throw failure("configuration");
|
|
83
|
-
}
|
|
84
|
-
catch {
|
|
85
|
-
throw failure("configuration");
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
get activeWork() { return this.work.size; }
|
|
89
|
-
async post(input) {
|
|
90
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
91
|
-
if (this.closed)
|
|
92
|
-
throw failure("closed");
|
|
93
|
-
if (this.work.size >= this.concurrency)
|
|
94
|
-
throw failure("capacity");
|
|
95
|
-
try {
|
|
96
|
-
if (!Number.isSafeInteger(input.contentLength) || input.contentLength < 0 || !input.body ||
|
|
97
|
-
typeof input.body[Symbol.asyncIterator] !== "function")
|
|
98
|
-
throw failure("body");
|
|
99
|
-
}
|
|
100
|
-
catch {
|
|
101
|
-
throw failure("body");
|
|
102
|
-
}
|
|
103
|
-
try {
|
|
104
|
-
if (!input.credential || typeof input.credential.referenceId !== "string" || !input.credential.referenceId ||
|
|
105
|
-
typeof input.credential.version !== "string" || !input.credential.version ||
|
|
106
|
-
input.credential.origin !== this.url.origin)
|
|
107
|
-
throw failure("credential");
|
|
108
|
-
}
|
|
109
|
-
catch {
|
|
110
|
-
throw failure("credential");
|
|
111
|
-
}
|
|
112
|
-
if (!(input.signal instanceof AbortSignal))
|
|
113
|
-
throw failure("configuration");
|
|
114
|
-
const cancellation = { control: new AbortController(), reason: undefined };
|
|
115
|
-
let finish;
|
|
116
|
-
const done = new Promise(resolve => { finish = resolve; });
|
|
117
|
-
const stop = (reason) => {
|
|
118
|
-
if (cancellation.reason)
|
|
119
|
-
return;
|
|
120
|
-
cancellation.reason = failure(reason);
|
|
121
|
-
// AbortSignal listeners execute synchronously. In particular, the reused
|
|
122
|
-
// DNS resolver closes its socket there, so defer the signal itself when
|
|
123
|
-
// its parent is aborted from within a synchronous SQL transaction.
|
|
124
|
-
queueMicrotask(() => {
|
|
125
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
126
|
-
cancellation.control.abort(cancellation.reason);
|
|
127
|
-
});
|
|
128
|
-
};
|
|
129
|
-
const job = { stop, done };
|
|
130
|
-
this.work.add(job);
|
|
131
|
-
const abort = () => stop("aborted");
|
|
132
|
-
input.signal.addEventListener("abort", abort, { once: true });
|
|
133
|
-
const timer = setTimeout(() => stop("timeout"), this.timeout);
|
|
134
|
-
timer.unref();
|
|
135
|
-
try {
|
|
136
|
-
if (input.signal.aborted)
|
|
137
|
-
stop("aborted");
|
|
138
|
-
await this.perform(input, cancellation, stop);
|
|
139
|
-
}
|
|
140
|
-
catch (error) {
|
|
141
|
-
throw safe(error, "io");
|
|
142
|
-
}
|
|
143
|
-
finally {
|
|
144
|
-
clearTimeout(timer);
|
|
145
|
-
input.signal.removeEventListener("abort", abort);
|
|
146
|
-
this.work.delete(job);
|
|
147
|
-
finish();
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
async close() {
|
|
151
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
152
|
-
this.closed = true;
|
|
153
|
-
const jobs = [...this.work];
|
|
154
|
-
for (const job of jobs)
|
|
155
|
-
job.stop("closed");
|
|
156
|
-
await Promise.all(jobs.map(job => job.done));
|
|
157
|
-
}
|
|
158
|
-
allow(targets) {
|
|
159
|
-
// The internal tool clause grants no network destination. Every concrete
|
|
160
|
-
// origin, DNS transport and answer still needs an explicit network allow.
|
|
161
|
-
const policy = { defaultEffect: "deny", rules: [
|
|
162
|
-
{ kind: "tool", toolId: "provider_transport", effect: "allow" }, ...this.policy.rules,
|
|
163
|
-
] };
|
|
164
|
-
const resources = targets.map(target => ({ kind: "network", ...target, identityDigest: digest(target) }));
|
|
165
|
-
if (evaluatePolicy(policy, "provider_transport", resources) !== "allow")
|
|
166
|
-
throw failure("denied");
|
|
167
|
-
}
|
|
168
|
-
async perform(input, cancellation, stop) {
|
|
169
|
-
const signal = cancellation.control.signal;
|
|
170
|
-
const check = () => {
|
|
171
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
172
|
-
if (cancellation.reason)
|
|
173
|
-
throw safe(cancellation.reason, "aborted");
|
|
174
|
-
};
|
|
175
|
-
const admit = () => { check(); synchronous(input.admit, "admission"); check(); };
|
|
176
|
-
const origin = { protocol: "https", host: this.host, port: this.port };
|
|
177
|
-
check();
|
|
178
|
-
admit();
|
|
179
|
-
this.allow([origin]);
|
|
180
|
-
let addresses = [this.host];
|
|
181
|
-
if (!isIP(this.host)) {
|
|
182
|
-
if (!this.resolver)
|
|
183
|
-
throw failure("dns");
|
|
184
|
-
this.allow([origin, { protocol: "udp", host: this.resolver.endpoint.address, port: this.resolver.endpoint.port },
|
|
185
|
-
{ protocol: "tcp", host: this.resolver.endpoint.address, port: this.resolver.endpoint.port }]);
|
|
186
|
-
try {
|
|
187
|
-
check();
|
|
188
|
-
addresses = (await this.resolver.resolve(this.host, signal)).addresses;
|
|
189
|
-
}
|
|
190
|
-
catch {
|
|
191
|
-
if (cancellation.reason)
|
|
192
|
-
throw safe(cancellation.reason, "aborted");
|
|
193
|
-
throw failure("dns");
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
check();
|
|
197
|
-
this.allow([origin, ...addresses.map(host => ({ protocol: "https", host, port: this.port }))]);
|
|
198
|
-
const address = numericAddress(addresses[0]);
|
|
199
|
-
admit();
|
|
200
|
-
let socket, socketClosed;
|
|
201
|
-
let agent, request, response;
|
|
202
|
-
let requestClosed, responseClosed;
|
|
203
|
-
let firstFailure;
|
|
204
|
-
const destroy = () => {
|
|
205
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
206
|
-
response?.destroy();
|
|
207
|
-
request?.destroy();
|
|
208
|
-
agent?.destroy();
|
|
209
|
-
socket?.destroy();
|
|
210
|
-
};
|
|
211
|
-
// Abort may be requested synchronously inside an authority transaction.
|
|
212
|
-
// Physical I/O runs only after that stack has unwound and outside SQL.
|
|
213
|
-
const aborted = () => { queueMicrotask(destroy); };
|
|
214
|
-
signal.addEventListener("abort", aborted, { once: true });
|
|
215
|
-
const fail = (error, fallback) => {
|
|
216
|
-
firstFailure ??= cancellation.reason ? safe(cancellation.reason, "aborted") : safe(error, fallback);
|
|
217
|
-
stop(firstFailure.failure);
|
|
218
|
-
return firstFailure;
|
|
219
|
-
};
|
|
220
|
-
try {
|
|
221
|
-
check();
|
|
222
|
-
const connection = { host: address, port: this.port, family: isIP(address), autoSelectFamily: false,
|
|
223
|
-
servername: isIP(this.host) ? "" : this.host, rejectUnauthorized: true, ALPNProtocols: ["http/1.1"],
|
|
224
|
-
...(this.ca === undefined ? {} : { ca: this.ca }) };
|
|
225
|
-
socket = tlsConnect(connection);
|
|
226
|
-
const verifiedSocket = socket;
|
|
227
|
-
socketClosed = new Promise(resolve => verifiedSocket.once("close", () => resolve()));
|
|
228
|
-
socket.on("error", () => { });
|
|
229
|
-
await new Promise((resolve, reject) => {
|
|
230
|
-
verifiedSocket.once("error", () => reject(cancellation.reason ? safe(cancellation.reason, "aborted") : failure("tls")));
|
|
231
|
-
verifiedSocket.once("close", () => reject(cancellation.reason ? safe(cancellation.reason, "aborted") : failure("tls")));
|
|
232
|
-
verifiedSocket.once("secureConnect", () => {
|
|
233
|
-
try {
|
|
234
|
-
check();
|
|
235
|
-
if (!verifiedSocket.remoteAddress || numericAddress(verifiedSocket.remoteAddress) !== address ||
|
|
236
|
-
verifiedSocket.remotePort !== this.port || !verifiedSocket.authorized ||
|
|
237
|
-
checkServerIdentity(this.host, verifiedSocket.getPeerCertificate()) ||
|
|
238
|
-
(verifiedSocket.alpnProtocol && verifiedSocket.alpnProtocol !== "http/1.1"))
|
|
239
|
-
throw failure("tls");
|
|
240
|
-
resolve();
|
|
241
|
-
}
|
|
242
|
-
catch (error) {
|
|
243
|
-
reject(safe(error, "tls"));
|
|
244
|
-
}
|
|
245
|
-
});
|
|
246
|
-
});
|
|
247
|
-
admit();
|
|
248
|
-
const secret = synchronous(input.resolveCredential, "credential");
|
|
249
|
-
if (typeof secret !== "string" || !secret.length || secret.length > 8192 || /[^\x21-\x7e]/u.test(secret))
|
|
250
|
-
throw failure("credential");
|
|
251
|
-
check();
|
|
252
|
-
const secretBytes = Buffer.from(secret, "ascii");
|
|
253
|
-
agent = new Agent({ keepAlive: false, maxSockets: 1 });
|
|
254
|
-
agent.createConnection = () => verifiedSocket;
|
|
255
|
-
let headers, rejected;
|
|
256
|
-
const received = new Promise((resolve, reject) => { headers = resolve; rejected = reject; });
|
|
257
|
-
request = httpRequest({ host: address, port: this.port, method: "POST", path: this.url.pathname, agent,
|
|
258
|
-
maxHeaderSize: 16_384, headers: { host: this.url.host, connection: "close", "accept-encoding": "identity",
|
|
259
|
-
"content-type": "application/json", accept: "application/json, text/event-stream",
|
|
260
|
-
"content-length": input.contentLength, authorization: `Bearer ${secret}` },
|
|
261
|
-
}, value => {
|
|
262
|
-
response = value;
|
|
263
|
-
responseClosed = new Promise(resolve => value.once("close", () => resolve()));
|
|
264
|
-
value.on("error", () => { });
|
|
265
|
-
headers(value);
|
|
266
|
-
});
|
|
267
|
-
const outgoing = request;
|
|
268
|
-
requestClosed = new Promise(resolve => outgoing.once("close", () => resolve()));
|
|
269
|
-
outgoing.maxHeadersCount = 64;
|
|
270
|
-
outgoing.on("error", () => rejected(fail(undefined, "io")));
|
|
271
|
-
outgoing.once("close", () => { if (!response)
|
|
272
|
-
rejected(fail(undefined, "io")); });
|
|
273
|
-
outgoing.once("upgrade", (_incoming, upgraded) => {
|
|
274
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
275
|
-
upgraded.destroy();
|
|
276
|
-
rejected(fail(undefined, "upstream"));
|
|
277
|
-
});
|
|
278
|
-
outgoing.once("socket", actual => {
|
|
279
|
-
try {
|
|
280
|
-
check();
|
|
281
|
-
if (actual !== verifiedSocket || verifiedSocket.destroyed || !verifiedSocket.remoteAddress ||
|
|
282
|
-
numericAddress(verifiedSocket.remoteAddress) !== address || verifiedSocket.remotePort !== this.port)
|
|
283
|
-
throw failure("tls");
|
|
284
|
-
}
|
|
285
|
-
catch (error) {
|
|
286
|
-
rejected(fail(error, "tls"));
|
|
287
|
-
}
|
|
288
|
-
});
|
|
289
|
-
const writer = this.write(input, outgoing, check, admit).catch(error => { throw fail(error, "body"); });
|
|
290
|
-
const reader = (async () => {
|
|
291
|
-
const incoming = await received;
|
|
292
|
-
check();
|
|
293
|
-
const status = incoming.statusCode ?? 0;
|
|
294
|
-
if (status < 200 || status >= 300)
|
|
295
|
-
throw failure(status === 401 || status === 403 ? "authentication" : status === 429 ? "rate_limited" : "upstream", status);
|
|
296
|
-
const rawType = incoming.headers["content-type"];
|
|
297
|
-
const type = typeof rawType === "string" ? rawType.split(";")[0].trim().toLowerCase() : "";
|
|
298
|
-
if ((type !== "application/json" && type !== "text/event-stream") ||
|
|
299
|
-
(incoming.headers["content-encoding"] !== undefined && incoming.headers["content-encoding"] !== "identity"))
|
|
300
|
-
throw failure("content_type");
|
|
301
|
-
check();
|
|
302
|
-
synchronous(input.onHeaders, "callback", status, Object.freeze({ "content-type": type }));
|
|
303
|
-
let pending = Buffer.alloc(0);
|
|
304
|
-
for await (const value of incoming) {
|
|
305
|
-
check();
|
|
306
|
-
if (!Buffer.isBuffer(value))
|
|
307
|
-
throw failure("io");
|
|
308
|
-
const bytes = pending.length ? Buffer.concat([pending, value]) : value;
|
|
309
|
-
if (bytes.includes(secretBytes))
|
|
310
|
-
throw failure("secret_echo");
|
|
311
|
-
const count = Math.max(0, bytes.length - secretBytes.length + 1);
|
|
312
|
-
if (count) {
|
|
313
|
-
check();
|
|
314
|
-
try {
|
|
315
|
-
await input.onChunk(bytes.subarray(0, count));
|
|
316
|
-
}
|
|
317
|
-
catch {
|
|
318
|
-
throw failure("callback");
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
pending = Buffer.from(bytes.subarray(count)); // At most secret.length - 1 bytes.
|
|
322
|
-
}
|
|
323
|
-
check();
|
|
324
|
-
if (pending.length) {
|
|
325
|
-
try {
|
|
326
|
-
await input.onChunk(pending);
|
|
327
|
-
}
|
|
328
|
-
catch {
|
|
329
|
-
throw failure("callback");
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
check();
|
|
333
|
-
})().catch(error => { throw fail(error, "io"); });
|
|
334
|
-
// Never race away an active iterator or consumer callback on cancellation.
|
|
335
|
-
// Both owners must physically settle before this post can become quiet.
|
|
336
|
-
await Promise.allSettled([writer, reader]);
|
|
337
|
-
if (firstFailure)
|
|
338
|
-
throw firstFailure;
|
|
339
|
-
check();
|
|
340
|
-
}
|
|
341
|
-
catch (error) {
|
|
342
|
-
throw firstFailure ?? (cancellation.reason ? safe(cancellation.reason, "aborted") : safe(error, "io"));
|
|
343
|
-
}
|
|
344
|
-
finally {
|
|
345
|
-
signal.removeEventListener("abort", aborted);
|
|
346
|
-
try {
|
|
347
|
-
destroy();
|
|
348
|
-
}
|
|
349
|
-
finally {
|
|
350
|
-
await Promise.all([socketClosed, requestClosed, responseClosed]);
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
async write(input, request, check, admit) {
|
|
355
|
-
check();
|
|
356
|
-
const iterator = input.body[Symbol.asyncIterator]();
|
|
357
|
-
let complete = false, count = 0, sent = false;
|
|
358
|
-
try {
|
|
359
|
-
while (true) {
|
|
360
|
-
check();
|
|
361
|
-
const next = await iterator.next();
|
|
362
|
-
check();
|
|
363
|
-
if (next.done) {
|
|
364
|
-
complete = true;
|
|
365
|
-
break;
|
|
366
|
-
}
|
|
367
|
-
if (!(next.value instanceof Uint8Array))
|
|
368
|
-
throw failure("body");
|
|
369
|
-
count += next.value.byteLength;
|
|
370
|
-
if (!Number.isSafeInteger(count) || count > input.contentLength)
|
|
371
|
-
throw failure("body");
|
|
372
|
-
if (!next.value.byteLength)
|
|
373
|
-
continue;
|
|
374
|
-
if (!sent) {
|
|
375
|
-
admit();
|
|
376
|
-
sent = true;
|
|
377
|
-
}
|
|
378
|
-
check();
|
|
379
|
-
if (!request.write(Buffer.from(next.value))) {
|
|
380
|
-
await new Promise((resolve, reject) => {
|
|
381
|
-
const drain = () => { clear(); resolve(); };
|
|
382
|
-
const closed = () => { clear(); reject(failure("io")); };
|
|
383
|
-
const clear = () => { request.removeListener("drain", drain); request.removeListener("error", closed); request.removeListener("close", closed); };
|
|
384
|
-
request.once("drain", drain);
|
|
385
|
-
request.once("error", closed);
|
|
386
|
-
request.once("close", closed);
|
|
387
|
-
});
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
if (count !== input.contentLength)
|
|
391
|
-
throw failure("body");
|
|
392
|
-
if (!sent)
|
|
393
|
-
admit();
|
|
394
|
-
check();
|
|
395
|
-
request.end();
|
|
396
|
-
}
|
|
397
|
-
finally {
|
|
398
|
-
// A producer's pending next/return may own physical work. Do not abandon
|
|
399
|
-
// either promise merely because the HTTP socket was already destroyed.
|
|
400
|
-
if (!complete && iterator.return) {
|
|
401
|
-
this.options.coordinator.assertOutsideTransaction();
|
|
402
|
-
await iterator.return();
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
}
|
|
@@ -1,213 +0,0 @@
|
|
|
1
|
-
import { EventEmitter } from 'node:events';
|
|
2
|
-
import { verifyWorkspaceInstructionSnapshot, workspaceInstructionInputs } from './workspace-view.js';
|
|
3
|
-
/** Model tools enter the bound broker only; administrative app-server methods never do. */
|
|
4
|
-
export class BrokeredCodexRuntime extends EventEmitter {
|
|
5
|
-
codex;
|
|
6
|
-
broker;
|
|
7
|
-
commitCompletion;
|
|
8
|
-
workspace;
|
|
9
|
-
dynamicTools;
|
|
10
|
-
#turns = new Map();
|
|
11
|
-
#names;
|
|
12
|
-
#sequence = 0;
|
|
13
|
-
#closed = false;
|
|
14
|
-
#failed = false;
|
|
15
|
-
#settlements = new Set();
|
|
16
|
-
#invocations = new Set();
|
|
17
|
-
constructor(codex, broker, commitCompletion = () => { }, workspace) {
|
|
18
|
-
super();
|
|
19
|
-
this.codex = codex;
|
|
20
|
-
this.broker = broker;
|
|
21
|
-
this.commitCompletion = commitCompletion;
|
|
22
|
-
this.workspace = workspace;
|
|
23
|
-
if (workspace)
|
|
24
|
-
verifyWorkspaceInstructionSnapshot(workspace.snapshot);
|
|
25
|
-
this.#names = new Set(broker.catalog.map(tool => tool.name));
|
|
26
|
-
if (this.#names.size !== broker.catalog.length || broker.catalog.some(tool => !/^[a-zA-Z0-9_-]{1,64}$/u.test(tool.name) || !tool.inputSchema ||
|
|
27
|
-
typeof tool.inputSchema !== 'object' || Array.isArray(tool.inputSchema))) {
|
|
28
|
-
throw new Error('Invalid broker catalog');
|
|
29
|
-
}
|
|
30
|
-
this.dynamicTools = Object.freeze(broker.catalog.map(tool => Object.freeze({
|
|
31
|
-
...tool, type: 'function', inputSchema: tool.inputSchema,
|
|
32
|
-
})));
|
|
33
|
-
codex.on('serverRequest', this.#serverRequest);
|
|
34
|
-
codex.on('notification', this.#notification);
|
|
35
|
-
}
|
|
36
|
-
get activeWork() { return this.#settlements.size; }
|
|
37
|
-
get modelActive() { return !this.#closed && !this.#failed && [...this.#turns.values()].some(turn => turn.active && !turn.completing); }
|
|
38
|
-
async settled() {
|
|
39
|
-
while (this.#settlements.size || this.#invocations.size)
|
|
40
|
-
await Promise.allSettled([...this.#settlements, ...this.#invocations]);
|
|
41
|
-
}
|
|
42
|
-
#fail(error) {
|
|
43
|
-
if (this.#closed || this.#failed)
|
|
44
|
-
return;
|
|
45
|
-
this.#failed = true;
|
|
46
|
-
this.emit('completionFailure', error);
|
|
47
|
-
}
|
|
48
|
-
#track(task) {
|
|
49
|
-
const tracked = task.catch(error => { this.#fail(error instanceof Error ? error : new Error('Runtime operation failed')); throw error; });
|
|
50
|
-
this.#settlements.add(tracked);
|
|
51
|
-
const settled = () => { this.#settlements.delete(tracked); };
|
|
52
|
-
void tracked.then(settled, settled);
|
|
53
|
-
return tracked;
|
|
54
|
-
}
|
|
55
|
-
#admit(turn) {
|
|
56
|
-
if (turn.active)
|
|
57
|
-
return true;
|
|
58
|
-
try {
|
|
59
|
-
if (this.broker.beginWork(turn.workId) === false)
|
|
60
|
-
return false;
|
|
61
|
-
turn.active = true;
|
|
62
|
-
return true;
|
|
63
|
-
}
|
|
64
|
-
catch {
|
|
65
|
-
return false;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
#park(turn) {
|
|
69
|
-
if (turn.active) {
|
|
70
|
-
this.broker.endWork(turn.workId);
|
|
71
|
-
turn.active = false;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
async startTurn(params) {
|
|
75
|
-
if (this.#closed || this.#failed || this.#turns.has(params.threadId))
|
|
76
|
-
throw new Error('Runtime thread is unavailable');
|
|
77
|
-
const turn = {
|
|
78
|
-
threadId: params.threadId, workId: `runtime-model:${++this.#sequence}:${params.threadId}`,
|
|
79
|
-
active: false, pending: new Map(),
|
|
80
|
-
};
|
|
81
|
-
if (!this.#admit(turn))
|
|
82
|
-
throw new Error('Runtime is parked');
|
|
83
|
-
this.#turns.set(turn.threadId, turn);
|
|
84
|
-
try {
|
|
85
|
-
let result;
|
|
86
|
-
if (this.workspace) {
|
|
87
|
-
if (!Array.isArray(params.input))
|
|
88
|
-
throw new Error('Runtime turn input must be an array');
|
|
89
|
-
result = await this.codex.startTurn({
|
|
90
|
-
...params, input: [
|
|
91
|
-
...workspaceInstructionInputs(this.workspace.snapshot, this.workspace.targetPath), ...params.input,
|
|
92
|
-
],
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
else
|
|
96
|
-
result = await this.codex.startTurn(params);
|
|
97
|
-
const id = result?.turn?.id;
|
|
98
|
-
if (typeof id !== 'string' || !id)
|
|
99
|
-
throw new Error('Runtime turn acknowledgement is invalid');
|
|
100
|
-
turn.turnId = id;
|
|
101
|
-
return result;
|
|
102
|
-
}
|
|
103
|
-
catch (error) {
|
|
104
|
-
this.#park(turn);
|
|
105
|
-
this.#turns.delete(turn.threadId);
|
|
106
|
-
throw error;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
#serverRequest = (message) => {
|
|
110
|
-
if (message.id === undefined)
|
|
111
|
-
return;
|
|
112
|
-
const params = message.params;
|
|
113
|
-
const turn = typeof params?.threadId === 'string' ? this.#turns.get(params.threadId) : undefined;
|
|
114
|
-
if (this.#closed || this.#failed || message.method !== 'item/tool/call' || !turn ||
|
|
115
|
-
typeof params?.tool !== 'string' || !this.#names.has(params.tool) ||
|
|
116
|
-
typeof params.callId !== 'string' || typeof params.turnId !== 'string' ||
|
|
117
|
-
!turn.turnId || params.turnId !== turn.turnId || turn.completing ||
|
|
118
|
-
(params.namespace !== null && params.namespace !== undefined) ||
|
|
119
|
-
!Object.hasOwn(params, 'arguments') || turn.pending.has(message.id)) {
|
|
120
|
-
try {
|
|
121
|
-
this.#track(Promise.resolve(this.codex.denyUnknownRequest(message.id)));
|
|
122
|
-
}
|
|
123
|
-
catch {
|
|
124
|
-
this.#fail(new Error('Runtime denial could not be written'));
|
|
125
|
-
}
|
|
126
|
-
return;
|
|
127
|
-
}
|
|
128
|
-
// A valid tool boundary ends model generation before any approval can park.
|
|
129
|
-
this.#park(turn);
|
|
130
|
-
const pending = { id: message.id };
|
|
131
|
-
turn.pending.set(message.id, pending);
|
|
132
|
-
const invocation = Promise.resolve().then(() => this.broker.invoke({
|
|
133
|
-
toolName: params.tool, arguments: params.arguments, invocationId: params.callId,
|
|
134
|
-
})).then(result => { pending.result = result; }, () => { pending.result = { success: false, text: 'Tool request denied' }; }).then(() => {
|
|
135
|
-
if (!this.#closed)
|
|
136
|
-
this.flushParked();
|
|
137
|
-
});
|
|
138
|
-
this.#invocations.add(invocation);
|
|
139
|
-
const settled = () => { this.#invocations.delete(invocation); };
|
|
140
|
-
void invocation.then(settled, settled);
|
|
141
|
-
};
|
|
142
|
-
/** Re-admit once, then keep the entire ready batch physically counted until
|
|
143
|
-
* every serial stream write has settled. No result is cleared optimistically. */
|
|
144
|
-
flushParked() {
|
|
145
|
-
if (this.#closed || this.#failed)
|
|
146
|
-
return;
|
|
147
|
-
for (const turn of this.#turns.values()) {
|
|
148
|
-
if (turn.flushing || !turn.pending.size || [...turn.pending.values()].some(item => !item.result))
|
|
149
|
-
continue;
|
|
150
|
-
if (!this.#admit(turn)) {
|
|
151
|
-
this.emit('parked', { threadId: turn.threadId });
|
|
152
|
-
continue;
|
|
153
|
-
}
|
|
154
|
-
const batch = [...turn.pending.values()];
|
|
155
|
-
const writing = Promise.allSettled(batch.map(async (pending) => {
|
|
156
|
-
const result = pending.result;
|
|
157
|
-
await this.codex.answerRequest(pending.id, { success: result.success, contentItems: [{ type: 'inputText', text: result.text }] });
|
|
158
|
-
if (turn.pending.get(pending.id) === pending)
|
|
159
|
-
turn.pending.delete(pending.id);
|
|
160
|
-
delete pending.result;
|
|
161
|
-
})).then(results => {
|
|
162
|
-
const failed = results.find(result => result.status === 'rejected');
|
|
163
|
-
if (failed?.status === 'rejected')
|
|
164
|
-
throw failed.reason;
|
|
165
|
-
}).finally(() => { delete turn.flushing; });
|
|
166
|
-
turn.flushing = this.#track(writing);
|
|
167
|
-
void turn.flushing.then(() => { if (!this.#closed)
|
|
168
|
-
this.flushParked(); }, () => { });
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
#notification = (message) => {
|
|
172
|
-
const params = message.params;
|
|
173
|
-
if (message.method !== 'turn/completed' || !params?.threadId)
|
|
174
|
-
return;
|
|
175
|
-
const turn = this.#turns.get(params.threadId);
|
|
176
|
-
if (!turn || !turn.turnId || params.turn?.id !== turn.turnId || turn.completing)
|
|
177
|
-
return;
|
|
178
|
-
turn.completing = true;
|
|
179
|
-
// Commit the already-admitted completion before releasing its active work.
|
|
180
|
-
this.#track(Promise.resolve().then(async () => {
|
|
181
|
-
// A server can see the last newline before our write callback/drain. Its
|
|
182
|
-
// completion waits for that existing response, never gets dropped/charged.
|
|
183
|
-
if (turn.flushing)
|
|
184
|
-
await turn.flushing;
|
|
185
|
-
if (this.#closed || this.#failed)
|
|
186
|
-
return;
|
|
187
|
-
if (turn.pending.size)
|
|
188
|
-
throw new Error('Runtime completed with unresolved tool requests');
|
|
189
|
-
await this.commitCompletion(message.params);
|
|
190
|
-
}).then(() => {
|
|
191
|
-
this.#turns.delete(turn.threadId);
|
|
192
|
-
if (!this.#closed && !this.#failed)
|
|
193
|
-
this.emit('turnCompleted', message.params);
|
|
194
|
-
}, error => { throw error; }).finally(() => {
|
|
195
|
-
this.#park(turn);
|
|
196
|
-
this.#turns.delete(turn.threadId);
|
|
197
|
-
}));
|
|
198
|
-
};
|
|
199
|
-
pause() { return this.broker.pause(); }
|
|
200
|
-
resume() {
|
|
201
|
-
const result = this.broker.resume();
|
|
202
|
-
this.flushParked();
|
|
203
|
-
return result;
|
|
204
|
-
}
|
|
205
|
-
detach() {
|
|
206
|
-
this.#closed = true;
|
|
207
|
-
this.codex.off('serverRequest', this.#serverRequest);
|
|
208
|
-
this.codex.off('notification', this.#notification);
|
|
209
|
-
for (const turn of this.#turns.values())
|
|
210
|
-
this.#park(turn);
|
|
211
|
-
this.#turns.clear();
|
|
212
|
-
}
|
|
213
|
-
}
|