agentapi-sandbox-daemon-runtime 0.0.0-stage → 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/README.md +4 -2
- package/child.mjs +68 -0
- package/journal.mjs +160 -0
- package/limits.mjs +23 -0
- package/log.mjs +14 -0
- package/model-proxy.mjs +202 -0
- package/package.json +17 -4
- package/rpc.mjs +25 -0
- package/runtime.mjs +258 -0
- package/supervisor.mjs +89 -0
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agentapi-sandbox-daemon-runtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Common HTTP/SSE transport, journal, supervision, and model proxy used by the
|
|
4
|
+
AgentAPI runtime daemon packages. It does not know CMA, Session state, or any
|
|
5
|
+
specific Agent protocol.
|
package/child.mjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { maxFrameBytes } from './limits.mjs';
|
|
3
|
+
import { errorCode } from './log.mjs';
|
|
4
|
+
import { rpcError } from './rpc.mjs';
|
|
5
|
+
|
|
6
|
+
/** Owns pipe failure, bounded NDJSON decoding and graceful child shutdown.
|
|
7
|
+
* Children inherit the supervisor's daemon process group. If the daemon dies,
|
|
8
|
+
* the supervisor kills that entire group before starting another generation.
|
|
9
|
+
*/
|
|
10
|
+
export function startChild(command, args, options, onMessage, onFailure, log) {
|
|
11
|
+
const child = spawn(command, args, { cwd: options.cwd, env: options.env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
12
|
+
let closing = false, failed = false, chunks = [], bufferedBytes = 0, exit;
|
|
13
|
+
const appendLinePart = part => { if (part.length) { chunks.push(part); bufferedBytes += part.length; } };
|
|
14
|
+
const emitLine = () => {
|
|
15
|
+
const line = Buffer.concat(chunks, bufferedBytes).toString('utf8');
|
|
16
|
+
chunks = []; bufferedBytes = 0;
|
|
17
|
+
if (!line.trim()) return;
|
|
18
|
+
try { onMessage(JSON.parse(line)); } catch { failure('AGENT_PROTOCOL_FAILED'); }
|
|
19
|
+
};
|
|
20
|
+
const feed = chunk => {
|
|
21
|
+
let offset = 0;
|
|
22
|
+
while (offset < chunk.length && !failed && !closing) {
|
|
23
|
+
const end = chunk.indexOf(10, offset);
|
|
24
|
+
if (end < 0) { appendLinePart(chunk.subarray(offset)); break; }
|
|
25
|
+
appendLinePart(chunk.subarray(offset, end));
|
|
26
|
+
if (bufferedBytes > maxFrameBytes) { failure('AGENT_FRAME_TOO_LARGE'); return; }
|
|
27
|
+
emitLine();
|
|
28
|
+
offset = end + 1;
|
|
29
|
+
}
|
|
30
|
+
if (bufferedBytes > maxFrameBytes) failure('AGENT_FRAME_TOO_LARGE');
|
|
31
|
+
};
|
|
32
|
+
const failure = code => { if (!closing && !failed) { failed = true; onFailure(code); } };
|
|
33
|
+
const exited = new Promise(resolve => { exit = resolve; });
|
|
34
|
+
child.once('error', error => { log('error', 'agent_spawn_failed', { code: errorCode(error) }); failure('AGENT_SPAWN_FAILED'); exit(); });
|
|
35
|
+
child.once('exit', (code, signal) => {
|
|
36
|
+
log(closing ? 'info' : 'error', 'agent_exited', { pid: child.pid, exit_code: code, signal });
|
|
37
|
+
failure('AGENT_EXITED'); exit();
|
|
38
|
+
});
|
|
39
|
+
child.stdin.on('error', () => failure('AGENT_STDIN_FAILED'));
|
|
40
|
+
child.stdout.on('error', () => failure('AGENT_STDOUT_FAILED'));
|
|
41
|
+
// Drain stderr to avoid blocking the agent. Arbitrary CLI stderr can contain
|
|
42
|
+
// user prompts and credentials; process and protocol failures have safe codes.
|
|
43
|
+
child.stderr.on('data', () => {});
|
|
44
|
+
child.stderr.on('error', () => failure('AGENT_STDERR_FAILED'));
|
|
45
|
+
child.stdout.on('data', chunk => {
|
|
46
|
+
if (failed || closing) return;
|
|
47
|
+
feed(chunk);
|
|
48
|
+
});
|
|
49
|
+
child.stdout.once('end', () => { if (bufferedBytes) failure('AGENT_TRUNCATED_FRAME'); });
|
|
50
|
+
let closePromise;
|
|
51
|
+
return {
|
|
52
|
+
child,
|
|
53
|
+
async write(message) {
|
|
54
|
+
if (failed || closing || !child.stdin.writable) throw Object.assign(new Error('agent pipe unavailable'), { code: 'AGENT_PIPE_UNAVAILABLE' });
|
|
55
|
+
const data = JSON.stringify(message) + '\n';
|
|
56
|
+
// Nothing was written, so this is a definite rejection rather than an
|
|
57
|
+
// unknown delivery outcome that would fail the whole daemon.
|
|
58
|
+
if (Buffer.byteLength(data) > maxFrameBytes) throw rpcError(-32600, 'agent input exceeds transport frame limit');
|
|
59
|
+
await new Promise((resolve, reject) => child.stdin.write(data, error => error ? reject(error) : resolve()));
|
|
60
|
+
},
|
|
61
|
+
close: () => closePromise ||= (async () => {
|
|
62
|
+
closing = true; child.stdin.end();
|
|
63
|
+
const term = setTimeout(() => child.kill('SIGTERM'), 2000);
|
|
64
|
+
const kill = setTimeout(() => child.kill('SIGKILL'), 5000);
|
|
65
|
+
try { await exited; } finally { clearTimeout(term); clearTimeout(kill); }
|
|
66
|
+
})().catch(error => { closePromise = undefined; throw error; }),
|
|
67
|
+
};
|
|
68
|
+
}
|
package/journal.mjs
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { closeSync, existsSync, fstatSync, fsyncSync, mkdirSync, openSync, readFileSync, readSync, writeSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { defaultJournalBytes, maxRecordBytes, replayBatchBytes } from './limits.mjs';
|
|
5
|
+
|
|
6
|
+
/** Append-only transport journal. fsync precedes publication and acknowledgments.
|
|
7
|
+
* An incomplete/corrupt tail is never silently discarded: it may describe an
|
|
8
|
+
* operation already delivered to a child process. Recovery must report ambiguity.
|
|
9
|
+
* The index stores offsets only, so SSE readers do not retain payloads in memory.
|
|
10
|
+
*/
|
|
11
|
+
export class Journal {
|
|
12
|
+
constructor(directory, maxBytes = defaultJournalBytes) {
|
|
13
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
14
|
+
this.directory = directory;
|
|
15
|
+
this.maxBytes = maxBytes;
|
|
16
|
+
this.path = join(directory, 'events.jsonl');
|
|
17
|
+
this.index = [];
|
|
18
|
+
this.calls = new Map();
|
|
19
|
+
this.pending = [];
|
|
20
|
+
this.pendingBytes = 0;
|
|
21
|
+
this.writeError = undefined;
|
|
22
|
+
this.fence = 0;
|
|
23
|
+
const epochPath = join(directory, 'epoch');
|
|
24
|
+
if (existsSync(epochPath)) this.epoch = readFileSync(epochPath, 'utf8').trim();
|
|
25
|
+
else {
|
|
26
|
+
this.epoch = randomUUID();
|
|
27
|
+
const fd = openSync(epochPath, 'wx', 0o600);
|
|
28
|
+
try { writeAll(fd, Buffer.from(this.epoch + '\n')); fsyncSync(fd); } finally { closeSync(fd); }
|
|
29
|
+
const dir = openSync(directory, 'r');
|
|
30
|
+
try { fsyncSync(dir); } finally { closeSync(dir); }
|
|
31
|
+
}
|
|
32
|
+
if (!/^[a-f0-9-]{36}$/.test(this.epoch)) throw new Error('invalid journal epoch');
|
|
33
|
+
this.fd = openSync(this.path, 'a+', 0o600);
|
|
34
|
+
try { this.#load(); } catch (error) { closeSync(this.fd); this.fd = undefined; throw error; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
#load() {
|
|
38
|
+
const size = fstatSync(this.fd).size;
|
|
39
|
+
if (size > this.maxBytes) throw new Error('journal exceeds configured capacity');
|
|
40
|
+
let offset = 0, pending = [], pendingBytes = 0, lineStart = 0;
|
|
41
|
+
const chunk = Buffer.alloc(64 * 1024);
|
|
42
|
+
while (offset < size) {
|
|
43
|
+
const n = readSync(this.fd, chunk, 0, Math.min(chunk.length, size - offset), offset);
|
|
44
|
+
if (!n) throw new Error('journal read ended before file boundary');
|
|
45
|
+
const chunkStart = offset;
|
|
46
|
+
offset += n;
|
|
47
|
+
let position = 0;
|
|
48
|
+
while (position < n) {
|
|
49
|
+
const end = chunk.indexOf(10, position);
|
|
50
|
+
if (end < 0) {
|
|
51
|
+
if (pendingBytes === 0) lineStart = chunkStart + position;
|
|
52
|
+
const part = Buffer.from(chunk.subarray(position, n));
|
|
53
|
+
pending.push(part);
|
|
54
|
+
pendingBytes += part.length;
|
|
55
|
+
if (pendingBytes > maxRecordBytes) throw new Error('journal record exceeds limit');
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
if (pendingBytes === 0) lineStart = chunkStart + position;
|
|
59
|
+
const part = Buffer.from(chunk.subarray(position, end));
|
|
60
|
+
if (part.length) { pending.push(part); pendingBytes += part.length; }
|
|
61
|
+
if (pendingBytes > maxRecordBytes) throw new Error('journal record exceeds limit');
|
|
62
|
+
const record = JSON.parse(Buffer.concat(pending, pendingBytes).toString('utf8'));
|
|
63
|
+
if (record.seq !== this.index.length + 1 || record.epoch !== this.epoch || !record.type) throw new Error(`journal sequence or epoch mismatch at byte ${lineStart}`);
|
|
64
|
+
this.index.push(lineStart);
|
|
65
|
+
this.#observe(record);
|
|
66
|
+
pending = [];
|
|
67
|
+
pendingBytes = 0;
|
|
68
|
+
position = end + 1;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (pendingBytes) throw new Error('journal has an incomplete tail; execution outcome requires reconciliation');
|
|
72
|
+
this.durableBytes = size;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
#observe(record) {
|
|
76
|
+
if (record.type === 'rpc.dispatch' || record.type === 'rpc.delivery') this.calls.set(record.key, { status: record.status, digest: record.digest });
|
|
77
|
+
if (record.type === 'daemon.fence') this.fence = record.fence;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Buffered inbound records become visible only after flush. Control records
|
|
81
|
+
// always flush the preceding batch before their caller may deliver a side effect.
|
|
82
|
+
append(partial, durable = true) {
|
|
83
|
+
if (this.writeError) throw this.writeError;
|
|
84
|
+
const record = { ...partial, seq: this.index.length + this.pending.length + 1, epoch: this.epoch };
|
|
85
|
+
const buf = Buffer.from(`${JSON.stringify(record)}\n`);
|
|
86
|
+
if (buf.length > maxRecordBytes) throw new Error('journal record exceeds limit');
|
|
87
|
+
const offset = this.durableBytes + this.pendingBytes;
|
|
88
|
+
if (offset + buf.length > this.maxBytes) {
|
|
89
|
+
this.writeError = Object.assign(new Error('journal capacity exhausted'), { code: 'JOURNAL_FULL', journalOperation: 'journal.capacity' });
|
|
90
|
+
throw this.writeError;
|
|
91
|
+
}
|
|
92
|
+
this.pending.push({ record, buf });
|
|
93
|
+
this.pendingBytes += buf.length;
|
|
94
|
+
if (durable || this.pending.length >= 128 || this.pendingBytes >= 256 * 1024) this.flush();
|
|
95
|
+
return record;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
flush() {
|
|
99
|
+
if (this.writeError) throw this.writeError;
|
|
100
|
+
if (!this.pending.length) return;
|
|
101
|
+
let offset = this.durableBytes;
|
|
102
|
+
let operation = 'journal.write';
|
|
103
|
+
try {
|
|
104
|
+
writeAll(this.fd, Buffer.concat(this.pending.map(entry => entry.buf), this.pendingBytes));
|
|
105
|
+
operation = 'journal.fsync';
|
|
106
|
+
fsyncSync(this.fd);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
// Never append beyond a potentially torn write or publish unflushed data.
|
|
109
|
+
// Node/libuv retries interrupted write/fsync syscalls (EINTR). A remaining
|
|
110
|
+
// error is not permission to replay this batch: an earlier short write
|
|
111
|
+
// may have persisted a prefix, and fsync EIO can leave durability unknown.
|
|
112
|
+
error.journalOperation = operation;
|
|
113
|
+
this.writeError = error;
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
for (const { record, buf } of this.pending) {
|
|
117
|
+
this.index.push(offset);
|
|
118
|
+
offset += buf.length;
|
|
119
|
+
this.#observe(record);
|
|
120
|
+
}
|
|
121
|
+
this.pending = [];
|
|
122
|
+
this.pendingBytes = 0;
|
|
123
|
+
this.durableBytes = offset;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
read(after, limit, maxBytes = replayBatchBytes) {
|
|
127
|
+
if (!Number.isSafeInteger(after) || after < 0 || after > this.index.length) throw new Error('invalid journal cursor');
|
|
128
|
+
const records = [];
|
|
129
|
+
let bytes = 0;
|
|
130
|
+
for (let seq = after + 1; seq <= this.index.length && records.length < limit; seq++) {
|
|
131
|
+
const start = this.index[seq - 1];
|
|
132
|
+
const end = seq < this.index.length ? this.index[seq] : this.durableBytes;
|
|
133
|
+
if (records.length && bytes + end - start > maxBytes) break;
|
|
134
|
+
bytes += end - start;
|
|
135
|
+
const buf = Buffer.alloc(end - start);
|
|
136
|
+
let read = 0;
|
|
137
|
+
while (read < buf.length) {
|
|
138
|
+
const n = readSync(this.fd, buf, read, buf.length - read, start + read);
|
|
139
|
+
if (!n) throw new Error('truncated journal record');
|
|
140
|
+
read += n;
|
|
141
|
+
}
|
|
142
|
+
records.push(JSON.parse(buf.toString('utf8')));
|
|
143
|
+
}
|
|
144
|
+
return { epoch: this.epoch, records, head: this.index.length };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
close() {
|
|
148
|
+
if (this.fd === undefined) return;
|
|
149
|
+
try { this.flush(); } finally { closeSync(this.fd); this.fd = undefined; }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function writeAll(fd, buffer) {
|
|
154
|
+
let offset = 0;
|
|
155
|
+
while (offset < buffer.length) {
|
|
156
|
+
const n = writeSync(fd, buffer, offset, buffer.length - offset);
|
|
157
|
+
if (!n) throw new Error('journal write made no progress');
|
|
158
|
+
offset += n; // Continue short writes from the acknowledged byte offset.
|
|
159
|
+
}
|
|
160
|
+
}
|
package/limits.mjs
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Transport bounds shared by the HTTP admission, agent pipes and journal.
|
|
2
|
+
*
|
|
3
|
+
* The controller's public Session ingress accepts at most a 32,000,000-byte
|
|
4
|
+
* UTF-8 request body. Re-encoding its decoded text without HTML escaping grows
|
|
5
|
+
* only U+2028/U+2029 (3 to 6 bytes), so a prompt or reply derived from one
|
|
6
|
+
* accepted request fits within 64,000,000 bytes plus a small envelope; even
|
|
7
|
+
* 3-byte replacement of invalid UTF-8 would stay below 96,000,000. These
|
|
8
|
+
* internal bounds therefore never reject such a request before the agent's own
|
|
9
|
+
* input handling decides. Each enclosing layer adds headroom for its envelope:
|
|
10
|
+
* an RPC body becomes one NDJSON pipe frame, and a frame becomes one journal
|
|
11
|
+
* record (also one SSE data line).
|
|
12
|
+
*/
|
|
13
|
+
export const maxRPCBytes = 128 * 1024 * 1024;
|
|
14
|
+
// Allow a maximum RPC at 1 MiB/s plus the existing 30s request allowance.
|
|
15
|
+
// Controller control requests add a separate 5s response margin.
|
|
16
|
+
export const rpcRequestTimeoutMS = 30000 + Math.ceil(maxRPCBytes / (1024 * 1024)) * 1000;
|
|
17
|
+
export const maxFrameBytes = maxRPCBytes + 1024 * 1024;
|
|
18
|
+
export const maxRecordBytes = maxFrameBytes + 1024 * 1024;
|
|
19
|
+
// Replay batches are byte-bounded; a single larger record still makes progress.
|
|
20
|
+
export const replayBatchBytes = 1024 * 1024;
|
|
21
|
+
/** Default journal capacity holds several maximum-size Turns, including each
|
|
22
|
+
* dispatched prompt and the agent's echoed input items. */
|
|
23
|
+
export const defaultJournalBytes = 1024 * 1024 * 1024;
|
package/log.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Structured diagnostics deliberately accept identifiers and codes only.
|
|
2
|
+
* Never pass RPC params, prompts, environment values, headers or provider bodies.
|
|
3
|
+
* The journal is the source of runtime events; stderr is for service operations.
|
|
4
|
+
*/
|
|
5
|
+
export function createLogger(component, sink = process.stderr) {
|
|
6
|
+
return (level, event, fields = {}) => {
|
|
7
|
+
sink.write(JSON.stringify({ time: new Date().toISOString(), level, component, event, ...fields }) + '\n');
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Safe error identity for operational logs. Error messages from SDKs may contain secrets. */
|
|
12
|
+
export function errorCode(error) {
|
|
13
|
+
return typeof error?.code === 'string' && /^[A-Z0-9_]+$/.test(error.code) ? error.code : 'INTERNAL_ERROR';
|
|
14
|
+
}
|
package/model-proxy.mjs
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { Agent as HttpAgent, createServer, request as httpRequest } from 'node:http';
|
|
2
|
+
import { Agent as HttpsAgent, request as httpsRequest } from 'node:https';
|
|
3
|
+
import { rootCertificates } from 'node:tls';
|
|
4
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
5
|
+
|
|
6
|
+
const hopHeaders = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer', 'transfer-encoding', 'upgrade'];
|
|
7
|
+
function forwardedHeaders(headers, upgrade = false) {
|
|
8
|
+
const result = { ...headers };
|
|
9
|
+
const nominated = String(headers.connection || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
|
10
|
+
for (const name of [...hopHeaders, ...nominated]) delete result[name];
|
|
11
|
+
if (upgrade) { result.connection = 'Upgrade'; result.upgrade = 'websocket'; }
|
|
12
|
+
return result;
|
|
13
|
+
}
|
|
14
|
+
function currentTrust(env, cache) {
|
|
15
|
+
const files = new Set(['/etc/ssl/certs/ca-certificates.crt', env.NODE_EXTRA_CA_CERTS, env.SSL_CERT_FILE].filter(Boolean));
|
|
16
|
+
const signatures = [];
|
|
17
|
+
for (const file of files) {
|
|
18
|
+
let stat;
|
|
19
|
+
try { stat = statSync(file); } catch (error) {
|
|
20
|
+
if (error.code !== 'ENOENT') throw error;
|
|
21
|
+
if (file === env.NODE_EXTRA_CA_CERTS || file === env.SSL_CERT_FILE) throw Object.assign(new Error('Configured CA bundle unavailable'), { code: 'CA_BUNDLE_UNAVAILABLE' });
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
signatures.push(`${file}:${stat.size}:${stat.mtimeMs}`);
|
|
25
|
+
}
|
|
26
|
+
const key = signatures.join('|');
|
|
27
|
+
if (cache.value?.key === key) return cache.value;
|
|
28
|
+
const ca = [...rootCertificates];
|
|
29
|
+
for (const file of files) {
|
|
30
|
+
if (existsSync(file)) ca.push(readFileSync(file));
|
|
31
|
+
}
|
|
32
|
+
// Do not destroy the previous agents here. They may own an in-flight model
|
|
33
|
+
// stream. Retire them after their requests finish; new requests use only the
|
|
34
|
+
// agent built from the current CA bundle.
|
|
35
|
+
if (cache.value) {
|
|
36
|
+
cache.retired ??= new Set();
|
|
37
|
+
cache.retired.add(cache.value);
|
|
38
|
+
cache.retireUnused?.();
|
|
39
|
+
}
|
|
40
|
+
const value = { key, ca, httpsAgent: new HttpsAgent({ keepAlive: true, ca }), httpAgent: new HttpAgent({ keepAlive: true }) };
|
|
41
|
+
cache.value = value;
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
function socketResponse(socket, status, headers = {}) {
|
|
45
|
+
socket.write(`HTTP/1.1 ${status} ${status === 101 ? 'Switching Protocols' : 'Model Transport'}\r\n`);
|
|
46
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
47
|
+
for (const item of Array.isArray(value) ? value : [value]) if (item !== undefined) socket.write(`${name}: ${item}\r\n`);
|
|
48
|
+
}
|
|
49
|
+
socket.write('\r\n');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// One fixed provider origin per runtime process. Request/response bodies and
|
|
53
|
+
// WebSocket frames stay opaque and use stream backpressure. The harness owns
|
|
54
|
+
// model retries and timeouts; this transport never replays requests or follows
|
|
55
|
+
// redirects. New upstream connections always read the current sandbox CA.
|
|
56
|
+
export async function createModelProxy(baseURL, env = process.env, options = {}) {
|
|
57
|
+
const upstream = new URL(baseURL);
|
|
58
|
+
if (!['http:', 'https:'].includes(upstream.protocol) || upstream.username || upstream.password || upstream.search || upstream.hash) throw new Error('Invalid model upstream URL');
|
|
59
|
+
if (upstream.protocol === 'http:' && !['127.0.0.1', '[::1]', 'localhost'].includes(upstream.hostname)) throw new Error('Model upstream requires HTTPS');
|
|
60
|
+
const prefix = upstream.pathname.replace(/\/$/, '');
|
|
61
|
+
const decodedPrefix = decodeURIComponent(prefix);
|
|
62
|
+
const requests = new Set(), sockets = new Set();
|
|
63
|
+
const trustCache = { value: undefined, retired: new Set() };
|
|
64
|
+
const retireUnusedTrust = () => {
|
|
65
|
+
for (const trust of trustCache.retired) {
|
|
66
|
+
if ([...requests].some(entry => entry.trust === trust)) continue;
|
|
67
|
+
trust.httpsAgent.destroy();
|
|
68
|
+
trust.httpAgent.destroy();
|
|
69
|
+
trustCache.retired.delete(trust);
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
trustCache.retireUnused = retireUnusedTrust;
|
|
73
|
+
let suspended = false, closed = false, closePromise;
|
|
74
|
+
const counters = { requests: 0, failures: 0 };
|
|
75
|
+
const diagnostic = options.onDiagnostic || (value => process.stderr.write(JSON.stringify(value) + '\n'));
|
|
76
|
+
const activeRequests = () => [...requests].filter(r => !r.websocket).length;
|
|
77
|
+
const server = createServer((req, res) => forward(req, res));
|
|
78
|
+
server.on('upgrade', (req, socket, head) => forward(req, null, socket, head));
|
|
79
|
+
server.on('connect', (_req, socket) => { socketResponse(socket, 405, { connection: 'close', 'content-length': 0 }); socket.end(); });
|
|
80
|
+
server.on('connection', socket => { sockets.add(socket); socket.once('close', () => sockets.delete(socket)); });
|
|
81
|
+
server.maxConnections = 128;
|
|
82
|
+
server.requestTimeout = 0; // Do not impose another model generation deadline.
|
|
83
|
+
server.headersTimeout = 30000;
|
|
84
|
+
|
|
85
|
+
function forward(req, res, socket, head) {
|
|
86
|
+
const websocket = !!socket;
|
|
87
|
+
const reply = status => {
|
|
88
|
+
if (res) { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end('{"error":{"type":"api_error","message":"Model transport unavailable"}}'); }
|
|
89
|
+
else { socketResponse(socket, status, { connection: 'close', 'content-length': 0 }); socket.end(); }
|
|
90
|
+
};
|
|
91
|
+
if (closed || suspended || requests.size >= 64) { reply(503); return; }
|
|
92
|
+
try {
|
|
93
|
+
// Validate decoded traversal as well as the raw prefix, but forward the
|
|
94
|
+
// original path/query bytes (provider signatures may depend on them).
|
|
95
|
+
if (!req.url.startsWith('/') || req.url.startsWith('//') || /[\\#]/.test(req.url)) throw new Error('invalid path');
|
|
96
|
+
const parsed = new URL(req.url, 'http://localhost');
|
|
97
|
+
const decodedPath = decodeURIComponent(parsed.pathname);
|
|
98
|
+
if (decodedPath.includes('\\') || decodedPath.split('/').some(part => part === '.' || part === '..')) throw new Error('invalid traversal');
|
|
99
|
+
for (const [path, scope] of [[parsed.pathname, prefix], [decodedPath, decodedPrefix]]) if (scope && path !== scope && !path.startsWith(scope + '/')) throw new Error('invalid prefix');
|
|
100
|
+
if (decodedPath.startsWith('//') || (websocket && (req.method !== 'GET' || String(req.headers.upgrade).toLowerCase() !== 'websocket'))) throw new Error('invalid upgrade');
|
|
101
|
+
} catch { reply(400); return; }
|
|
102
|
+
const entry = { websocket: false, outgoing: null, remote: null, trust: null, stopped: false };
|
|
103
|
+
requests.add(entry); counters.requests++;
|
|
104
|
+
const downstream = res || socket;
|
|
105
|
+
let connectTimer;
|
|
106
|
+
const cleanup = () => {
|
|
107
|
+
if (entry.stopped) return;
|
|
108
|
+
entry.stopped = true; clearTimeout(connectTimer);
|
|
109
|
+
entry.outgoing?.destroy(); entry.remote?.destroy();
|
|
110
|
+
requests.delete(entry);
|
|
111
|
+
retireUnusedTrust();
|
|
112
|
+
};
|
|
113
|
+
const fail = error => {
|
|
114
|
+
if (entry.stopped) return;
|
|
115
|
+
counters.failures++;
|
|
116
|
+
// Codes only: messages can contain URLs, credentials or provider bodies.
|
|
117
|
+
const code = /^[A-Z0-9_]+$/.test(error?.code || '') ? error.code : 'TRANSPORT_ERROR';
|
|
118
|
+
diagnostic({ event: 'model_transport_error', code, transport: websocket ? 'websocket' : 'http' });
|
|
119
|
+
if (res?.headersSent || entry.websocket) downstream.destroy();
|
|
120
|
+
else reply(502);
|
|
121
|
+
cleanup();
|
|
122
|
+
};
|
|
123
|
+
downstream.once('close', cleanup);
|
|
124
|
+
downstream.on('error', cleanup);
|
|
125
|
+
req.on('aborted', cleanup);
|
|
126
|
+
req.on('error', cleanup);
|
|
127
|
+
try {
|
|
128
|
+
const headers = forwardedHeaders(req.headers, websocket);
|
|
129
|
+
headers.host = upstream.host;
|
|
130
|
+
const request = upstream.protocol === 'https:' ? httpsRequest : httpRequest;
|
|
131
|
+
const trust = currentTrust(env, trustCache);
|
|
132
|
+
entry.trust = trust;
|
|
133
|
+
const outgoing = request(upstream, { method: req.method, path: req.url, headers, agent: upstream.protocol === 'https:' ? trust.httpsAgent : trust.httpAgent, rejectUnauthorized: true }, incoming => {
|
|
134
|
+
clearTimeout(connectTimer);
|
|
135
|
+
incoming.on('error', fail);
|
|
136
|
+
incoming.on('aborted', () => fail({ code: 'UPSTREAM_RESPONSE_ABORTED' }));
|
|
137
|
+
if (res) {
|
|
138
|
+
res.writeHead(incoming.statusCode, forwardedHeaders(incoming.headers));
|
|
139
|
+
res.flushHeaders();
|
|
140
|
+
incoming.pipe(res);
|
|
141
|
+
} else {
|
|
142
|
+
// Preserve a refused upgrade's status/headers; it is not a tunnel.
|
|
143
|
+
socketResponse(socket, incoming.statusCode, { ...forwardedHeaders(incoming.headers), connection: 'close' });
|
|
144
|
+
incoming.pipe(socket);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
entry.outgoing = outgoing;
|
|
148
|
+
outgoing.once('socket', remote => {
|
|
149
|
+
const established = upstream.protocol === 'https:' ? 'secureConnect' : 'connect';
|
|
150
|
+
const connecting = remote.connecting === true || (upstream.protocol === 'https:' && remote.secureConnecting === true);
|
|
151
|
+
if (connecting) {
|
|
152
|
+
connectTimer = setTimeout(() => fail({ code: 'UPSTREAM_CONNECT_TIMEOUT' }), options.connectTimeoutMs || 30000);
|
|
153
|
+
connectTimer.unref();
|
|
154
|
+
remote.once(established, () => clearTimeout(connectTimer));
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
outgoing.on('error', fail);
|
|
158
|
+
outgoing.on('upgrade', (incoming, remote, upstreamHead) => {
|
|
159
|
+
clearTimeout(connectTimer);
|
|
160
|
+
if (!websocket || entry.stopped) { remote.destroy(); fail({ code: 'UNEXPECTED_UPGRADE' }); return; }
|
|
161
|
+
entry.websocket = true; entry.remote = remote;
|
|
162
|
+
socketResponse(socket, incoming.statusCode, forwardedHeaders(incoming.headers, true));
|
|
163
|
+
if (upstreamHead.length) socket.write(upstreamHead);
|
|
164
|
+
if (head.length) remote.write(head);
|
|
165
|
+
remote.on('error', fail);
|
|
166
|
+
remote.once('close', () => { socket.destroy(); cleanup(); });
|
|
167
|
+
socket.pipe(remote); remote.pipe(socket);
|
|
168
|
+
});
|
|
169
|
+
req.pipe(outgoing);
|
|
170
|
+
} catch (error) { fail(error); }
|
|
171
|
+
}
|
|
172
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
|
173
|
+
return {
|
|
174
|
+
url: `http://127.0.0.1:${server.address().port}${prefix}`,
|
|
175
|
+
get activeRequests() { return activeRequests(); },
|
|
176
|
+
snapshot: () => ({ ...counters, active_requests: activeRequests(), websocket_connections: [...requests].filter(r => r.websocket).length, suspended }),
|
|
177
|
+
// The adapter must first establish a runtime-safe idle/approval boundary.
|
|
178
|
+
// An open WebSocket can be idle; close it before freezing so the next model
|
|
179
|
+
// request reconnects with fresh trust instead of reusing a stale tunnel.
|
|
180
|
+
suspend() {
|
|
181
|
+
if (activeRequests()) throw new Error('Model requests are still active');
|
|
182
|
+
suspended = true;
|
|
183
|
+
for (const entry of requests) { entry.remote?.destroy(); entry.outgoing?.destroy(); }
|
|
184
|
+
trustCache.value?.httpsAgent.destroy();
|
|
185
|
+
trustCache.value?.httpAgent.destroy();
|
|
186
|
+
for (const trust of trustCache.retired) { trust.httpsAgent.destroy(); trust.httpAgent.destroy(); }
|
|
187
|
+
trustCache.retired.clear();
|
|
188
|
+
server.closeIdleConnections();
|
|
189
|
+
},
|
|
190
|
+
resume() { if (closed) throw new Error('Model transport is closed'); suspended = false; },
|
|
191
|
+
close: () => closePromise ||= new Promise((resolve, reject) => {
|
|
192
|
+
closed = true; suspended = true;
|
|
193
|
+
for (const entry of requests) { entry.remote?.destroy(); entry.outgoing?.destroy(); }
|
|
194
|
+
trustCache.value?.httpsAgent.destroy();
|
|
195
|
+
trustCache.value?.httpAgent.destroy();
|
|
196
|
+
for (const trust of trustCache.retired) { trust.httpsAgent.destroy(); trust.httpAgent.destroy(); }
|
|
197
|
+
trustCache.retired.clear();
|
|
198
|
+
for (const socket of sockets) socket.destroy();
|
|
199
|
+
server.close(error => error && error.code !== 'ERR_SERVER_NOT_RUNNING' ? reject(error) : resolve());
|
|
200
|
+
}).catch(error => { closePromise = undefined; throw error; }),
|
|
201
|
+
};
|
|
202
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentapi-sandbox-daemon-runtime",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Common HTTP/SSE transport and supervision for AgentAPI sandbox daemons",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": { "node": ">=22" },
|
|
7
|
+
"exports": {
|
|
8
|
+
"./runtime.mjs": "./runtime.mjs",
|
|
9
|
+
"./supervisor.mjs": "./supervisor.mjs",
|
|
10
|
+
"./child.mjs": "./child.mjs",
|
|
11
|
+
"./rpc.mjs": "./rpc.mjs",
|
|
12
|
+
"./log.mjs": "./log.mjs",
|
|
13
|
+
"./limits.mjs": "./limits.mjs",
|
|
14
|
+
"./journal.mjs": "./journal.mjs",
|
|
15
|
+
"./model-proxy.mjs": "./model-proxy.mjs"
|
|
16
|
+
},
|
|
17
|
+
"files": ["child.mjs", "journal.mjs", "limits.mjs", "log.mjs", "model-proxy.mjs", "rpc.mjs", "runtime.mjs", "supervisor.mjs", "package.json", "README.md"],
|
|
18
|
+
"publishConfig": { "access": "public" }
|
|
19
|
+
}
|
package/rpc.mjs
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Protocol errors known to occur before an operation takes effect. Unknown
|
|
2
|
+
* exceptions are not converted into a retryable rejection: their outcome may
|
|
3
|
+
* already have reached the agent, so the daemon fails closed instead.
|
|
4
|
+
*/
|
|
5
|
+
export function rpcError(code, message) { return Object.assign(new Error(message), { code }); }
|
|
6
|
+
export function httpError(status, code, message) { return Object.assign(new Error(message), { status, code }); }
|
|
7
|
+
|
|
8
|
+
export function validateRPC(message) {
|
|
9
|
+
if (!message || Array.isArray(message) || typeof message !== 'object' ||
|
|
10
|
+
(message.jsonrpc !== undefined && message.jsonrpc !== '2.0')) throw httpError(400, 'INVALID_RPC', 'expected one JSON-RPC message');
|
|
11
|
+
if (Object.hasOwn(message, 'id') && !((typeof message.id === 'string' && message.id.length > 0 && message.id.length <= 256) || Number.isSafeInteger(message.id))) {
|
|
12
|
+
throw httpError(400, 'INVALID_RPC_ID', 'RPC id must be a non-empty string or safe integer');
|
|
13
|
+
}
|
|
14
|
+
if (Object.hasOwn(message, 'method')) {
|
|
15
|
+
if (typeof message.method !== 'string' || !message.method || message.method.length > 256 || Object.hasOwn(message, 'result') || Object.hasOwn(message, 'error')) {
|
|
16
|
+
throw httpError(400, 'INVALID_RPC_REQUEST', 'invalid RPC request or notification');
|
|
17
|
+
}
|
|
18
|
+
} else if (!Object.hasOwn(message, 'id') || Object.hasOwn(message, 'result') === Object.hasOwn(message, 'error')) {
|
|
19
|
+
throw httpError(400, 'INVALID_RPC_RESPONSE', 'response requires id and exactly one result or error');
|
|
20
|
+
}
|
|
21
|
+
return message;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Distinguishes numeric and string IDs, which JSON-RPC treats as different. */
|
|
25
|
+
export const rpcID = id => JSON.stringify(id);
|
package/runtime.mjs
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { Journal } from './journal.mjs';
|
|
6
|
+
import { createLogger, errorCode } from './log.mjs';
|
|
7
|
+
import { maxRPCBytes, rpcRequestTimeoutMS } from './limits.mjs';
|
|
8
|
+
import { httpError, validateRPC } from './rpc.mjs';
|
|
9
|
+
|
|
10
|
+
export const protocolVersion = 2;
|
|
11
|
+
const agentName = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
12
|
+
const stable = value => Array.isArray(value) ? value.map(stable) : value && typeof value === 'object'
|
|
13
|
+
? Object.fromEntries(Object.keys(value).sort().map(key => [key, stable(value[key])])) : value;
|
|
14
|
+
const digest = value => createHash('sha256').update(JSON.stringify(stable(value))).digest('hex');
|
|
15
|
+
|
|
16
|
+
/** One authenticated transport around one agent adapter.
|
|
17
|
+
*
|
|
18
|
+
* POST /rpc records an outgoing message before delivery. HTTP 202 acknowledges
|
|
19
|
+
* admission only; results, requests and notifications arrive on the same SSE
|
|
20
|
+
* journal. Retrying the same delivery key never writes to the agent twice.
|
|
21
|
+
* The context header is opaque correlation supplied by the caller, not a
|
|
22
|
+
* Session/Turn understood by this module. Configuration and credentials are
|
|
23
|
+
* supplied separately in the protected options file and never journaled.
|
|
24
|
+
* The controller serializes RPC delivery and sandbox memory pause. The daemon
|
|
25
|
+
* retains unread events and does not own a consumer cursor or pause state.
|
|
26
|
+
*/
|
|
27
|
+
export async function serveDaemon(options, adapter, hooks = {}) {
|
|
28
|
+
if (typeof options.token !== 'string' || options.token.length < 32) throw new Error('daemon token requires at least 32 characters');
|
|
29
|
+
if (!adapter || !agentName.test(adapter.agent || '') || ['handle', 'quiescent', 'close'].some(key => typeof adapter[key] !== 'function')) throw new Error('incomplete daemon adapter');
|
|
30
|
+
const log = hooks.log || createLogger(adapter.agent);
|
|
31
|
+
const authHash = createHash('sha256').update(`Bearer ${options.token}`).digest();
|
|
32
|
+
const now = hooks.now || Date.now;
|
|
33
|
+
const generation = randomUUID();
|
|
34
|
+
const journal = new Journal(options.directory, options.maxBytes);
|
|
35
|
+
let failure = [...journal.calls.values()].some(row => row.status === 'dispatching' || row.status === 'unknown') ? 'DELIVERY_OUTCOME_UNKNOWN' : '';
|
|
36
|
+
let failureDetail = failure ? { code: failure, operation: 'journal.recovery' } : undefined;
|
|
37
|
+
let context = '', closing = false, modelProxy, closePromise, flushTimer, failureClosePromise;
|
|
38
|
+
let failureStopped = false;
|
|
39
|
+
const waiters = new Set(), streams = new Set(), operations = new Set();
|
|
40
|
+
const activeModel = () => modelProxy?.activeRequests || 0;
|
|
41
|
+
const wakeWaiters = () => { for (const done of waiters) done(); };
|
|
42
|
+
|
|
43
|
+
function safeFailureDetail(code, error, operation) {
|
|
44
|
+
// Do not copy arbitrary messages, paths or provider bodies. Codes and
|
|
45
|
+
// operation names preserve the actual OS cause without leaking inputs.
|
|
46
|
+
const detail = { code, operation: error?.journalOperation || operation };
|
|
47
|
+
if (error) detail.cause_code = errorCode(error);
|
|
48
|
+
if (Number.isSafeInteger(error?.errno)) detail.errno = error.errno;
|
|
49
|
+
return detail;
|
|
50
|
+
}
|
|
51
|
+
function fail(code, error, operation = 'daemon') {
|
|
52
|
+
if (failure) return;
|
|
53
|
+
failure = code;
|
|
54
|
+
failureDetail = safeFailureDetail(code, error, operation);
|
|
55
|
+
log('error', 'daemon_failed', { ...failureDetail, generation });
|
|
56
|
+
// A failed journal cannot produce a trustworthy SSE terminal record. Close
|
|
57
|
+
// existing streams so the controller immediately performs /state recovery.
|
|
58
|
+
for (const res of streams) res.destroy();
|
|
59
|
+
wakeWaiters();
|
|
60
|
+
// A failed journal must stop the agent: further effects could not be observed.
|
|
61
|
+
stopFailedAgent();
|
|
62
|
+
}
|
|
63
|
+
function stopFailedAgent() {
|
|
64
|
+
if (failureStopped) return;
|
|
65
|
+
failureClosePromise ||= Promise.resolve().then(async () => {
|
|
66
|
+
await adapter.close();
|
|
67
|
+
await Promise.allSettled([...operations]);
|
|
68
|
+
await modelProxy?.close();
|
|
69
|
+
failureStopped = true;
|
|
70
|
+
}).catch(error => {
|
|
71
|
+
failureClosePromise = undefined;
|
|
72
|
+
log('error', 'agent_shutdown_failed', { code: errorCode(error) });
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
function flushJournal() {
|
|
76
|
+
clearTimeout(flushTimer); flushTimer = undefined;
|
|
77
|
+
journal.flush();
|
|
78
|
+
wakeWaiters();
|
|
79
|
+
}
|
|
80
|
+
function publish(event, durable = true) {
|
|
81
|
+
if (failure && event.type !== 'daemon.started') throw httpError(503, failure, 'daemon has failed');
|
|
82
|
+
try {
|
|
83
|
+
const previousHead = journal.index.length;
|
|
84
|
+
const record = journal.append({ context, ...event, generation }, durable);
|
|
85
|
+
// Durable appends flush synchronously inside Journal.append. Wake an SSE
|
|
86
|
+
// reader for those records as well; the delayed path above handles only
|
|
87
|
+
// buffered records.
|
|
88
|
+
if (journal.index.length > previousHead) wakeWaiters();
|
|
89
|
+
if (journal.pending.length && !flushTimer) flushTimer = setTimeout(() => {
|
|
90
|
+
try { flushJournal(); } catch (error) { fail('JOURNAL_WRITE_FAILED', error, 'journal.flush'); }
|
|
91
|
+
}, 10);
|
|
92
|
+
// Readers are woken by flushJournal only. A buffered record is not in
|
|
93
|
+
// the SSE-visible journal yet, so publishing a wake-up here would make
|
|
94
|
+
// a reader perform an empty read and potentially spin.
|
|
95
|
+
return record;
|
|
96
|
+
} catch (error) { fail(errorCode(error) === 'JOURNAL_FULL' ? 'JOURNAL_FULL' : 'JOURNAL_WRITE_FAILED', error, 'journal.append'); throw error; }
|
|
97
|
+
}
|
|
98
|
+
const bridge = {
|
|
99
|
+
emit(message) { validateRPC(message); return publish({ type: 'rpc', direction: 'inbound', message }, false); },
|
|
100
|
+
fail(code) {
|
|
101
|
+
publish({ type: 'daemon.failed', code });
|
|
102
|
+
fail(code, undefined, 'adapter.reported');
|
|
103
|
+
},
|
|
104
|
+
log,
|
|
105
|
+
async bindModelUpstream(upstream, env) {
|
|
106
|
+
if (modelProxy) return modelProxy.url;
|
|
107
|
+
const { createModelProxy } = await import('./model-proxy.mjs');
|
|
108
|
+
modelProxy = await createModelProxy(upstream, env, { onDiagnostic: event => log('warn', event.event, { code: event.code, transport: event.transport }) });
|
|
109
|
+
return modelProxy.url;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
function snapshot() {
|
|
113
|
+
return { version: protocolVersion, agent: adapter.agent, package: options.package || '', release: options.release || '', epoch: journal.epoch, generation, pid: process.pid,
|
|
114
|
+
failure_detail: failureDetail,
|
|
115
|
+
failure, quiescent: failure ? failureStopped && activeModel() === 0 : !operations.size && !journal.pending.length && adapter.quiescent() === true && activeModel() === 0,
|
|
116
|
+
head: journal.index.length, fence: journal.fence, model_active: activeModel(), model_transport: modelProxy?.snapshot() };
|
|
117
|
+
}
|
|
118
|
+
function checkGrant(grant) {
|
|
119
|
+
if (grant.generation !== generation) throw httpError(409, 'STALE_GENERATION', 'daemon process changed');
|
|
120
|
+
if (!Number.isSafeInteger(grant.fence) || grant.fence < 1 || grant.fence < journal.fence) throw httpError(409, 'STALE_FENCE', 'controller ownership changed');
|
|
121
|
+
if (!Number.isSafeInteger(grant.expiresAt) || now() >= grant.expiresAt || grant.expiresAt > now() + 120000) throw httpError(409, 'EXPIRED_GRANT', 'control grant expired or exceeds limit');
|
|
122
|
+
}
|
|
123
|
+
function grantOf(req) {
|
|
124
|
+
const expiresIn = Number(req.headers['x-daemon-expires-in-ms']);
|
|
125
|
+
const expiresAt = Number.isSafeInteger(expiresIn) && expiresIn > 0 && expiresIn <= 120000
|
|
126
|
+
? now() + expiresIn
|
|
127
|
+
: Number(req.headers['x-daemon-expires-at']);
|
|
128
|
+
return { generation: req.headers['x-daemon-generation'], fence: Number(req.headers['x-daemon-fence']), expiresAt };
|
|
129
|
+
}
|
|
130
|
+
function claim(grant) {
|
|
131
|
+
checkGrant(grant);
|
|
132
|
+
if (grant.fence > journal.fence) publish({ type: 'daemon.fence', fence: grant.fence });
|
|
133
|
+
}
|
|
134
|
+
function accept(message, grant, key, callerContext) {
|
|
135
|
+
validateRPC(message);
|
|
136
|
+
if (typeof key !== 'string' || !key || key.length > 256 || typeof callerContext !== 'string' || callerContext.length > 256) throw httpError(400, 'INVALID_DELIVERY', 'delivery key and context are required');
|
|
137
|
+
claim(grant);
|
|
138
|
+
const content = digest({ message, context: callerContext });
|
|
139
|
+
const previous = journal.calls.get(key);
|
|
140
|
+
if (previous) {
|
|
141
|
+
if (previous.digest !== content) throw httpError(409, 'DELIVERY_CONFLICT', 'delivery key already has different content');
|
|
142
|
+
if (previous.status === 'unknown') throw httpError(409, 'DELIVERY_OUTCOME_UNKNOWN', 'delivery outcome requires reconciliation');
|
|
143
|
+
return { key, accepted: true };
|
|
144
|
+
}
|
|
145
|
+
if (failure || closing) throw httpError(503, failure || 'SHUTTING_DOWN', 'daemon cannot accept input');
|
|
146
|
+
if (operations.size >= 32) throw httpError(429, 'TOO_MANY_DELIVERIES', 'outstanding delivery limit reached');
|
|
147
|
+
if (journal.calls.size >= 100000) throw httpError(507, 'DELIVERY_CAPACITY', 'delivery journal capacity exhausted');
|
|
148
|
+
// A context changes only at a safe adapter boundary. Control replies retain
|
|
149
|
+
// the current context, even while the adapter is waiting for a callback.
|
|
150
|
+
if (callerContext !== context && (operations.size || !(adapter.idle ? adapter.idle() : adapter.quiescent()))) throw httpError(409, 'CONTEXT_BUSY', 'previous context is still active');
|
|
151
|
+
context = callerContext;
|
|
152
|
+
publish({ type: 'rpc.dispatch', key, digest: content, status: 'dispatching', direction: 'outbound', message });
|
|
153
|
+
const dispatchBridge = { ...bridge, checkGrant: () => { checkGrant(grant); if (closing || failure) throw httpError(409, 'INPUT_CLOSED', 'daemon input closed'); } };
|
|
154
|
+
const operation = Promise.resolve().then(() => adapter.handle(message, dispatchBridge)).then(() => {
|
|
155
|
+
publish({ type: 'rpc.delivery', key, digest: content, status: 'sent', context: callerContext });
|
|
156
|
+
}, error => {
|
|
157
|
+
const rejected = Number.isInteger(error.code) || !!error.status;
|
|
158
|
+
publish({ type: 'rpc.delivery', key, digest: content, status: rejected ? 'rejected' : 'unknown', context: callerContext, code: rejected ? String(error.code) : errorCode(error) });
|
|
159
|
+
if (rejected && message.method && Object.hasOwn(message, 'id')) {
|
|
160
|
+
bridge.emit({ jsonrpc: '2.0', id: message.id, error: { code: Number.isInteger(error.code) ? error.code : -32001, message: error.message } });
|
|
161
|
+
}
|
|
162
|
+
if (!rejected) { publish({ type: 'daemon.failed', code: 'DELIVERY_OUTCOME_UNKNOWN' }); fail('DELIVERY_OUTCOME_UNKNOWN'); }
|
|
163
|
+
log('error', 'rpc_delivery_failed', { key, code: rejected ? String(error.code) : errorCode(error) });
|
|
164
|
+
}).catch(error => fail(errorCode(error))).finally(() => operations.delete(operation));
|
|
165
|
+
operations.add(operation);
|
|
166
|
+
return { key, accepted: true };
|
|
167
|
+
}
|
|
168
|
+
async function body(req) {
|
|
169
|
+
// The bound covers every request derived from the controller's public
|
|
170
|
+
// input contract (see limits.mjs); reject a declared overflow before reading.
|
|
171
|
+
if (Number(req.headers['content-length']) > maxRPCBytes) throw httpError(413, 'REQUEST_TOO_LARGE', 'RPC exceeds request limit');
|
|
172
|
+
const chunks = []; let length = 0;
|
|
173
|
+
for await (const chunk of req) {
|
|
174
|
+
length += chunk.length;
|
|
175
|
+
if (length > maxRPCBytes) throw httpError(413, 'REQUEST_TOO_LARGE', 'RPC exceeds request limit');
|
|
176
|
+
chunks.push(chunk);
|
|
177
|
+
}
|
|
178
|
+
try { return JSON.parse(Buffer.concat(chunks).toString()); } catch { throw httpError(400, 'INVALID_JSON', 'invalid JSON'); }
|
|
179
|
+
}
|
|
180
|
+
const server = createServer(async (req, res) => {
|
|
181
|
+
const send = (status, data) => {
|
|
182
|
+
if (res.destroyed || res.writableEnded) return;
|
|
183
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(data));
|
|
184
|
+
};
|
|
185
|
+
try {
|
|
186
|
+
const actual = createHash('sha256').update(req.headers.authorization || '').digest();
|
|
187
|
+
if (!timingSafeEqual(actual, authHash)) throw httpError(401, 'UNAUTHORIZED', 'unauthorized');
|
|
188
|
+
const url = new URL(req.url, 'http://daemon');
|
|
189
|
+
if (req.method === 'GET' && url.pathname === '/state') {
|
|
190
|
+
// A later recovery probe may retry a failed stop, never reopen input or
|
|
191
|
+
// clear the journal failure. Concurrent probes share the same attempt.
|
|
192
|
+
if (failure && !closing) stopFailedAgent();
|
|
193
|
+
return send(200, snapshot());
|
|
194
|
+
}
|
|
195
|
+
if (req.method === 'POST' && url.pathname === '/rpc') return send(202, accept(await body(req), grantOf(req), req.headers['x-daemon-request-id'], req.headers['x-daemon-context'] || ''));
|
|
196
|
+
if (req.method === 'GET' && url.pathname === '/events/stream') {
|
|
197
|
+
if (failure) throw httpError(503, failure, 'daemon has failed');
|
|
198
|
+
if (streams.size >= 16) throw httpError(429, 'STREAM_LIMIT', 'event stream limit reached');
|
|
199
|
+
if (url.searchParams.get('epoch') !== journal.epoch) throw httpError(409, 'EPOCH_CHANGED', 'journal epoch changed');
|
|
200
|
+
let after = Number(url.searchParams.get('cursor') || 0);
|
|
201
|
+
if (!Number.isSafeInteger(after) || after < 0 || after > journal.index.length) throw httpError(409, 'INVALID_CURSOR', 'invalid journal cursor');
|
|
202
|
+
res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-store', connection: 'keep-alive' });
|
|
203
|
+
res.flushHeaders(); streams.add(res);
|
|
204
|
+
let closed = false;
|
|
205
|
+
const heartbeat = setInterval(() => { if (!res.destroyed && !res.writableNeedDrain) res.write(': keep-alive\n\n'); }, 15000);
|
|
206
|
+
const cleanup = () => { closed = true; clearInterval(heartbeat); streams.delete(res); };
|
|
207
|
+
res.once('close', cleanup);
|
|
208
|
+
try {
|
|
209
|
+
while (!closed && !closing) {
|
|
210
|
+
for (const record of journal.read(after, 128).records) {
|
|
211
|
+
if (closed || closing) break;
|
|
212
|
+
if (!res.write(`id: ${record.seq}\nevent: source\ndata: ${JSON.stringify(record)}\n\n`)) await new Promise(resolve => {
|
|
213
|
+
const done = () => { res.off('drain', done); res.off('close', done); resolve(); };
|
|
214
|
+
res.once('drain', done); res.once('close', done);
|
|
215
|
+
});
|
|
216
|
+
after = record.seq;
|
|
217
|
+
}
|
|
218
|
+
if (closed || closing || after < journal.index.length) continue;
|
|
219
|
+
await new Promise(resolve => {
|
|
220
|
+
const done = () => { waiters.delete(done); res.off('close', done); resolve(); };
|
|
221
|
+
waiters.add(done); res.once('close', done);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
} finally { cleanup(); if (!res.destroyed) res.end(); }
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
throw httpError(404, 'NOT_FOUND', 'not found');
|
|
228
|
+
} catch (error) {
|
|
229
|
+
if (res.headersSent) { res.destroy(); return; }
|
|
230
|
+
if (!error.status) log('error', 'http_request_failed', { code: errorCode(error) });
|
|
231
|
+
send(error.status || 500, { code: error.status ? error.code : 'INTERNAL_ERROR', error: error.status ? error.message : 'daemon operation failed; inspect service diagnostics' });
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
server.requestTimeout = rpcRequestTimeoutMS; server.headersTimeout = 10000; server.maxConnections = 64;
|
|
235
|
+
try {
|
|
236
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(options.port, options.bind || '127.0.0.1', resolve); });
|
|
237
|
+
writeFileSync(join(options.directory, 'port'), String(server.address().port), { mode: 0o600 });
|
|
238
|
+
publish({ type: 'daemon.started', agent: adapter.agent });
|
|
239
|
+
if (failure) stopFailedAgent();
|
|
240
|
+
log('info', 'daemon_started', { generation, epoch: journal.epoch, port: server.address().port });
|
|
241
|
+
} catch (error) { server.close(); journal.close(); throw error; }
|
|
242
|
+
return { port: server.address().port, url: `http://127.0.0.1:${server.address().port}`, generation, snapshot, journal,
|
|
243
|
+
close: () => closePromise ||= (async () => {
|
|
244
|
+
closing = true;
|
|
245
|
+
for (const done of waiters) done();
|
|
246
|
+
for (const res of streams) res.destroy();
|
|
247
|
+
const errors = [];
|
|
248
|
+
try { await adapter.close(); } catch (error) { errors.push(error); }
|
|
249
|
+
await Promise.allSettled([...operations]);
|
|
250
|
+
try { await modelProxy?.close(); } catch (error) { errors.push(error); }
|
|
251
|
+
await new Promise(resolve => { server.close(resolve); server.closeIdleConnections(); });
|
|
252
|
+
clearTimeout(flushTimer);
|
|
253
|
+
try { journal.close(); } catch (error) { errors.push(error); }
|
|
254
|
+
log(errors.length ? 'error' : 'info', 'daemon_stopped', { generation, errors: errors.length });
|
|
255
|
+
if (errors.length) throw new AggregateError(errors, 'daemon shutdown failed');
|
|
256
|
+
})(),
|
|
257
|
+
};
|
|
258
|
+
}
|
package/supervisor.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { createServer } from 'node:net';
|
|
5
|
+
import { dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
|
+
import { createLogger, errorCode } from './log.mjs';
|
|
8
|
+
|
|
9
|
+
/** One supervisor owns a daemon process group. A kernel-held local socket is
|
|
10
|
+
* the singleton lock: it survives memory pause and is released on process death,
|
|
11
|
+
* with no stale timestamp or empty-PID-file race. Production Linux uses an
|
|
12
|
+
* abstract Unix socket; development platforms use a loopback port and fail
|
|
13
|
+
* closed if that port is occupied. No messages are accepted on this lock.
|
|
14
|
+
*/
|
|
15
|
+
const entry = process.argv[2], optionsPath = process.argv[3];
|
|
16
|
+
if (!entry || !optionsPath) throw new Error('supervisor requires entry and protected options file');
|
|
17
|
+
const directory = dirname(resolve(optionsPath));
|
|
18
|
+
const identity = createHash('sha256').update(directory).digest('hex');
|
|
19
|
+
const log = createLogger('supervisor');
|
|
20
|
+
const lock = createServer(socket => socket.destroy());
|
|
21
|
+
const lockAddress = process.platform === 'linux' ? { path: `\0agentapi-daemon-${identity.slice(0, 40)}` }
|
|
22
|
+
: { host: '127.0.0.1', port: 32768 + parseInt(identity.slice(0, 4), 16) % 28000 };
|
|
23
|
+
const acquired = await new Promise((resolve, reject) => {
|
|
24
|
+
lock.once('error', error => error.code === 'EADDRINUSE' ? resolve(false) : reject(error));
|
|
25
|
+
lock.listen(lockAddress, () => resolve(true));
|
|
26
|
+
});
|
|
27
|
+
if (!acquired) process.exit(0);
|
|
28
|
+
|
|
29
|
+
const pidPath = join(directory, 'supervisor.pid');
|
|
30
|
+
const childPath = join(directory, 'child.json');
|
|
31
|
+
const bootID = process.platform === 'linux' ? readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() : '';
|
|
32
|
+
let child, stopping = false, escalation;
|
|
33
|
+
writeFileSync(pidPath, String(process.pid), { mode: 0o600 });
|
|
34
|
+
|
|
35
|
+
function signalGroup(pid, signal) {
|
|
36
|
+
if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error('invalid owned process group');
|
|
37
|
+
// The group may still contain tools after its leader has exited. Checking
|
|
38
|
+
// whether the leader PID is alive would leak exactly those orphan children.
|
|
39
|
+
try { process.kill(-pid, signal); }
|
|
40
|
+
catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
41
|
+
}
|
|
42
|
+
async function terminateGroup(pid) {
|
|
43
|
+
signalGroup(pid, 'SIGTERM');
|
|
44
|
+
await delay(200);
|
|
45
|
+
signalGroup(pid, 'SIGKILL');
|
|
46
|
+
}
|
|
47
|
+
function stop() {
|
|
48
|
+
stopping = true;
|
|
49
|
+
if (child?.pid) {
|
|
50
|
+
signalGroup(child.pid, 'SIGTERM');
|
|
51
|
+
escalation ||= setTimeout(() => { if (child?.pid) signalGroup(child.pid, 'SIGKILL'); }, 5000);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
process.once('SIGTERM', stop); process.once('SIGINT', stop);
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
// Reclaim a group left by a killed supervisor only on the same Linux boot.
|
|
58
|
+
// Templates must not ship state directories. A new sandbox boot must never
|
|
59
|
+
// signal PIDs copied from another machine's installation.
|
|
60
|
+
try {
|
|
61
|
+
const old = JSON.parse(readFileSync(childPath, 'utf8'));
|
|
62
|
+
if (bootID && old.boot_id === bootID) { await terminateGroup(old.pid); log('warn', 'orphan_group_reaped', { pid: old.pid }); }
|
|
63
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
64
|
+
let failures = 0;
|
|
65
|
+
while (!stopping) {
|
|
66
|
+
const started = Date.now();
|
|
67
|
+
child = spawn(process.execPath, [entry, optionsPath], { cwd: directory, stdio: 'inherit', detached: true });
|
|
68
|
+
if (child.pid) writeFileSync(childPath, JSON.stringify({ pid: child.pid, boot_id: bootID }), { mode: 0o600 });
|
|
69
|
+
const outcome = await new Promise(resolve => {
|
|
70
|
+
child.once('error', error => resolve({ code: null, signal: null, error: errorCode(error) }));
|
|
71
|
+
child.once('exit', (code, signal) => resolve({ code, signal }));
|
|
72
|
+
});
|
|
73
|
+
if (child.pid) await terminateGroup(child.pid);
|
|
74
|
+
rmSync(childPath, { force: true }); child = undefined;
|
|
75
|
+
clearTimeout(escalation); escalation = undefined;
|
|
76
|
+
log(stopping ? 'info' : 'warn', 'daemon_exit', { exit_code: outcome.code, signal: outcome.signal, code: outcome.error });
|
|
77
|
+
if (stopping) break;
|
|
78
|
+
failures = Date.now() - started > 60000 ? 0 : Math.min(failures + 1, 6);
|
|
79
|
+
await delay(Math.min(30000, 250 * 2 ** failures));
|
|
80
|
+
}
|
|
81
|
+
} catch (error) {
|
|
82
|
+
log('error', 'supervisor_failed', { code: errorCode(error) });
|
|
83
|
+
if (child?.pid) await terminateGroup(child.pid);
|
|
84
|
+
process.exitCode = 1;
|
|
85
|
+
} finally {
|
|
86
|
+
clearTimeout(escalation);
|
|
87
|
+
rmSync(pidPath, { force: true });
|
|
88
|
+
await new Promise(resolve => lock.close(resolve));
|
|
89
|
+
}
|