agentapi-sandbox-daemon-runtime 0.1.0 → 0.1.2

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/child.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { maxFrameBytes } from './limits.mjs';
2
3
  import { errorCode } from './log.mjs';
4
+ import { rpcError } from './rpc.mjs';
3
5
 
4
6
  /** Owns pipe failure, bounded NDJSON decoding and graceful child shutdown.
5
7
  * Children inherit the supervisor's daemon process group. If the daemon dies,
@@ -8,7 +10,6 @@ import { errorCode } from './log.mjs';
8
10
  export function startChild(command, args, options, onMessage, onFailure, log) {
9
11
  const child = spawn(command, args, { cwd: options.cwd, env: options.env, stdio: ['pipe', 'pipe', 'pipe'] });
10
12
  let closing = false, failed = false, chunks = [], bufferedBytes = 0, exit;
11
- const maxFrameBytes = 8 * 1024 * 1024;
12
13
  const appendLinePart = part => { if (part.length) { chunks.push(part); bufferedBytes += part.length; } };
13
14
  const emitLine = () => {
14
15
  const line = Buffer.concat(chunks, bufferedBytes).toString('utf8');
@@ -52,7 +53,9 @@ export function startChild(command, args, options, onMessage, onFailure, log) {
52
53
  async write(message) {
53
54
  if (failed || closing || !child.stdin.writable) throw Object.assign(new Error('agent pipe unavailable'), { code: 'AGENT_PIPE_UNAVAILABLE' });
54
55
  const data = JSON.stringify(message) + '\n';
55
- if (Buffer.byteLength(data) > 4 * 1024 * 1024) throw Object.assign(new Error('agent input exceeds limit'), { code: 'AGENT_INPUT_TOO_LARGE' });
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');
56
59
  await new Promise((resolve, reject) => child.stdin.write(data, error => error ? reject(error) : resolve()));
57
60
  },
58
61
  close: () => closePromise ||= (async () => {
@@ -60,6 +63,6 @@ export function startChild(command, args, options, onMessage, onFailure, log) {
60
63
  const term = setTimeout(() => child.kill('SIGTERM'), 2000);
61
64
  const kill = setTimeout(() => child.kill('SIGKILL'), 5000);
62
65
  try { await exited; } finally { clearTimeout(term); clearTimeout(kill); }
63
- })(),
66
+ })().catch(error => { closePromise = undefined; throw error; }),
64
67
  };
65
68
  }
package/journal.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { closeSync, existsSync, fstatSync, fsyncSync, mkdirSync, openSync, readFileSync, readSync, writeSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ import { defaultJournalBytes, maxRecordBytes, replayBatchBytes } from './limits.mjs';
4
5
 
5
6
  /** Append-only transport journal. fsync precedes publication and acknowledgments.
6
7
  * An incomplete/corrupt tail is never silently discarded: it may describe an
@@ -8,7 +9,7 @@ import { join } from 'node:path';
8
9
  * The index stores offsets only, so SSE readers do not retain payloads in memory.
9
10
  */
10
11
  export class Journal {
11
- constructor(directory, maxBytes = 256 * 1024 * 1024) {
12
+ constructor(directory, maxBytes = defaultJournalBytes) {
12
13
  mkdirSync(directory, { recursive: true, mode: 0o700 });
13
14
  this.directory = directory;
14
15
  this.maxBytes = maxBytes;
@@ -51,13 +52,13 @@ export class Journal {
51
52
  const part = Buffer.from(chunk.subarray(position, n));
52
53
  pending.push(part);
53
54
  pendingBytes += part.length;
54
- if (pendingBytes > 8 * 1024 * 1024) throw new Error('journal record exceeds limit');
55
+ if (pendingBytes > maxRecordBytes) throw new Error('journal record exceeds limit');
55
56
  break;
56
57
  }
57
58
  if (pendingBytes === 0) lineStart = chunkStart + position;
58
59
  const part = Buffer.from(chunk.subarray(position, end));
59
60
  if (part.length) { pending.push(part); pendingBytes += part.length; }
60
- if (pendingBytes > 8 * 1024 * 1024) throw new Error('journal record exceeds limit');
61
+ if (pendingBytes > maxRecordBytes) throw new Error('journal record exceeds limit');
61
62
  const record = JSON.parse(Buffer.concat(pending, pendingBytes).toString('utf8'));
62
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}`);
63
64
  this.index.push(lineStart);
@@ -82,9 +83,12 @@ export class Journal {
82
83
  if (this.writeError) throw this.writeError;
83
84
  const record = { ...partial, seq: this.index.length + this.pending.length + 1, epoch: this.epoch };
84
85
  const buf = Buffer.from(`${JSON.stringify(record)}\n`);
85
- if (buf.length > 8 * 1024 * 1024) throw new Error('journal record exceeds limit');
86
+ if (buf.length > maxRecordBytes) throw new Error('journal record exceeds limit');
86
87
  const offset = this.durableBytes + this.pendingBytes;
87
- if (offset + buf.length > this.maxBytes) throw Object.assign(new Error('journal capacity exhausted'), { code: 'JOURNAL_FULL' });
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
+ }
88
92
  this.pending.push({ record, buf });
89
93
  this.pendingBytes += buf.length;
90
94
  if (durable || this.pending.length >= 128 || this.pendingBytes >= 256 * 1024) this.flush();
@@ -95,11 +99,17 @@ export class Journal {
95
99
  if (this.writeError) throw this.writeError;
96
100
  if (!this.pending.length) return;
97
101
  let offset = this.durableBytes;
102
+ let operation = 'journal.write';
98
103
  try {
99
104
  writeAll(this.fd, Buffer.concat(this.pending.map(entry => entry.buf), this.pendingBytes));
105
+ operation = 'journal.fsync';
100
106
  fsyncSync(this.fd);
101
107
  } catch (error) {
102
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;
103
113
  this.writeError = error;
104
114
  throw error;
105
115
  }
@@ -113,12 +123,15 @@ export class Journal {
113
123
  this.durableBytes = offset;
114
124
  }
115
125
 
116
- read(after, limit) {
126
+ read(after, limit, maxBytes = replayBatchBytes) {
117
127
  if (!Number.isSafeInteger(after) || after < 0 || after > this.index.length) throw new Error('invalid journal cursor');
118
128
  const records = [];
129
+ let bytes = 0;
119
130
  for (let seq = after + 1; seq <= this.index.length && records.length < limit; seq++) {
120
131
  const start = this.index[seq - 1];
121
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;
122
135
  const buf = Buffer.alloc(end - start);
123
136
  let read = 0;
124
137
  while (read < buf.length) {
@@ -142,6 +155,6 @@ function writeAll(fd, buffer) {
142
155
  while (offset < buffer.length) {
143
156
  const n = writeSync(fd, buffer, offset, buffer.length - offset);
144
157
  if (!n) throw new Error('journal write made no progress');
145
- offset += n;
158
+ offset += n; // Continue short writes from the acknowledged byte offset.
146
159
  }
147
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/model-proxy.mjs CHANGED
@@ -196,7 +196,7 @@ export async function createModelProxy(baseURL, env = process.env, options = {})
196
196
  for (const trust of trustCache.retired) { trust.httpsAgent.destroy(); trust.httpAgent.destroy(); }
197
197
  trustCache.retired.clear();
198
198
  for (const socket of sockets) socket.destroy();
199
- server.close(error => error ? reject(error) : resolve());
200
- }),
199
+ server.close(error => error && error.code !== 'ERR_SERVER_NOT_RUNNING' ? reject(error) : resolve());
200
+ }).catch(error => { closePromise = undefined; throw error; }),
201
201
  };
202
202
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentapi-sandbox-daemon-runtime",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Common HTTP/SSE transport and supervision for AgentAPI sandbox daemons",
5
5
  "type": "module",
6
6
  "engines": { "node": ">=22" },
@@ -10,9 +10,10 @@
10
10
  "./child.mjs": "./child.mjs",
11
11
  "./rpc.mjs": "./rpc.mjs",
12
12
  "./log.mjs": "./log.mjs",
13
+ "./limits.mjs": "./limits.mjs",
13
14
  "./journal.mjs": "./journal.mjs",
14
15
  "./model-proxy.mjs": "./model-proxy.mjs"
15
16
  },
16
- "files": ["child.mjs", "journal.mjs", "log.mjs", "model-proxy.mjs", "rpc.mjs", "runtime.mjs", "supervisor.mjs", "package.json", "README.md"],
17
+ "files": ["child.mjs", "journal.mjs", "limits.mjs", "log.mjs", "model-proxy.mjs", "rpc.mjs", "runtime.mjs", "supervisor.mjs", "package.json", "README.md"],
17
18
  "publishConfig": { "access": "public" }
18
19
  }
package/runtime.mjs CHANGED
@@ -4,6 +4,7 @@ import { writeFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import { Journal } from './journal.mjs';
6
6
  import { createLogger, errorCode } from './log.mjs';
7
+ import { maxRPCBytes, rpcRequestTimeoutMS } from './limits.mjs';
7
8
  import { httpError, validateRPC } from './rpc.mjs';
8
9
 
9
10
  export const protocolVersion = 2;
@@ -32,17 +33,44 @@ export async function serveDaemon(options, adapter, hooks = {}) {
32
33
  const generation = randomUUID();
33
34
  const journal = new Journal(options.directory, options.maxBytes);
34
35
  let failure = [...journal.calls.values()].some(row => row.status === 'dispatching' || row.status === 'unknown') ? 'DELIVERY_OUTCOME_UNKNOWN' : '';
35
- let context = '', closing = false, modelProxy, closePromise, flushTimer;
36
+ let failureDetail = failure ? { code: failure, operation: 'journal.recovery' } : undefined;
37
+ let context = '', closing = false, modelProxy, closePromise, flushTimer, failureClosePromise;
38
+ let failureStopped = false;
36
39
  const waiters = new Set(), streams = new Set(), operations = new Set();
37
40
  const activeModel = () => modelProxy?.activeRequests || 0;
38
41
  const wakeWaiters = () => { for (const done of waiters) done(); };
39
42
 
40
- function fail(code) {
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') {
41
52
  if (failure) return;
42
53
  failure = code;
43
- log('error', 'daemon_failed', { code, generation });
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();
44
60
  // A failed journal must stop the agent: further effects could not be observed.
45
- Promise.resolve(adapter.close()).catch(error => log('error', 'agent_shutdown_failed', { code: errorCode(error) }));
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
+ });
46
74
  }
47
75
  function flushJournal() {
48
76
  clearTimeout(flushTimer); flushTimer = undefined;
@@ -50,6 +78,7 @@ export async function serveDaemon(options, adapter, hooks = {}) {
50
78
  wakeWaiters();
51
79
  }
52
80
  function publish(event, durable = true) {
81
+ if (failure && event.type !== 'daemon.started') throw httpError(503, failure, 'daemon has failed');
53
82
  try {
54
83
  const previousHead = journal.index.length;
55
84
  const record = journal.append({ context, ...event, generation }, durable);
@@ -58,19 +87,19 @@ export async function serveDaemon(options, adapter, hooks = {}) {
58
87
  // buffered records.
59
88
  if (journal.index.length > previousHead) wakeWaiters();
60
89
  if (journal.pending.length && !flushTimer) flushTimer = setTimeout(() => {
61
- try { flushJournal(); } catch { fail('JOURNAL_WRITE_FAILED'); }
90
+ try { flushJournal(); } catch (error) { fail('JOURNAL_WRITE_FAILED', error, 'journal.flush'); }
62
91
  }, 10);
63
92
  // Readers are woken by flushJournal only. A buffered record is not in
64
93
  // the SSE-visible journal yet, so publishing a wake-up here would make
65
94
  // a reader perform an empty read and potentially spin.
66
95
  return record;
67
- } catch (error) { fail(errorCode(error) === 'JOURNAL_FULL' ? 'JOURNAL_FULL' : 'JOURNAL_WRITE_FAILED'); throw error; }
96
+ } catch (error) { fail(errorCode(error) === 'JOURNAL_FULL' ? 'JOURNAL_FULL' : 'JOURNAL_WRITE_FAILED', error, 'journal.append'); throw error; }
68
97
  }
69
98
  const bridge = {
70
99
  emit(message) { validateRPC(message); return publish({ type: 'rpc', direction: 'inbound', message }, false); },
71
100
  fail(code) {
72
101
  publish({ type: 'daemon.failed', code });
73
- fail(code);
102
+ fail(code, undefined, 'adapter.reported');
74
103
  },
75
104
  log,
76
105
  async bindModelUpstream(upstream, env) {
@@ -82,7 +111,8 @@ export async function serveDaemon(options, adapter, hooks = {}) {
82
111
  };
83
112
  function snapshot() {
84
113
  return { version: protocolVersion, agent: adapter.agent, package: options.package || '', release: options.release || '', epoch: journal.epoch, generation, pid: process.pid,
85
- failure, quiescent: !failure && !operations.size && !journal.pending.length && adapter.quiescent() === true && activeModel() === 0,
114
+ failure_detail: failureDetail,
115
+ failure, quiescent: failure ? failureStopped && activeModel() === 0 : !operations.size && !journal.pending.length && adapter.quiescent() === true && activeModel() === 0,
86
116
  head: journal.index.length, fence: journal.fence, model_active: activeModel(), model_transport: modelProxy?.snapshot() };
87
117
  }
88
118
  function checkGrant(grant) {
@@ -136,10 +166,13 @@ export async function serveDaemon(options, adapter, hooks = {}) {
136
166
  return { key, accepted: true };
137
167
  }
138
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');
139
172
  const chunks = []; let length = 0;
140
173
  for await (const chunk of req) {
141
174
  length += chunk.length;
142
- if (length > 4 * 1024 * 1024) throw httpError(413, 'REQUEST_TOO_LARGE', 'RPC exceeds request limit');
175
+ if (length > maxRPCBytes) throw httpError(413, 'REQUEST_TOO_LARGE', 'RPC exceeds request limit');
143
176
  chunks.push(chunk);
144
177
  }
145
178
  try { return JSON.parse(Buffer.concat(chunks).toString()); } catch { throw httpError(400, 'INVALID_JSON', 'invalid JSON'); }
@@ -153,9 +186,15 @@ export async function serveDaemon(options, adapter, hooks = {}) {
153
186
  const actual = createHash('sha256').update(req.headers.authorization || '').digest();
154
187
  if (!timingSafeEqual(actual, authHash)) throw httpError(401, 'UNAUTHORIZED', 'unauthorized');
155
188
  const url = new URL(req.url, 'http://daemon');
156
- if (req.method === 'GET' && url.pathname === '/state') return send(200, snapshot());
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
+ }
157
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'] || ''));
158
196
  if (req.method === 'GET' && url.pathname === '/events/stream') {
197
+ if (failure) throw httpError(503, failure, 'daemon has failed');
159
198
  if (streams.size >= 16) throw httpError(429, 'STREAM_LIMIT', 'event stream limit reached');
160
199
  if (url.searchParams.get('epoch') !== journal.epoch) throw httpError(409, 'EPOCH_CHANGED', 'journal epoch changed');
161
200
  let after = Number(url.searchParams.get('cursor') || 0);
@@ -192,11 +231,12 @@ export async function serveDaemon(options, adapter, hooks = {}) {
192
231
  send(error.status || 500, { code: error.status ? error.code : 'INTERNAL_ERROR', error: error.status ? error.message : 'daemon operation failed; inspect service diagnostics' });
193
232
  }
194
233
  });
195
- server.requestTimeout = 30000; server.headersTimeout = 10000; server.maxConnections = 64;
234
+ server.requestTimeout = rpcRequestTimeoutMS; server.headersTimeout = 10000; server.maxConnections = 64;
196
235
  try {
197
236
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(options.port, options.bind || '127.0.0.1', resolve); });
198
237
  writeFileSync(join(options.directory, 'port'), String(server.address().port), { mode: 0o600 });
199
238
  publish({ type: 'daemon.started', agent: adapter.agent });
239
+ if (failure) stopFailedAgent();
200
240
  log('info', 'daemon_started', { generation, epoch: journal.epoch, port: server.address().port });
201
241
  } catch (error) { server.close(); journal.close(); throw error; }
202
242
  return { port: server.address().port, url: `http://127.0.0.1:${server.address().port}`, generation, snapshot, journal,