@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,118 @@
1
+ // What a manager has to look at, without any message text (spec
2
+ // aisac-engineering-manager FR6, FR7, FR9): replies not read yet, workers that
3
+ // wait for the user's approval, and approval requests held for the manager.
4
+ // The manager's server, its hooks and `aisac workers --wait` all read the room
5
+ // through this module, and none of them changes the room here.
6
+
7
+ import { MANAGER_RECIPIENT, listSessions } from './bus.mjs';
8
+ import { authorizeForManager, listMailbox, listPending, readMailboxFile } from './messages.mjs';
9
+
10
+ /** What `aisac workers --wait` prints when nothing changed before its timeout (FR9). */
11
+ export const NO_CHANGE = 'no_change';
12
+
13
+ /** @typedef {import('./bus.mjs').RoomPaths} RoomPaths */
14
+ /** @typedef {import('./bus.mjs').BusClock} BusClock */
15
+ /** @typedef {import('./bus.mjs').SessionRecord} SessionRecord */
16
+ /**
17
+ * @typedef {object} RoomStatus
18
+ * @property {SessionRecord[]} workers the room's live workers
19
+ * @property {number} pending requests without a final reply
20
+ * @property {{ messageId: string, workerName: string }[]} replies replies in the manager's inbox, by the request they answer
21
+ * @property {{ workerName: string, kind: string, since: number }[]} waitingUser workers whose approval prompt waits for the user
22
+ * @property {{ approvalId: string, workerName: string, holdUntil: number }[]} held approval requests a worker's adapter holds for the manager
23
+ */
24
+
25
+ /**
26
+ * Read the room's state for a manager. Messages that fail their checks are
27
+ * skipped, never deleted: only the manager's server rejects a message. The
28
+ * one removal a reading can cause is the bus's own: a damaged pending record
29
+ * a day after its last change.
30
+ * @param {RoomPaths} paths
31
+ * @param {string} roomId
32
+ * @param {BusClock} [clock]
33
+ * @returns {Promise<RoomStatus>}
34
+ */
35
+ export async function roomStatus(paths, roomId, clock) {
36
+ const sessions = await listSessions(paths, { ...clock, sweep: false });
37
+ const workers = sessions.filter((entry) => entry.role === 'worker');
38
+ const pending = await listPending(paths, clock);
39
+ const { names } = await listMailbox(paths, 'inbox', MANAGER_RECIPIENT);
40
+ /** @type {RoomStatus['replies']} */
41
+ const replies = [];
42
+ /** @type {RoomStatus['held']} */
43
+ const held = [];
44
+ for (const name of names) {
45
+ const file = await readMailboxFile(paths, 'inbox', MANAGER_RECIPIENT, name);
46
+ if (!file.ok || !authorizeForManager(file.message, { roomId, pending, workers }).ok) continue;
47
+ const message = file.message;
48
+ if (message.kind === 'reply')
49
+ replies.push({ messageId: message.inReplyTo, workerName: message.sender.name });
50
+ if (message.kind !== 'approval_request') continue;
51
+ const worker = workers.find((entry) => entry.sessionId === message.sender.sessionId);
52
+ // A request the adapter no longer holds was decided, forwarded or withdrawn.
53
+ if (worker?.heldApprovals.includes(message.id))
54
+ held.push({
55
+ approvalId: message.id,
56
+ workerName: message.sender.name,
57
+ holdUntil: message.holdUntil,
58
+ });
59
+ }
60
+ const waitingUser = workers.flatMap((entry) =>
61
+ entry.state === 'waiting_approval' && entry.approval?.decider === 'user'
62
+ ? [{ workerName: entry.name, kind: entry.approval.kind, since: entry.approval.since }]
63
+ : [],
64
+ );
65
+ return { workers, pending: pending.size, replies, waitingUser, held };
66
+ }
67
+
68
+ /**
69
+ * Whether there is anything for the manager to look at.
70
+ * @param {RoomStatus} status
71
+ */
72
+ export function hasNews(status) {
73
+ return status.replies.length > 0 || status.waitingUser.length > 0 || status.held.length > 0;
74
+ }
75
+
76
+ /**
77
+ * A key that changes when the manager has something new to look at: the wait
78
+ * command and the hooks compare two of them.
79
+ * @param {RoomStatus} status
80
+ */
81
+ export function statusKey(status) {
82
+ return JSON.stringify([
83
+ status.replies.map((entry) => entry.messageId).sort(),
84
+ status.waitingUser.map((entry) => `${entry.workerName}:${entry.since}`).sort(),
85
+ status.held.map((entry) => entry.approvalId).sort(),
86
+ ]);
87
+ }
88
+
89
+ /** @param {string[]} names */
90
+ function uniqueNames(names) {
91
+ return [...new Set(names)].sort().join(', ');
92
+ }
93
+
94
+ /**
95
+ * One content-free line for the manager's model: counts and worker names,
96
+ * never reply or command text (FR7, FR9). Locale-free, like every tool result.
97
+ * @param {RoomStatus} status
98
+ * @returns {string | null} null when there is nothing to report
99
+ */
100
+ export function statusLine(status) {
101
+ /** @type {string[]} */
102
+ const parts = [];
103
+ if (status.replies.length > 0)
104
+ parts.push(
105
+ `${status.replies.length} unread worker repl${status.replies.length === 1 ? 'y' : 'ies'} (${uniqueNames(status.replies.map((entry) => entry.workerName))})`,
106
+ );
107
+ if (status.held.length > 0)
108
+ parts.push(
109
+ `${status.held.length} approval request${status.held.length === 1 ? '' : 's'} held for your decision (${uniqueNames(status.held.map((entry) => entry.workerName))})`,
110
+ );
111
+ if (status.waitingUser.length > 0)
112
+ parts.push(
113
+ `${status.waitingUser.length} worker${status.waitingUser.length === 1 ? '' : 's'} waiting for the user's approval in its own terminal (${uniqueNames(status.waitingUser.map((entry) => entry.workerName))})`,
114
+ );
115
+ if (parts.length === 0) return null;
116
+ // A statement of fact, not an order: the line reaches the model as hook context.
117
+ return `AISAC manager: ${parts.join('; ')}. manager_wait returns them.`;
118
+ }
@@ -0,0 +1,87 @@
1
+ // How a role process learns that a bus directory changed (spec
2
+ // aisac-engineering-manager D4): the operating system's directory watch, with
3
+ // a slow poll behind it for file systems where the watch says nothing. Every
4
+ // consumer takes this as an injected function, so tests drive changes by hand.
5
+
6
+ import { watch } from 'node:fs';
7
+
8
+ const DEFAULT_POLL_MS = 2_000;
9
+
10
+ /**
11
+ * @typedef {(directory: string, listener: () => void) => { on: (event: 'error', listener: () => void) => unknown, close: () => void }} WatchDirectory
12
+ * @typedef {(callback: () => void, milliseconds: number) => () => void} Every
13
+ */
14
+
15
+ /** @type {WatchDirectory} */
16
+ function watchDirectory(directory, listener) {
17
+ return watch(directory, { persistent: false }, listener);
18
+ }
19
+
20
+ /** @type {Every} */
21
+ function every(callback, milliseconds) {
22
+ const timer = setInterval(callback, milliseconds);
23
+ timer.unref();
24
+ return () => clearInterval(timer);
25
+ }
26
+
27
+ /**
28
+ * Call the consumer without letting it throw out of a timer: a failing
29
+ * reading must not end the role process, and the next change reads again.
30
+ * @param {() => unknown} onChange
31
+ */
32
+ function callSafely(onChange) {
33
+ try {
34
+ const result = onChange();
35
+ if (result instanceof Promise) result.catch(() => undefined);
36
+ } catch {
37
+ // The next change, or the poll, reads the directories again.
38
+ }
39
+ }
40
+
41
+ /**
42
+ * @typedef {(directories: string[], onChange: () => void) => () => void} DirectoryWatch
43
+ * Starts watching; the returned function stops it. `onChange` carries no
44
+ * detail: the consumer reads the directories again.
45
+ */
46
+
47
+ /**
48
+ * @param {{ pollMs?: number, watchDirectory?: WatchDirectory, every?: Every }} [options]
49
+ * the last two for tests: the operating system's watch and interval otherwise
50
+ * @returns {DirectoryWatch}
51
+ */
52
+ export function createDirectoryWatch({
53
+ pollMs = DEFAULT_POLL_MS,
54
+ watchDirectory: watchOne = watchDirectory,
55
+ every: repeat = every,
56
+ } = {}) {
57
+ return (directories, onChange) => {
58
+ let stopped = false;
59
+ let scheduled = false;
60
+ // Several events of one rename arrive together: one reading is enough.
61
+ const notify = () => {
62
+ if (stopped || scheduled) return;
63
+ scheduled = true;
64
+ setImmediate(() => {
65
+ scheduled = false;
66
+ if (!stopped) callSafely(onChange);
67
+ });
68
+ };
69
+ /** @type {ReturnType<WatchDirectory>[]} */
70
+ const watchers = [];
71
+ for (const directory of directories) {
72
+ try {
73
+ const watcher = watchOne(directory, notify);
74
+ watcher.on('error', () => undefined);
75
+ watchers.push(watcher);
76
+ } catch {
77
+ // A directory that cannot be watched is still covered by the poll.
78
+ }
79
+ }
80
+ const stopPoll = repeat(notify, pollMs);
81
+ return () => {
82
+ stopped = true;
83
+ stopPoll();
84
+ for (const watcher of watchers) watcher.close();
85
+ };
86
+ };
87
+ }