@ulm0/gonogo 0.0.0-stage → 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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/bin/gonogo.js +18 -0
  4. package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
  7. package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
  8. package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
  9. package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
  10. package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
  11. package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
  12. package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
  13. package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  14. package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  15. package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  16. package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  17. package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  18. package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  19. package/dist/client/assets/index-BqCn1SM7.js +50 -0
  20. package/dist/client/assets/index-KZtFVMJG.css +1 -0
  21. package/dist/client/favicon.ico +0 -0
  22. package/dist/client/favicon.svg +1 -0
  23. package/dist/client/index.html +19 -0
  24. package/dist/server/audited.js +133 -0
  25. package/dist/server/blackbox.js +261 -0
  26. package/dist/server/board.js +123 -0
  27. package/dist/server/cleanroom.js +214 -0
  28. package/dist/server/clearance.js +158 -0
  29. package/dist/server/cli.js +763 -0
  30. package/dist/server/command.js +44 -0
  31. package/dist/server/constants.js +465 -0
  32. package/dist/server/docking.js +541 -0
  33. package/dist/server/downlink.js +191 -0
  34. package/dist/server/hangar.js +311 -0
  35. package/dist/server/home.js +520 -0
  36. package/dist/server/hooks.js +166 -0
  37. package/dist/server/hub.js +2642 -0
  38. package/dist/server/launcher.js +547 -0
  39. package/dist/server/livery.js +210 -0
  40. package/dist/server/logchart.js +58 -0
  41. package/dist/server/logsearch.js +112 -0
  42. package/dist/server/massbudget.js +169 -0
  43. package/dist/server/mcp.js +228 -0
  44. package/dist/server/migrate.js +122 -0
  45. package/dist/server/missionlog.js +211 -0
  46. package/dist/server/payload.js +168 -0
  47. package/dist/server/propellant.js +314 -0
  48. package/dist/server/providers.js +199 -0
  49. package/dist/server/recorder.js +176 -0
  50. package/dist/server/relay.js +300 -0
  51. package/dist/server/relaykinds.js +182 -0
  52. package/dist/server/relief.js +226 -0
  53. package/dist/server/rollout.js +172 -0
  54. package/dist/server/schedules.js +277 -0
  55. package/dist/server/tasks.js +272 -0
  56. package/dist/server/telemetry.js +110 -0
  57. package/dist/server/terminal.js +635 -0
  58. package/dist/server/uplinks.js +356 -0
  59. package/dist/server/web.js +1607 -0
  60. package/dist/shared/cron.js +149 -0
  61. package/dist/shared/fuel.js +18 -0
  62. package/dist/shared/livery.js +348 -0
  63. package/dist/shared/positions.js +132 -0
  64. package/dist/shared/protocol.js +245 -0
  65. package/package.json +84 -3
@@ -0,0 +1,520 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmodSync, closeSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync, } from 'node:fs';
3
+ import { appendFile, rename, unlink, writeFile } from 'node:fs/promises';
4
+ import { join, resolve } from 'node:path';
5
+ import { POSITION_IDS } from '../shared/positions.js';
6
+ import { ACTIVITY_STATUSES, KEYS_MAX, MODEL_PATTERN, PERMISSION_MODES, PROVIDERS, providerInfo, RESERVED_NAMES } from '../shared/protocol.js';
7
+ import { AGENT_NAME_PATTERN, AGENTS_DIR, AGENTS_FILE, BROWSER_TOKEN_FILE, COMMAND_MAX_CHARS, DIR_MODE, FILE_MODE, LOCK_FILE, MESSAGES_FILE, MESSAGES_ROTATE_BYTES, MESSAGES_ROTATED_FILE, MESSAGES_TAIL_BYTES, TOKEN_BYTES, nullLogger, } from './constants.js';
8
+ import { readCustomCommand } from './command.js';
9
+ import { migrateHome } from './migrate.js';
10
+ import { parseCleanRoom } from './cleanroom.js';
11
+ import { keyNameProblem } from './clearance.js';
12
+ import { parsePayload, payloadRefusal } from './payload.js';
13
+ const MODEL_RE = new RegExp(MODEL_PATTERN);
14
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
15
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
16
+ const TOKEN_RE = /^[0-9a-f]{64}$/i;
17
+ const MESSAGE_ID_RE = /^m(\d+)$/;
18
+ const LOCK_ATTEMPTS = 5;
19
+ /**
20
+ * Directories this process holds a lock on. A pid in a lock file can name this very process (containers reuse pids), so
21
+ * the file alone cannot tell "my own lock" from "the lock of a previous run that had my pid".
22
+ */
23
+ const heldDirs = new Set();
24
+ function errMessage(e) {
25
+ return e instanceof Error ? e.message : String(e);
26
+ }
27
+ function errCode(e) {
28
+ if (typeof e === 'object' && e !== null && 'code' in e && typeof e.code === 'string')
29
+ return e.code;
30
+ return undefined;
31
+ }
32
+ function isRecord(x) {
33
+ return typeof x === 'object' && x !== null && !Array.isArray(x);
34
+ }
35
+ function lockError(dir, pid) {
36
+ return new Error(`another gonogo is using ${dir} (pid ${pid}). Stop it, or delete ${join(dir, LOCK_FILE)} if none is running.`);
37
+ }
38
+ /** The pid in a lock file, or null when the content is not a positive integer. Throws ENOENT when the file is gone. */
39
+ function readLockPid(path) {
40
+ const m = /^\s*(\d+)\s*$/.exec(readFileSync(path, 'utf8'));
41
+ const pid = m ? Number(m[1]) : 0;
42
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
43
+ }
44
+ function isProcessAlive(pid) {
45
+ try {
46
+ process.kill(pid, 0);
47
+ return true;
48
+ }
49
+ catch (e) {
50
+ // EPERM means the process exists but belongs to someone else: still a live owner
51
+ return errCode(e) !== 'ESRCH';
52
+ }
53
+ }
54
+ /**
55
+ * A home or a token that another user owns, or that group and other can still reach after the chmod, is not private: the
56
+ * browser token and the roster would be theirs too, so the start is refused instead of carried on. A path that is not
57
+ * there yet is skipped (whoever creates it makes it private).
58
+ */
59
+ function requirePrivate(path, mode, what) {
60
+ const found = statSync(path, { throwIfNoEntry: false });
61
+ if (found === undefined)
62
+ return;
63
+ const own = 'use --home with a directory of your own';
64
+ if (what === 'directory' ? !found.isDirectory() : !found.isFile())
65
+ throw new Error(`${path} is not a ${what}; remove it or ${own}`);
66
+ const owner = process.getuid?.();
67
+ if (owner !== undefined && found.uid !== owner) {
68
+ throw new Error(`${path} belongs to another user (uid ${found.uid}); ${what === 'file' ? `delete it (a new token is made) or ${own}` : own}`);
69
+ }
70
+ let refused = '';
71
+ try {
72
+ chmodSync(path, mode);
73
+ }
74
+ catch (e) {
75
+ refused = ` (${errMessage(e)})`;
76
+ }
77
+ const bits = statSync(path).mode & 0o777;
78
+ if ((bits & 0o077) !== 0) {
79
+ throw new Error(`${path} is open to other users (mode ${bits.toString(8)}) and chmod ${mode.toString(8)} did not close it${refused}; have its owner run chmod ${mode.toString(8)} on it, or ${own}`);
80
+ }
81
+ }
82
+ function acquireLock(dir, key) {
83
+ if (heldDirs.has(key))
84
+ throw lockError(dir, process.pid);
85
+ const path = join(dir, LOCK_FILE);
86
+ let lastPid = '?';
87
+ for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt += 1) {
88
+ try {
89
+ const fd = openSync(path, 'wx', FILE_MODE);
90
+ try {
91
+ writeSync(fd, `${process.pid}\n`);
92
+ }
93
+ finally {
94
+ closeSync(fd);
95
+ }
96
+ heldDirs.add(key);
97
+ return;
98
+ }
99
+ catch (e) {
100
+ if (errCode(e) !== 'EEXIST')
101
+ throw e;
102
+ }
103
+ let pid;
104
+ try {
105
+ pid = readLockPid(path);
106
+ }
107
+ catch (e) {
108
+ if (errCode(e) === 'ENOENT')
109
+ continue;
110
+ throw e;
111
+ }
112
+ if (pid !== null) {
113
+ lastPid = pid;
114
+ // heldDirs does not have this directory, so a lock naming our own pid is a leftover of an earlier run
115
+ if (pid !== process.pid && isProcessAlive(pid))
116
+ throw lockError(dir, pid);
117
+ }
118
+ // shortcut: two servers that both find the same stale lock in the same millisecond can both win; use flock if that ever matters
119
+ try {
120
+ unlinkSync(path);
121
+ }
122
+ catch (e) {
123
+ if (errCode(e) !== 'ENOENT')
124
+ throw e;
125
+ }
126
+ }
127
+ throw lockError(dir, lastPid);
128
+ }
129
+ function isPermissionMode(x) {
130
+ return typeof x === 'string' && PERMISSION_MODES.includes(x);
131
+ }
132
+ function parseAgent(a) {
133
+ if (!isRecord(a))
134
+ return 'not an object';
135
+ const { name, role, dir, mode, sessionId, desk, boss, createdAt } = a;
136
+ if (typeof name !== 'string' || !NAME_RE.test(name))
137
+ return 'invalid name';
138
+ if (RESERVED_NAMES.includes(name))
139
+ return `${name}: a reserved name`;
140
+ if (typeof role !== 'string')
141
+ return `${name}: role must be a string`;
142
+ if (typeof dir !== 'string')
143
+ return `${name}: dir must be a string`;
144
+ if (!isPermissionMode(mode))
145
+ return `${name}: mode must be one of ${PERMISSION_MODES.join(', ')}`;
146
+ if (typeof sessionId !== 'string' || !UUID_RE.test(sessionId))
147
+ return `${name}: sessionId must be a UUID`;
148
+ if (typeof desk !== 'number' || !Number.isInteger(desk) || desk < 0)
149
+ return `${name}: desk must be a non-negative integer`;
150
+ if (typeof boss !== 'boolean')
151
+ return `${name}: boss must be true or false`;
152
+ if (typeof createdAt !== 'number' || !Number.isFinite(createdAt))
153
+ return `${name}: createdAt must be a number`;
154
+ const record = { name, role, dir, mode, sessionId, desk, boss, createdAt };
155
+ const { position, provider, command, payload, cleanRoom } = a;
156
+ if (position !== undefined) {
157
+ if (typeof position !== 'string' || !POSITION_IDS.includes(position))
158
+ return `${name}: unknown position`;
159
+ record.position = position;
160
+ }
161
+ if (provider !== undefined && !PROVIDERS.includes(provider)) {
162
+ return `${name}: provider must be one of ${PROVIDERS.join(', ')}`;
163
+ }
164
+ if (provider !== undefined && provider !== 'claude')
165
+ record.provider = provider;
166
+ if (command !== undefined) {
167
+ if (provider !== 'custom')
168
+ return `${name}: only a custom agent has a command`;
169
+ if (typeof command !== 'string' || command.length === 0 || command.length > COMMAND_MAX_CHARS) {
170
+ return `${name}: command must be 1 to ${COMMAND_MAX_CHARS} characters`;
171
+ }
172
+ try {
173
+ readCustomCommand(command);
174
+ }
175
+ catch (error) {
176
+ return `${name}: ${error instanceof Error ? error.message : String(error)}`;
177
+ }
178
+ record.command = command;
179
+ }
180
+ else if (provider === 'custom')
181
+ return `${name}: a custom agent needs a command`;
182
+ if (provider === 'custom' && boss)
183
+ return `${name}: the boss cannot be a custom agent`;
184
+ if (payload !== undefined) {
185
+ const checked = parsePayload(payload);
186
+ if (!checked.ok)
187
+ return `${name}: ${checked.error}`;
188
+ const refused = checked.payload && payloadRefusal(record.provider, checked.payload);
189
+ if (refused)
190
+ return `${name}: ${refused.error}`;
191
+ if (checked.payload)
192
+ record.payload = checked.payload;
193
+ }
194
+ if (cleanRoom !== undefined) {
195
+ const checked = parseCleanRoom(cleanRoom, record.provider);
196
+ if (!checked.ok)
197
+ return `${name}: ${checked.error}`;
198
+ record.cleanRoom = checked.cleanRoom;
199
+ }
200
+ const { model, keys } = a;
201
+ if (model !== undefined) {
202
+ if (typeof model !== 'string' || !MODEL_RE.test(model))
203
+ return `${name}: model is not a usable name`;
204
+ if (providerInfo(record.provider).model === null)
205
+ return `${name}: ${providerInfo(record.provider).label} takes no model setting`;
206
+ record.model = model;
207
+ }
208
+ if (keys !== undefined) {
209
+ if (!isRecord(keys) || Object.keys(keys).length > KEYS_MAX)
210
+ return `${name}: keys must be an object of at most ${KEYS_MAX} names`;
211
+ const names = {};
212
+ // shortcut: a name that a later gonogo reserves makes the roster unusable here (the start stops and names the agent); delete it from `keys` to go on
213
+ for (const [key, at] of Object.entries(keys)) {
214
+ if (keyNameProblem(key) !== null || typeof at !== 'number' || !Number.isFinite(at))
215
+ return `${name}: keys holds a name or a time that is not usable`;
216
+ names[key] = at;
217
+ }
218
+ if (Object.keys(names).length > 0)
219
+ record.keys = names;
220
+ }
221
+ return record;
222
+ }
223
+ function parseRoster(text, path) {
224
+ const fail = (reason) => new Error(`${path} is not usable (${reason}); fix or delete this file`);
225
+ let data;
226
+ try {
227
+ data = JSON.parse(text);
228
+ }
229
+ catch {
230
+ throw fail('not valid JSON');
231
+ }
232
+ if (!isRecord(data) || data.version !== 1 || !Array.isArray(data.agents)) {
233
+ throw fail('expected {"version":1,"agents":[...]}');
234
+ }
235
+ const seen = new Set();
236
+ const agents = data.agents.map((item, i) => {
237
+ const parsed = parseAgent(item);
238
+ if (typeof parsed === 'string')
239
+ throw fail(`agent ${i + 1}: ${parsed}`);
240
+ if (seen.has(parsed.name))
241
+ throw fail(`agent name "${parsed.name}" appears twice`);
242
+ seen.add(parsed.name);
243
+ return parsed;
244
+ });
245
+ return { version: 1, agents };
246
+ }
247
+ function isStatus(x) {
248
+ return typeof x === 'string' && ACTIVITY_STATUSES.includes(x);
249
+ }
250
+ /** A whole record opens an entry, a four-field line updates one. Anything else is unreadable (null). */
251
+ function parseMessageLine(line) {
252
+ let o;
253
+ try {
254
+ o = JSON.parse(line);
255
+ }
256
+ catch {
257
+ return null;
258
+ }
259
+ if (!isRecord(o) || typeof o.id !== 'string' || !isStatus(o.status))
260
+ return null;
261
+ const { id, status } = o;
262
+ const note = typeof o.note === 'string' ? o.note : null;
263
+ if (typeof o.from !== 'string') {
264
+ return typeof o.updatedAt === 'number' && Number.isFinite(o.updatedAt) ? { id, status, note, updatedAt: o.updatedAt } : null;
265
+ }
266
+ const { to, body, at } = o;
267
+ if (typeof to !== 'string' || typeof body !== 'string' || typeof at !== 'number' || !Number.isFinite(at))
268
+ return null;
269
+ return {
270
+ id,
271
+ from: o.from,
272
+ to,
273
+ subject: typeof o.subject === 'string' ? o.subject : '',
274
+ body,
275
+ inReplyTo: typeof o.inReplyTo === 'string' ? o.inReplyTo : null,
276
+ hops: typeof o.hops === 'number' && Number.isFinite(o.hops) ? o.hops : 0,
277
+ at,
278
+ status,
279
+ note,
280
+ updatedAt: typeof o.updatedAt === 'number' && Number.isFinite(o.updatedAt) ? o.updatedAt : at,
281
+ };
282
+ }
283
+ /**
284
+ * Whole lines inside the last `maxBytes` of a file; a line that starts before the window is dropped. null when the file
285
+ * does not exist. Reads only the window, so start-up stays fast whatever the file size.
286
+ */
287
+ function readTailLines(path, maxBytes) {
288
+ let fd;
289
+ try {
290
+ fd = openSync(path, 'r');
291
+ }
292
+ catch (e) {
293
+ if (errCode(e) === 'ENOENT')
294
+ return null;
295
+ throw e;
296
+ }
297
+ try {
298
+ const size = fstatSync(fd).size;
299
+ const start = Math.max(0, size - maxBytes);
300
+ // the byte before the window tells whether the window begins on a line boundary
301
+ const from = start > 0 ? start - 1 : 0;
302
+ const buf = Buffer.alloc(size - from);
303
+ let read = 0;
304
+ while (read < buf.length) {
305
+ const n = readSync(fd, buf, read, buf.length - read, from + read);
306
+ if (n === 0)
307
+ break;
308
+ read += n;
309
+ }
310
+ let begin = 0;
311
+ if (start > 0) {
312
+ const nl = buf.indexOf(0x0a);
313
+ if (nl === -1 || nl >= read)
314
+ return [];
315
+ begin = nl + 1;
316
+ }
317
+ return buf
318
+ .subarray(begin, read)
319
+ .toString('utf8')
320
+ .split('\n')
321
+ .filter((l) => l.trim() !== '');
322
+ }
323
+ finally {
324
+ closeSync(fd);
325
+ }
326
+ }
327
+ export function openHome(dir, log = nullLogger) {
328
+ const logger = log.child('home');
329
+ const root = resolve(dir);
330
+ const agentsRoot = join(root, AGENTS_DIR);
331
+ const rosterPath = join(root, AGENTS_FILE);
332
+ const messagesPath = join(root, MESSAGES_FILE);
333
+ const rotatedPath = join(root, MESSAGES_ROTATED_FILE);
334
+ const tokenPath = join(root, BROWSER_TOKEN_FILE);
335
+ // a home that exists is looked at before anything is put into it
336
+ requirePrivate(root, DIR_MODE, 'directory');
337
+ try {
338
+ mkdirSync(agentsRoot, { recursive: true, mode: DIR_MODE });
339
+ }
340
+ catch (e) {
341
+ throw new Error(`cannot create ${root}: ${errMessage(e)}`);
342
+ }
343
+ // mkdir's mode is cut by the umask and ignored for a directory that already exists (a restore or rsync may leave 0755)
344
+ for (const d of [root, agentsRoot])
345
+ requirePrivate(d, DIR_MODE, 'directory');
346
+ /** Sync on purpose: inside the append chain nothing can write between the check and the rename. Never throws. */
347
+ const rotateMessagesIfLarge = () => {
348
+ // shortcut: a rename that keeps failing warns on every append; add a latch if that ever floods the log
349
+ try {
350
+ if (statSync(messagesPath).size > MESSAGES_ROTATE_BYTES) {
351
+ renameSync(messagesPath, rotatedPath);
352
+ logger.info(`${MESSAGES_FILE} was larger than ${MESSAGES_ROTATE_BYTES} bytes; moved to ${MESSAGES_ROTATED_FILE}`);
353
+ }
354
+ }
355
+ catch (e) {
356
+ if (errCode(e) !== 'ENOENT')
357
+ logger.warn(`could not rotate ${MESSAGES_FILE}: ${errMessage(e)}`);
358
+ }
359
+ };
360
+ const lockKey = realpathSync(root);
361
+ acquireLock(root, lockKey);
362
+ const lockPath = join(root, LOCK_FILE);
363
+ const releaseLock = () => {
364
+ try {
365
+ if (readLockPid(lockPath) === process.pid)
366
+ unlinkSync(lockPath);
367
+ }
368
+ catch (e) {
369
+ if (errCode(e) !== 'ENOENT')
370
+ logger.warn(`could not remove ${lockPath}: ${errMessage(e)}`);
371
+ }
372
+ heldDirs.delete(lockKey);
373
+ };
374
+ let browserToken;
375
+ try {
376
+ requirePrivate(tokenPath, FILE_MODE, 'file');
377
+ let existing = '';
378
+ try {
379
+ existing = readFileSync(tokenPath, 'utf8').trim();
380
+ }
381
+ catch (e) {
382
+ if (errCode(e) !== 'ENOENT')
383
+ throw e;
384
+ }
385
+ if (TOKEN_RE.test(existing)) {
386
+ browserToken = existing;
387
+ }
388
+ else {
389
+ if (existing !== '')
390
+ logger.warn(`${tokenPath} did not hold a 64 character hex token; replacing it`);
391
+ browserToken = randomBytes(TOKEN_BYTES).toString('hex');
392
+ // only this process writes it (it holds the lock), and a torn write is replaced at the next start by the check above
393
+ writeFileSync(tokenPath, browserToken + '\n', { mode: FILE_MODE });
394
+ }
395
+ chmodSync(tokenPath, FILE_MODE);
396
+ // under the lock, before any store reads a file: an upgrade is written once, and a file of a newer gonogo stops the start
397
+ migrateHome(root, logger);
398
+ rotateMessagesIfLarge();
399
+ }
400
+ catch (e) {
401
+ releaseLock();
402
+ throw e;
403
+ }
404
+ let rosterChain = Promise.resolve();
405
+ let messageChain = Promise.resolve();
406
+ const writtenIds = new Set();
407
+ let closing = null;
408
+ // shortcut: no fsync before the rename, so a power cut can lose the last save but never leaves half a file; add one if that ever hurts
409
+ const writeRoster = async (data) => {
410
+ const tmp = join(root, `.${AGENTS_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
411
+ try {
412
+ await writeFile(tmp, data, { mode: FILE_MODE, flag: 'wx' });
413
+ await rename(tmp, rosterPath);
414
+ }
415
+ catch (e) {
416
+ await unlink(tmp).catch(() => undefined);
417
+ throw e;
418
+ }
419
+ };
420
+ const maxSeqIn = (path) => {
421
+ const lines = readTailLines(path, MESSAGES_TAIL_BYTES);
422
+ let max = 0;
423
+ for (const line of lines ?? []) {
424
+ let o;
425
+ try {
426
+ o = JSON.parse(line);
427
+ }
428
+ catch {
429
+ continue;
430
+ }
431
+ const m = isRecord(o) && typeof o.id === 'string' ? MESSAGE_ID_RE.exec(o.id) : null;
432
+ const n = m ? Number(m[1]) : 0;
433
+ if (Number.isSafeInteger(n) && n > max)
434
+ max = n;
435
+ }
436
+ return max;
437
+ };
438
+ return {
439
+ dir: root,
440
+ browserToken,
441
+ agentDir(name) {
442
+ if (typeof name !== 'string' || !NAME_RE.test(name))
443
+ throw new Error(`invalid agent name "${String(name)}"`);
444
+ return join(agentsRoot, name);
445
+ },
446
+ loadRoster() {
447
+ let text;
448
+ try {
449
+ text = readFileSync(rosterPath, 'utf8');
450
+ }
451
+ catch (e) {
452
+ if (errCode(e) === 'ENOENT')
453
+ return { version: 1, agents: [] };
454
+ throw new Error(`cannot read ${rosterPath}: ${errMessage(e)}; fix or delete this file`);
455
+ }
456
+ return parseRoster(text, rosterPath);
457
+ },
458
+ saveRoster(file) {
459
+ // serialised now: the caller may change the object before the chain gets to it
460
+ const json = JSON.stringify(file, null, 2);
461
+ const run = rosterChain.then(() => writeRoster(json));
462
+ rosterChain = run.catch(() => undefined);
463
+ return run;
464
+ },
465
+ appendMessage(record) {
466
+ let line;
467
+ try {
468
+ line = writtenIds.has(record.id)
469
+ ? JSON.stringify({ id: record.id, status: record.status, note: record.note, updatedAt: record.updatedAt })
470
+ : JSON.stringify(record);
471
+ }
472
+ catch (e) {
473
+ logger.error(`could not serialise message ${String(record.id)}: ${errMessage(e)}`);
474
+ return;
475
+ }
476
+ writtenIds.add(record.id);
477
+ messageChain = messageChain
478
+ .then(() => {
479
+ // a run adds lines for as long as it lives: the limit is checked here too, not only when the home is opened
480
+ rotateMessagesIfLarge();
481
+ return appendFile(messagesPath, line + '\n', { mode: FILE_MODE });
482
+ })
483
+ .catch((e) => logger.error(`could not append to ${MESSAGES_FILE}: ${errMessage(e)}`));
484
+ },
485
+ loadRecentMessages(limit) {
486
+ const lines = readTailLines(messagesPath, MESSAGES_TAIL_BYTES);
487
+ if (!lines || !(limit >= 1))
488
+ return [];
489
+ let unreadable = 0;
490
+ const byId = new Map();
491
+ for (const line of lines) {
492
+ const parsed = parseMessageLine(line);
493
+ if (parsed === null) {
494
+ unreadable += 1;
495
+ }
496
+ else if ('from' in parsed) {
497
+ byId.set(parsed.id, parsed);
498
+ }
499
+ else {
500
+ const current = byId.get(parsed.id);
501
+ if (current)
502
+ byId.set(parsed.id, { ...current, status: parsed.status, note: parsed.note, updatedAt: parsed.updatedAt });
503
+ }
504
+ }
505
+ if (unreadable > 0)
506
+ logger.warn(`${MESSAGES_FILE}: ignored ${unreadable} line(s) that could not be read`);
507
+ return [...byId.values()].sort((a, b) => a.at - b.at).slice(-Math.floor(limit));
508
+ },
509
+ lastMessageSeq() {
510
+ return maxSeqIn(messagesPath) || maxSeqIn(rotatedPath);
511
+ },
512
+ close() {
513
+ closing ??= (async () => {
514
+ await Promise.all([rosterChain, messageChain]);
515
+ releaseLock();
516
+ })();
517
+ return closing;
518
+ },
519
+ };
520
+ }
@@ -0,0 +1,166 @@
1
+ import { API_ERROR_CODES, HOOK_EVENTS } from '../shared/protocol.js';
2
+ import { AGENT_NAME_PATTERN, MAX_HOOK_BODY_BYTES } from './constants.js';
3
+ /* ---- HTTP plumbing shared by hooks.ts, mcp.ts and web.ts (this file sits at the bottom of their import order) ---- */
4
+ export function isRecord(x) {
5
+ return typeof x === 'object' && x !== null && !Array.isArray(x);
6
+ }
7
+ /** Recognises a HubError by its name and code, not by instanceof (protocol.ts: the hub's class is not imported here). */
8
+ export function hubErrorInfo(e) {
9
+ if (!(e instanceof Error) || e.name !== 'HubError' || !('code' in e))
10
+ return null;
11
+ const { code } = e;
12
+ if (typeof code !== 'string' || !API_ERROR_CODES.includes(code))
13
+ return null;
14
+ const field = 'field' in e && typeof e.field === 'string' ? e.field : undefined;
15
+ const info = { code: code, message: e.message };
16
+ if (field !== undefined)
17
+ info.field = field;
18
+ return info;
19
+ }
20
+ /** The token of an `Authorization: Bearer <token>` header, or null. */
21
+ export function bearerToken(header) {
22
+ const m = header === undefined ? null : /^Bearer +(\S+)$/i.exec(header);
23
+ return m ? m[1] : null;
24
+ }
25
+ export function sendText(res, status, text) {
26
+ if (res.headersSent || res.writableEnded)
27
+ return;
28
+ res.writeHead(status, { 'Content-Type': 'text/plain', 'Content-Length': Buffer.byteLength(text) });
29
+ res.end(text);
30
+ }
31
+ export function sendJson(res, status, body, headers = {}) {
32
+ if (res.headersSent || res.writableEnded)
33
+ return;
34
+ const text = JSON.stringify(body);
35
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(text), ...headers });
36
+ res.end(text);
37
+ }
38
+ export function sendApiError(res, status, error, code, field, headers = {}) {
39
+ const body = field === undefined ? { error, code } : { error, code, field };
40
+ sendJson(res, status, body, headers);
41
+ }
42
+ export function sendUnauthorized(res) {
43
+ sendApiError(res, 401, 'unauthorized', 'unauthorized', undefined, { 'WWW-Authenticate': 'Bearer' });
44
+ }
45
+ export function sendNotFound(res, error = 'not found') {
46
+ sendApiError(res, 404, error, 'not_found');
47
+ }
48
+ export function sendMethodNotAllowed(res, allow) {
49
+ sendApiError(res, 405, 'method not allowed', 'bad_request', undefined, { Allow: allow });
50
+ }
51
+ /**
52
+ * Collects a request body of at most `limit` bytes. Past the limit nothing more is kept and the rest is read and thrown
53
+ * away, so the client can finish sending and read the 413 instead of meeting a reset.
54
+ */
55
+ export function readBody(req, limit) {
56
+ return new Promise((resolve) => {
57
+ const declared = Number(req.headers['content-length']);
58
+ if (req.destroyed) {
59
+ resolve({ ok: false, reason: 'aborted' });
60
+ return;
61
+ }
62
+ if (req.readableEnded) {
63
+ resolve({ ok: true, body: Buffer.alloc(0) });
64
+ return;
65
+ }
66
+ if (Number.isFinite(declared) && declared > limit) {
67
+ req.resume();
68
+ resolve({ ok: false, reason: 'too_large' });
69
+ return;
70
+ }
71
+ const chunks = [];
72
+ let size = 0;
73
+ let settled = false;
74
+ const settle = (result) => {
75
+ if (settled)
76
+ return;
77
+ settled = true;
78
+ req.removeListener('data', onData);
79
+ req.removeListener('end', onEnd);
80
+ req.removeListener('error', onAbort);
81
+ req.removeListener('close', onAbort);
82
+ resolve(result);
83
+ };
84
+ const onData = (chunk) => {
85
+ size += chunk.length;
86
+ if (size > limit) {
87
+ settle({ ok: false, reason: 'too_large' });
88
+ req.resume();
89
+ return;
90
+ }
91
+ chunks.push(chunk);
92
+ };
93
+ const onEnd = () => settle({ ok: true, body: Buffer.concat(chunks, size) });
94
+ const onAbort = () => settle({ ok: false, reason: 'aborted' });
95
+ req.on('data', onData);
96
+ req.on('end', onEnd);
97
+ req.on('error', onAbort);
98
+ req.on('close', onAbort);
99
+ });
100
+ }
101
+ /* ---- the hook endpoint ---- */
102
+ function isHookEvent(event) {
103
+ return HOOK_EVENTS.includes(event);
104
+ }
105
+ /** Only a Stop reply may carry a decision, and only a block with a reason; every other shape lets the agent go on. */
106
+ function stopReplyBody(reply) {
107
+ if (isRecord(reply) && reply.decision === 'block' && typeof reply.reason === 'string' && reply.reason !== '') {
108
+ return { decision: 'block', reason: reply.reason };
109
+ }
110
+ return {};
111
+ }
112
+ export function createHookHandler(deps) {
113
+ const { hub, log } = deps;
114
+ const nameRe = new RegExp(AGENT_NAME_PATTERN);
115
+ return async (req, res, agentName, event) => {
116
+ const token = bearerToken(req.headers.authorization);
117
+ const identity = token === null ? null : deps.resolveToken(token);
118
+ if (!identity) {
119
+ sendUnauthorized(res);
120
+ return;
121
+ }
122
+ if (req.method !== 'POST') {
123
+ sendMethodNotAllowed(res, 'POST');
124
+ return;
125
+ }
126
+ if (!nameRe.test(agentName) || !isHookEvent(event)) {
127
+ sendNotFound(res);
128
+ return;
129
+ }
130
+ if (identity.agent !== agentName) {
131
+ sendApiError(res, 403, 'token does not belong to this agent', 'forbidden');
132
+ return;
133
+ }
134
+ const body = await readBody(req, MAX_HOOK_BODY_BYTES);
135
+ if (!body.ok) {
136
+ if (body.reason === 'too_large')
137
+ sendApiError(res, 413, 'hook body too large', 'too_large');
138
+ else
139
+ res.destroy();
140
+ return;
141
+ }
142
+ let payload = null;
143
+ try {
144
+ payload = JSON.parse(body.body.toString('utf8'));
145
+ }
146
+ catch {
147
+ // answered below: a body that is not JSON is the same 400 as one that is not an object
148
+ }
149
+ if (!isRecord(payload)) {
150
+ sendApiError(res, 400, 'hook body must be a JSON object', 'bad_request');
151
+ return;
152
+ }
153
+ let reply;
154
+ try {
155
+ // the hub reads every field defensively (protocol.ts), so the unchecked shape is what it expects
156
+ reply = hub.onHook({ agent: agentName, generation: identity.generation, event, payload: payload });
157
+ }
158
+ catch (e) {
159
+ log.error(`hook ${event} of ${agentName} failed`, e);
160
+ sendApiError(res, 500, 'internal error', 'internal');
161
+ return;
162
+ }
163
+ log.debug(`hook ${event} of ${agentName}`);
164
+ sendJson(res, 200, event === 'Stop' ? stopReplyBody(reply) : {});
165
+ };
166
+ }