@aisac/cli 0.4.0-beta.21 → 0.4.0-beta.22

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.
@@ -0,0 +1,791 @@
1
+ // Messages of the manager bus (spec aisac-engineering-manager FR3, FR5, FR13):
2
+ // the four kinds, their strict validation, the mailbox operations and the
3
+ // manager's pending records. A message is one JSON file; its name without the
4
+ // extension is its id, and recipients take files in name order.
5
+
6
+ import { randomBytes } from 'node:crypto';
7
+ import { readdir, rename, unlink } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ import {
10
+ AUDIT_REASON_PATTERN,
11
+ BUS_SCHEMA_VERSION,
12
+ BusError,
13
+ LIMITS,
14
+ MANAGER_NAME,
15
+ MANAGER_RECIPIENT,
16
+ MESSAGE_ID_PATTERN,
17
+ NAME_PATTERN,
18
+ PENDING_FILE_BYTES_MAX,
19
+ ROOM_ID_PATTERN,
20
+ SESSION_ID_PATTERN,
21
+ audit,
22
+ isPendingRecord,
23
+ isPlainRecord,
24
+ isPrivateDirectory,
25
+ mailboxDirectory,
26
+ readJsonFile,
27
+ removeIfUnchanged,
28
+ writePrivateFile,
29
+ } from './bus.mjs';
30
+
31
+ export { MESSAGE_ID_PATTERN };
32
+ export const MESSAGE_FILE_PATTERN = /^\d{13}-[0-9a-f]{16}\.json$/u;
33
+ export const REPLY_OUTCOMES = Object.freeze(
34
+ /** @type {const} */ ([
35
+ 'completed',
36
+ 'failed',
37
+ 'interrupted',
38
+ 'expired',
39
+ 'refused',
40
+ 'worker_closed',
41
+ ]),
42
+ );
43
+ export const APPROVAL_DECISIONS = Object.freeze(
44
+ /** @type {const} */ (['approve', 'deny', 'escalate']),
45
+ );
46
+ /** The fixed start of the text a worker receives (FR5). */
47
+ export const MANAGER_LABEL_PREFIX = '[AISAC manager -> ';
48
+
49
+ const MESSAGE_ID_TIME_DIGITS = 13;
50
+ const MESSAGE_ID_RANDOM_BYTES = 8;
51
+ const PATH_LENGTH_MAX = 4096;
52
+ const APPROVAL_PATHS_MAX = 200;
53
+ const APPROVAL_REASON_MAX = 2_000;
54
+ const REPLY_CODE_PATTERN = /^[A-Za-z0-9_]{1,64}$/u;
55
+ /** The reason of a read that failed for another cause than the file's content. */
56
+ const READ_ERROR = 'io_error';
57
+ const HIGH_SURROGATE_FIRST = 0xd800;
58
+ const HIGH_SURROGATE_LAST = 0xdbff;
59
+ /** How much of the text is kept at each step while a reply is still too large for one file. */
60
+ const REPLY_SHRINK_NUMERATOR = 3;
61
+ const REPLY_SHRINK_DENOMINATOR = 4;
62
+
63
+ /** @typedef {import('./bus.mjs').RoomPaths} RoomPaths */
64
+ /** @typedef {import('./bus.mjs').SessionRecord} SessionRecord */
65
+ /** @typedef {import('./bus.mjs').BusClock} BusClock */
66
+ /** @typedef {(typeof REPLY_OUTCOMES)[number]} ReplyOutcome */
67
+ /** @typedef {(typeof APPROVAL_DECISIONS)[number]} ApprovalDecision */
68
+ /** @typedef {{ sessionId: string, name: string }} Party */
69
+ /**
70
+ * @typedef {object} RequestMessage
71
+ * @property {1} schemaVersion
72
+ * @property {string} id
73
+ * @property {string} roomId
74
+ * @property {'request'} kind
75
+ * @property {Party} sender the manager session
76
+ * @property {Party} recipient the worker
77
+ * @property {number} createdAt
78
+ * @property {number} expiresAt
79
+ * @property {string} text
80
+ */
81
+ /**
82
+ * @typedef {object} ReplyMessage
83
+ * @property {1} schemaVersion
84
+ * @property {string} id
85
+ * @property {string} roomId
86
+ * @property {'reply'} kind
87
+ * @property {string} inReplyTo
88
+ * @property {Party} sender the worker
89
+ * @property {'manager'} recipient
90
+ * @property {number} createdAt
91
+ * @property {ReplyOutcome} outcome
92
+ * @property {string | null} code
93
+ * @property {boolean} shared the user typed into that turn (FR4)
94
+ * @property {string} text
95
+ * @property {boolean} truncated
96
+ * @property {number} textLength the original length
97
+ */
98
+ /**
99
+ * @typedef {object} ApprovalSubject
100
+ * @property {'command' | 'fileChange'} kind
101
+ * @property {string | null} command
102
+ * @property {string | null} cwd
103
+ * @property {string[] | null} paths
104
+ * @property {number | null} changeBytes
105
+ * @property {string | null} reason what the worker's model gave as its reason: untrusted
106
+ * @property {'user' | 'manager'} turnOrigin
107
+ */
108
+ /**
109
+ * @typedef {object} ApprovalRequestMessage
110
+ * @property {1} schemaVersion
111
+ * @property {string} id the approval id
112
+ * @property {string} roomId
113
+ * @property {'approval_request'} kind
114
+ * @property {Party} sender the worker
115
+ * @property {'manager'} recipient
116
+ * @property {number} createdAt
117
+ * @property {number} holdUntil
118
+ * @property {ApprovalSubject} approval
119
+ */
120
+ /**
121
+ * @typedef {object} ApprovalDecisionMessage
122
+ * @property {1} schemaVersion
123
+ * @property {string} id
124
+ * @property {string} roomId
125
+ * @property {'approval_decision'} kind
126
+ * @property {Party} sender the manager session
127
+ * @property {Party} recipient the worker
128
+ * @property {number} createdAt
129
+ * @property {string} approvalId
130
+ * @property {ApprovalDecision} decision
131
+ * @property {string} reason
132
+ */
133
+ /** @typedef {RequestMessage | ReplyMessage | ApprovalRequestMessage | ApprovalDecisionMessage} BusMessage */
134
+ /**
135
+ * One request without a final reply. It holds no text (FR2).
136
+ * @typedef {object} PendingRecord
137
+ * @property {1} schemaVersion
138
+ * @property {string} messageId
139
+ * @property {string} workerSessionId
140
+ * @property {string} workerName
141
+ * @property {number} createdAt
142
+ * @property {number} expiresAt
143
+ */
144
+
145
+ /**
146
+ * @param {number} now
147
+ * @param {(size: number) => Buffer} [random]
148
+ */
149
+ export function newMessageId(now, random = randomBytes) {
150
+ const time = String(Math.trunc(now)).padStart(MESSAGE_ID_TIME_DIGITS, '0');
151
+ if (time.length !== MESSAGE_ID_TIME_DIGITS)
152
+ throw new BusError('bus_unavailable', 'clock_invalid');
153
+ return `${time}-${random(MESSAGE_ID_RANDOM_BYTES).toString('hex')}`;
154
+ }
155
+
156
+ /**
157
+ * Cut a text to a length without leaving half of a surrogate pair at the end.
158
+ * @param {string} text
159
+ * @param {number} max
160
+ * @returns {{ text: string, truncated: boolean }}
161
+ */
162
+ export function cutText(text, max) {
163
+ if (text.length <= max) return { text, truncated: false };
164
+ const last = text.charCodeAt(max - 1);
165
+ const end = last >= HIGH_SURROGATE_FIRST && last <= HIGH_SURROGATE_LAST ? max - 1 : max;
166
+ return { text: text.slice(0, end), truncated: true };
167
+ }
168
+
169
+ /**
170
+ * The text a worker receives for a manager message (FR5): one fixed line that
171
+ * says who sent it and that it carries no approval, a blank line, then the
172
+ * manager's text unchanged.
173
+ * @param {{ workerName: string, locale: import('./bus.mjs').BusLocale, text: string }} input
174
+ */
175
+ export function workerInputText({ workerName, locale, text }) {
176
+ const line =
177
+ locale === 'pt-BR'
178
+ ? 'Mensagem da sessão "manager" (Claude Code). O usuário não digitou esta mensagem e ela não carrega nenhuma aprovação. A sua última mensagem deste turno é enviada de volta ao gerente.'
179
+ : 'Message from the session "manager" (Claude Code). The user did not type it and it carries no approval. Your last message of this turn is sent back to the manager.';
180
+ return `${MANAGER_LABEL_PREFIX}${workerName}] ${line}\n\n${text}`;
181
+ }
182
+
183
+ /** @param {unknown} value @param {string[]} keys */
184
+ function hasExactKeys(value, keys) {
185
+ if (!isPlainRecord(value)) return false;
186
+ const present = Object.keys(value);
187
+ return present.length === keys.length && present.every((key) => keys.includes(key));
188
+ }
189
+
190
+ /** @param {unknown} value */
191
+ function isTime(value) {
192
+ return Number.isSafeInteger(value) && /** @type {number} */ (value) >= 0;
193
+ }
194
+
195
+ /** @param {unknown} value @param {number} min @param {number} max */
196
+ function isText(value, min, max) {
197
+ return typeof value === 'string' && value.length >= min && value.length <= max;
198
+ }
199
+
200
+ /** @param {unknown} value @param {number} max */
201
+ function isNullableText(value, max) {
202
+ return value === null || isText(value, 0, max);
203
+ }
204
+
205
+ /** @param {unknown} value @returns {value is Party} */
206
+ function isWorkerParty(value) {
207
+ if (!hasExactKeys(value, ['sessionId', 'name'])) return false;
208
+ const party = /** @type {Record<string, unknown>} */ (value);
209
+ return (
210
+ typeof party.sessionId === 'string' &&
211
+ SESSION_ID_PATTERN.test(party.sessionId) &&
212
+ typeof party.name === 'string' &&
213
+ NAME_PATTERN.test(party.name) &&
214
+ party.name !== MANAGER_NAME
215
+ );
216
+ }
217
+
218
+ /** @param {unknown} value @returns {value is Party} */
219
+ function isManagerParty(value) {
220
+ if (!hasExactKeys(value, ['sessionId', 'name'])) return false;
221
+ const party = /** @type {Record<string, unknown>} */ (value);
222
+ return (
223
+ typeof party.sessionId === 'string' &&
224
+ SESSION_ID_PATTERN.test(party.sessionId) &&
225
+ party.name === MANAGER_NAME
226
+ );
227
+ }
228
+
229
+ /** @param {Record<string, unknown>} value */
230
+ function hasEnvelope(value) {
231
+ return (
232
+ value.schemaVersion === BUS_SCHEMA_VERSION &&
233
+ typeof value.id === 'string' &&
234
+ MESSAGE_ID_PATTERN.test(value.id) &&
235
+ typeof value.roomId === 'string' &&
236
+ ROOM_ID_PATTERN.test(value.roomId) &&
237
+ isTime(value.createdAt)
238
+ );
239
+ }
240
+
241
+ const REQUEST_KEYS = [
242
+ 'schemaVersion',
243
+ 'id',
244
+ 'roomId',
245
+ 'kind',
246
+ 'sender',
247
+ 'recipient',
248
+ 'createdAt',
249
+ 'expiresAt',
250
+ 'text',
251
+ ];
252
+ const REPLY_KEYS = [
253
+ 'schemaVersion',
254
+ 'id',
255
+ 'roomId',
256
+ 'kind',
257
+ 'inReplyTo',
258
+ 'sender',
259
+ 'recipient',
260
+ 'createdAt',
261
+ 'outcome',
262
+ 'code',
263
+ 'shared',
264
+ 'text',
265
+ 'truncated',
266
+ 'textLength',
267
+ ];
268
+ const APPROVAL_REQUEST_KEYS = [
269
+ 'schemaVersion',
270
+ 'id',
271
+ 'roomId',
272
+ 'kind',
273
+ 'sender',
274
+ 'recipient',
275
+ 'createdAt',
276
+ 'holdUntil',
277
+ 'approval',
278
+ ];
279
+ const APPROVAL_SUBJECT_KEYS = [
280
+ 'kind',
281
+ 'command',
282
+ 'cwd',
283
+ 'paths',
284
+ 'changeBytes',
285
+ 'reason',
286
+ 'turnOrigin',
287
+ ];
288
+ const APPROVAL_DECISION_KEYS = [
289
+ 'schemaVersion',
290
+ 'id',
291
+ 'roomId',
292
+ 'kind',
293
+ 'sender',
294
+ 'recipient',
295
+ 'createdAt',
296
+ 'approvalId',
297
+ 'decision',
298
+ 'reason',
299
+ ];
300
+
301
+ /** @param {unknown} value @returns {value is RequestMessage} */
302
+ function isRequest(value) {
303
+ if (!hasExactKeys(value, REQUEST_KEYS)) return false;
304
+ const message = /** @type {Record<string, unknown>} */ (value);
305
+ return (
306
+ hasEnvelope(message) &&
307
+ isManagerParty(message.sender) &&
308
+ isWorkerParty(message.recipient) &&
309
+ isTime(message.expiresAt) &&
310
+ isText(message.text, 1, LIMITS.requestTextMax)
311
+ );
312
+ }
313
+
314
+ /** @param {unknown} value @returns {value is ReplyMessage} */
315
+ function isReply(value) {
316
+ if (!hasExactKeys(value, REPLY_KEYS)) return false;
317
+ const message = /** @type {Record<string, unknown>} */ (value);
318
+ return (
319
+ hasEnvelope(message) &&
320
+ typeof message.inReplyTo === 'string' &&
321
+ MESSAGE_ID_PATTERN.test(message.inReplyTo) &&
322
+ isWorkerParty(message.sender) &&
323
+ message.recipient === MANAGER_RECIPIENT &&
324
+ REPLY_OUTCOMES.includes(/** @type {ReplyOutcome} */ (message.outcome)) &&
325
+ (message.code === null ||
326
+ (typeof message.code === 'string' && REPLY_CODE_PATTERN.test(message.code))) &&
327
+ typeof message.shared === 'boolean' &&
328
+ isText(message.text, 0, LIMITS.replyTextMax) &&
329
+ typeof message.truncated === 'boolean' &&
330
+ isTime(message.textLength)
331
+ );
332
+ }
333
+
334
+ /** @param {unknown} value @returns {value is ApprovalSubject} */
335
+ function isApprovalSubject(value) {
336
+ if (!hasExactKeys(value, APPROVAL_SUBJECT_KEYS)) return false;
337
+ const subject = /** @type {Record<string, unknown>} */ (value);
338
+ const paths = subject.paths;
339
+ const pathsValid =
340
+ paths === null ||
341
+ (Array.isArray(paths) &&
342
+ paths.length <= APPROVAL_PATHS_MAX &&
343
+ paths.every((path) => isText(path, 1, PATH_LENGTH_MAX)));
344
+ return (
345
+ (subject.kind === 'command' || subject.kind === 'fileChange') &&
346
+ isNullableText(subject.command, LIMITS.commandTextMax) &&
347
+ isNullableText(subject.cwd, PATH_LENGTH_MAX) &&
348
+ pathsValid &&
349
+ (subject.changeBytes === null || isTime(subject.changeBytes)) &&
350
+ isNullableText(subject.reason, APPROVAL_REASON_MAX) &&
351
+ (subject.turnOrigin === 'user' || subject.turnOrigin === 'manager')
352
+ );
353
+ }
354
+
355
+ /** @param {unknown} value @returns {value is ApprovalRequestMessage} */
356
+ function isApprovalRequest(value) {
357
+ if (!hasExactKeys(value, APPROVAL_REQUEST_KEYS)) return false;
358
+ const message = /** @type {Record<string, unknown>} */ (value);
359
+ return (
360
+ hasEnvelope(message) &&
361
+ isWorkerParty(message.sender) &&
362
+ message.recipient === MANAGER_RECIPIENT &&
363
+ isTime(message.holdUntil) &&
364
+ isApprovalSubject(message.approval)
365
+ );
366
+ }
367
+
368
+ /** @param {unknown} value @returns {value is ApprovalDecisionMessage} */
369
+ function isApprovalDecision(value) {
370
+ if (!hasExactKeys(value, APPROVAL_DECISION_KEYS)) return false;
371
+ const message = /** @type {Record<string, unknown>} */ (value);
372
+ return (
373
+ hasEnvelope(message) &&
374
+ isManagerParty(message.sender) &&
375
+ isWorkerParty(message.recipient) &&
376
+ typeof message.approvalId === 'string' &&
377
+ MESSAGE_ID_PATTERN.test(message.approvalId) &&
378
+ APPROVAL_DECISIONS.includes(/** @type {ApprovalDecision} */ (message.decision)) &&
379
+ isText(message.reason, 1, LIMITS.decisionReasonMax)
380
+ );
381
+ }
382
+
383
+ /**
384
+ * Strict schema check of one message: a known kind, no unknown key, every
385
+ * field of the expected type and size (FR3).
386
+ * @param {unknown} value
387
+ * @returns {{ ok: true, message: BusMessage } | { ok: false, reason: 'schema' }}
388
+ */
389
+ export function parseMessage(value) {
390
+ if (!isPlainRecord(value)) return { ok: false, reason: 'schema' };
391
+ const valid =
392
+ (value.kind === 'request' && isRequest(value)) ||
393
+ (value.kind === 'reply' && isReply(value)) ||
394
+ (value.kind === 'approval_request' && isApprovalRequest(value)) ||
395
+ (value.kind === 'approval_decision' && isApprovalDecision(value));
396
+ return valid
397
+ ? { ok: true, message: /** @type {BusMessage} */ (/** @type {unknown} */ (value)) }
398
+ : { ok: false, reason: 'schema' };
399
+ }
400
+
401
+ /**
402
+ * What a worker checks before it uses a file of its inbox (FR3, FR13 step 4):
403
+ * the room, that it is the recipient, and that the sender is the room's live
404
+ * manager. The codes go to the audit.
405
+ * @param {BusMessage} message
406
+ * @param {{ roomId: string, self: Party, manager: SessionRecord | null }} context
407
+ * @returns {{ ok: true } | { ok: false, reason: 'kind' | 'room' | 'recipient' | 'sender' }}
408
+ */
409
+ export function authorizeForWorker(message, context) {
410
+ if (message.kind !== 'request' && message.kind !== 'approval_decision')
411
+ return { ok: false, reason: 'kind' };
412
+ if (message.roomId !== context.roomId) return { ok: false, reason: 'room' };
413
+ if (
414
+ message.recipient.sessionId !== context.self.sessionId ||
415
+ message.recipient.name !== context.self.name
416
+ )
417
+ return { ok: false, reason: 'recipient' };
418
+ if (context.manager === null || message.sender.sessionId !== context.manager.sessionId)
419
+ return { ok: false, reason: 'sender' };
420
+ return { ok: true };
421
+ }
422
+
423
+ /**
424
+ * What the manager's server checks before it uses a file of the manager inbox
425
+ * (FR3): the room, and for a reply that it answers a pending request whose
426
+ * worker is the sender, by session id and by name; for an approval request
427
+ * that the sender is a live worker of the room.
428
+ * @param {BusMessage} message
429
+ * @param {{ roomId: string, pending: Map<string, PendingRecord>, workers: SessionRecord[] }} context
430
+ * @returns {{ ok: true } | { ok: false, reason: 'kind' | 'room' | 'unknown_request' | 'sender' }}
431
+ */
432
+ export function authorizeForManager(message, context) {
433
+ if (message.kind !== 'reply' && message.kind !== 'approval_request')
434
+ return { ok: false, reason: 'kind' };
435
+ if (message.roomId !== context.roomId) return { ok: false, reason: 'room' };
436
+ if (message.kind === 'reply') {
437
+ const pending = context.pending.get(message.inReplyTo);
438
+ if (pending === undefined) return { ok: false, reason: 'unknown_request' };
439
+ return pending.workerSessionId === message.sender.sessionId &&
440
+ pending.workerName === message.sender.name
441
+ ? { ok: true }
442
+ : { ok: false, reason: 'sender' };
443
+ }
444
+ const worker = context.workers.find((entry) => entry.sessionId === message.sender.sessionId);
445
+ return worker !== undefined && worker.role === 'worker' && worker.name === message.sender.name
446
+ ? { ok: true }
447
+ : { ok: false, reason: 'sender' };
448
+ }
449
+
450
+ /** @param {BusMessage | PendingRecord} value */
451
+ function serialize(value) {
452
+ return `${JSON.stringify(value)}\n`;
453
+ }
454
+
455
+ /**
456
+ * @param {object} input
457
+ * @param {string} input.roomId
458
+ * @param {Party} input.sender the manager session
459
+ * @param {Party} input.recipient the worker
460
+ * @param {string} input.text
461
+ * @param {number} [input.ttlMs]
462
+ * @param {number} input.now
463
+ * @returns {RequestMessage}
464
+ */
465
+ export function buildRequest({
466
+ roomId,
467
+ sender,
468
+ recipient,
469
+ text,
470
+ ttlMs = LIMITS.ttlDefaultMs,
471
+ now,
472
+ }) {
473
+ if (text.length < 1 || text.length > LIMITS.requestTextMax)
474
+ throw new BusError('message_too_large');
475
+ if (!Number.isSafeInteger(ttlMs) || ttlMs < LIMITS.ttlMinMs || ttlMs > LIMITS.ttlMaxMs)
476
+ throw new BusError('ttl_invalid');
477
+ return {
478
+ schemaVersion: BUS_SCHEMA_VERSION,
479
+ id: newMessageId(now),
480
+ roomId,
481
+ kind: 'request',
482
+ sender: { sessionId: sender.sessionId, name: sender.name },
483
+ recipient: { sessionId: recipient.sessionId, name: recipient.name },
484
+ createdAt: now,
485
+ expiresAt: now + ttlMs,
486
+ text,
487
+ };
488
+ }
489
+
490
+ /**
491
+ * A reply to one request. Text over the limit is cut and marked; a reply that
492
+ * still does not fit one file is cut further.
493
+ * @param {object} input
494
+ * @param {string} input.roomId
495
+ * @param {string} input.inReplyTo
496
+ * @param {Party} input.sender the worker
497
+ * @param {ReplyOutcome} input.outcome
498
+ * @param {string | null} [input.code]
499
+ * @param {boolean} [input.shared]
500
+ * @param {string} [input.text]
501
+ * @param {number} input.now
502
+ * @returns {ReplyMessage}
503
+ */
504
+ export function buildReply({
505
+ roomId,
506
+ inReplyTo,
507
+ sender,
508
+ outcome,
509
+ code = null,
510
+ shared = false,
511
+ text = '',
512
+ now,
513
+ }) {
514
+ const cut = cutText(text, LIMITS.replyTextMax);
515
+ /** @type {ReplyMessage} */
516
+ const reply = {
517
+ schemaVersion: BUS_SCHEMA_VERSION,
518
+ id: newMessageId(now),
519
+ roomId,
520
+ kind: 'reply',
521
+ inReplyTo,
522
+ sender: { sessionId: sender.sessionId, name: sender.name },
523
+ recipient: MANAGER_RECIPIENT,
524
+ createdAt: now,
525
+ outcome,
526
+ code: code !== null && REPLY_CODE_PATTERN.test(code) ? code : null,
527
+ shared,
528
+ text: cut.text,
529
+ truncated: cut.truncated,
530
+ textLength: text.length,
531
+ };
532
+ while (
533
+ Buffer.byteLength(serialize(reply), 'utf8') > LIMITS.fileBytesMax &&
534
+ reply.text.length > 0
535
+ ) {
536
+ const shorter = Math.floor(
537
+ (reply.text.length * REPLY_SHRINK_NUMERATOR) / REPLY_SHRINK_DENOMINATOR,
538
+ );
539
+ reply.text = cutText(reply.text, shorter).text;
540
+ reply.truncated = true;
541
+ }
542
+ return reply;
543
+ }
544
+
545
+ /**
546
+ * @param {object} input
547
+ * @param {string} input.roomId
548
+ * @param {Party} input.sender the worker
549
+ * @param {ApprovalSubject} input.approval
550
+ * @param {number} input.now
551
+ * @param {number} [input.holdMs]
552
+ * @returns {ApprovalRequestMessage}
553
+ */
554
+ export function buildApprovalRequest({ roomId, sender, approval, now, holdMs = LIMITS.holdMs }) {
555
+ return {
556
+ schemaVersion: BUS_SCHEMA_VERSION,
557
+ id: newMessageId(now),
558
+ roomId,
559
+ kind: 'approval_request',
560
+ sender: { sessionId: sender.sessionId, name: sender.name },
561
+ recipient: MANAGER_RECIPIENT,
562
+ createdAt: now,
563
+ holdUntil: now + holdMs,
564
+ approval: {
565
+ kind: approval.kind,
566
+ command:
567
+ approval.command === null ? null : cutText(approval.command, LIMITS.commandTextMax).text,
568
+ cwd: approval.cwd === null ? null : approval.cwd.slice(0, PATH_LENGTH_MAX),
569
+ paths:
570
+ approval.paths === null
571
+ ? null
572
+ : approval.paths
573
+ .slice(0, APPROVAL_PATHS_MAX)
574
+ .map((path) => path.slice(0, PATH_LENGTH_MAX)),
575
+ changeBytes: approval.changeBytes,
576
+ reason: approval.reason === null ? null : cutText(approval.reason, APPROVAL_REASON_MAX).text,
577
+ turnOrigin: approval.turnOrigin,
578
+ },
579
+ };
580
+ }
581
+
582
+ /**
583
+ * @param {object} input
584
+ * @param {string} input.roomId
585
+ * @param {Party} input.sender the manager session
586
+ * @param {Party} input.recipient the worker
587
+ * @param {string} input.approvalId
588
+ * @param {ApprovalDecision} input.decision
589
+ * @param {string} input.reason
590
+ * @param {number} input.now
591
+ * @returns {ApprovalDecisionMessage}
592
+ */
593
+ export function buildApprovalDecision({
594
+ roomId,
595
+ sender,
596
+ recipient,
597
+ approvalId,
598
+ decision,
599
+ reason,
600
+ now,
601
+ }) {
602
+ return {
603
+ schemaVersion: BUS_SCHEMA_VERSION,
604
+ id: newMessageId(now),
605
+ roomId,
606
+ kind: 'approval_decision',
607
+ sender: { sessionId: sender.sessionId, name: sender.name },
608
+ recipient: { sessionId: recipient.sessionId, name: recipient.name },
609
+ createdAt: now,
610
+ approvalId,
611
+ decision,
612
+ reason,
613
+ };
614
+ }
615
+
616
+ /**
617
+ * Deliver one message: written in `tmp/`, renamed into the recipient's inbox.
618
+ * A file over 256 KiB is never written (FR3).
619
+ * @param {RoomPaths} paths
620
+ * @param {string} recipient a worker's session id, or `manager`
621
+ * @param {BusMessage} message
622
+ * @returns {Promise<number>} the file's size in bytes
623
+ */
624
+ export async function deliverMessage(paths, recipient, message) {
625
+ if (!parseMessage(message).ok) throw new BusError('bus_unavailable', 'message_invalid');
626
+ const text = serialize(message);
627
+ const bytes = Buffer.byteLength(text, 'utf8');
628
+ if (bytes > LIMITS.fileBytesMax) throw new BusError('message_too_large');
629
+ const target = join(mailboxDirectory(paths, 'inbox', recipient), `${message.id}.json`);
630
+ try {
631
+ await writePrivateFile(paths, target, text);
632
+ } catch {
633
+ throw new BusError('bus_unavailable', 'delivery_failed');
634
+ }
635
+ return bytes;
636
+ }
637
+
638
+ /**
639
+ * The files of one mailbox directory: message files in name order (the order
640
+ * of delivery), and every other entry, which a recipient deletes.
641
+ * @param {RoomPaths} paths
642
+ * @param {'inbox' | 'claimed'} box
643
+ * @param {string} recipient
644
+ * @returns {Promise<{ names: string[], foreign: string[] }>}
645
+ */
646
+ export async function listMailbox(paths, box, recipient) {
647
+ let entries;
648
+ try {
649
+ entries = await readdir(mailboxDirectory(paths, box, recipient));
650
+ } catch {
651
+ return { names: [], foreign: [] };
652
+ }
653
+ const names = entries.filter((name) => MESSAGE_FILE_PATTERN.test(name)).sort();
654
+ return { names, foreign: entries.filter((name) => !MESSAGE_FILE_PATTERN.test(name)) };
655
+ }
656
+
657
+ /**
658
+ * Read and schema-check one mailbox file. The reason of a failure is a code;
659
+ * the caller rejects the file with it.
660
+ * @param {RoomPaths} paths
661
+ * @param {'inbox' | 'claimed'} box
662
+ * @param {string} recipient
663
+ * @param {string} name
664
+ * @returns {Promise<{ ok: true, message: BusMessage, bytes: number } | { ok: false, reason: string, bytes: number }>}
665
+ */
666
+ export async function readMailboxFile(paths, box, recipient, name) {
667
+ if (!MESSAGE_FILE_PATTERN.test(name)) return { ok: false, reason: 'name', bytes: 0 };
668
+ const file = await readJsonFile(
669
+ join(mailboxDirectory(paths, box, recipient), name),
670
+ LIMITS.fileBytesMax,
671
+ );
672
+ if (!file.ok) return file;
673
+ const parsed = parseMessage(file.value);
674
+ if (!parsed.ok) return { ok: false, reason: parsed.reason, bytes: file.bytes };
675
+ if (`${parsed.message.id}.json` !== name)
676
+ return { ok: false, reason: 'id_mismatch', bytes: file.bytes };
677
+ return { ok: true, message: parsed.message, bytes: file.bytes };
678
+ }
679
+
680
+ /**
681
+ * @param {RoomPaths} paths
682
+ * @param {'inbox' | 'claimed'} box
683
+ * @param {string} recipient
684
+ * @param {string} name
685
+ */
686
+ export async function removeMailboxFile(paths, box, recipient, name) {
687
+ const directory = mailboxDirectory(paths, box, recipient);
688
+ // Never through a mailbox that is a link to somewhere else.
689
+ if (!(await isPrivateDirectory(directory))) return;
690
+ await unlink(join(directory, name)).catch(() => undefined);
691
+ }
692
+
693
+ /**
694
+ * Delete a file that failed its checks and record why, never its content
695
+ * (FR3). The session keeps running. A file whose read failed for a reason
696
+ * other than its content (`io_error`: a permission, the system's file table)
697
+ * may be valid: it is recorded and left for a later attempt.
698
+ * @param {RoomPaths} paths
699
+ * @param {string} recipient
700
+ * @param {string} name
701
+ * @param {{ reason: string, bytes: number, sessionId: string }} detail
702
+ * @param {BusClock} [clock]
703
+ */
704
+ export async function rejectMailboxFile(paths, recipient, name, detail, clock) {
705
+ if (detail.reason !== READ_ERROR) await removeMailboxFile(paths, 'inbox', recipient, name);
706
+ await audit(
707
+ paths,
708
+ {
709
+ event: 'rejected',
710
+ sessionId: detail.sessionId,
711
+ bytes: detail.bytes,
712
+ reason: AUDIT_REASON_PATTERN.test(detail.reason) ? detail.reason : 'invalid',
713
+ },
714
+ clock,
715
+ );
716
+ }
717
+
718
+ /**
719
+ * Claim one inbox file by renaming it into `claimed/` (FR4 step 2). False
720
+ * when the file is no longer there (cancelled, or taken already).
721
+ * @param {RoomPaths} paths
722
+ * @param {string} recipient
723
+ * @param {string} name
724
+ */
725
+ export async function claimMailboxFile(paths, recipient, name) {
726
+ try {
727
+ await rename(
728
+ join(mailboxDirectory(paths, 'inbox', recipient), name),
729
+ join(mailboxDirectory(paths, 'claimed', recipient), name),
730
+ );
731
+ return true;
732
+ } catch {
733
+ return false;
734
+ }
735
+ }
736
+
737
+ /**
738
+ * @param {RequestMessage} request
739
+ * @returns {PendingRecord}
740
+ */
741
+ export function pendingFor(request) {
742
+ return {
743
+ schemaVersion: BUS_SCHEMA_VERSION,
744
+ messageId: request.id,
745
+ workerSessionId: request.recipient.sessionId,
746
+ workerName: request.recipient.name,
747
+ createdAt: request.createdAt,
748
+ expiresAt: request.expiresAt,
749
+ };
750
+ }
751
+
752
+ /** @param {RoomPaths} paths @param {PendingRecord} record */
753
+ export async function writePending(paths, record) {
754
+ if (!isPendingRecord(record)) throw new BusError('bus_unavailable', 'pending_invalid');
755
+ await writePrivateFile(paths, join(paths.pending, `${record.messageId}.json`), serialize(record));
756
+ }
757
+
758
+ /** @param {RoomPaths} paths @param {string} messageId */
759
+ export async function removePending(paths, messageId) {
760
+ if (!MESSAGE_ID_PATTERN.test(messageId)) return;
761
+ if (!(await isPrivateDirectory(paths.pending))) return;
762
+ await unlink(join(paths.pending, `${messageId}.json`)).catch(() => undefined);
763
+ }
764
+
765
+ /**
766
+ * The room's pending records by message id, oldest first. A file that is not
767
+ * a pending record (a newer schema, a damaged file) is not listed, and is
768
+ * deleted only a day after its last change; a file that could not be read is
769
+ * left alone.
770
+ * @param {RoomPaths} paths
771
+ * @param {BusClock} [clock]
772
+ * @returns {Promise<Map<string, PendingRecord>>}
773
+ */
774
+ export async function listPending(paths, clock) {
775
+ /** @type {Map<string, PendingRecord>} */
776
+ const pending = new Map();
777
+ const staleBefore = (clock?.now ?? Date.now)() - LIMITS.retentionMs;
778
+ const names = await readdir(paths.pending).catch(() => []);
779
+ for (const name of names.sort()) {
780
+ const path = join(paths.pending, name);
781
+ const file = await readJsonFile(path, PENDING_FILE_BYTES_MAX);
782
+ if (file.ok && isPendingRecord(file.value) && `${file.value.messageId}.json` === name) {
783
+ pending.set(file.value.messageId, file.value);
784
+ continue;
785
+ }
786
+ if (!file.ok && (file.reason === 'missing' || file.reason === READ_ERROR)) continue;
787
+ if (file.modifiedAt !== null && file.modifiedAt < staleBefore)
788
+ await removeIfUnchanged(path, file.ino);
789
+ }
790
+ return pending;
791
+ }