@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.
- package/README.md +32 -1
- package/dist/assets/codex-context-compaction.mjs +603 -9
- package/dist/assets/jev-paid-pilot-terminal.mjs +6 -1
- package/dist/claude-observation.mjs +1 -1
- package/dist/cli.mjs +61 -4
- package/dist/engineering-pack.mjs +21 -4
- package/dist/extensions-catalog.mjs +18 -1
- package/dist/guardrails/guards.mjs +1144 -36
- package/dist/launch.mjs +132 -20
- package/dist/manager/bus.mjs +1921 -0
- package/dist/manager/delegation.mjs +354 -0
- package/dist/manager/hooks.mjs +918 -0
- package/dist/manager/launch-role.mjs +476 -0
- package/dist/manager/mcp-stdio.mjs +463 -0
- package/dist/manager/messages.mjs +791 -0
- package/dist/manager/reserve.mjs +2166 -0
- package/dist/manager/room.mjs +106 -0
- package/dist/manager/server.mjs +1792 -0
- package/dist/manager/status.mjs +118 -0
- package/dist/manager/watch.mjs +87 -0
- package/dist/manager/worker.mjs +2793 -0
- package/dist/manager/workers-cli.mjs +1403 -0
- package/dist/package.json +1 -1
- package/dist/release-manifest.json +7 -7
- package/package.json +1 -1
|
@@ -0,0 +1,1403 @@
|
|
|
1
|
+
// `aisac workers` (spec aisac-engineering-manager FR1, FR9, FR13; D3, D15,
|
|
2
|
+
// D16): the live sessions of a room, the wake command a manager runs in the
|
|
3
|
+
// background, the delegation of approvals that only the user grants from a
|
|
4
|
+
// terminal of their own, and the record of what was decided in their name.
|
|
5
|
+
// It reads and writes local state only and needs no license. Human output
|
|
6
|
+
// follows the stored locale; `--json` and the wake line are locale-free.
|
|
7
|
+
|
|
8
|
+
import { execFile } from 'node:child_process';
|
|
9
|
+
import { readFile } from 'node:fs/promises';
|
|
10
|
+
import { resolve } from 'node:path';
|
|
11
|
+
import {
|
|
12
|
+
BusError,
|
|
13
|
+
LIMITS,
|
|
14
|
+
MANAGER_RECIPIENT,
|
|
15
|
+
MANAGER_ROLE_ENV,
|
|
16
|
+
NAME_PATTERN,
|
|
17
|
+
WORKER_ROLE_ENV,
|
|
18
|
+
audit,
|
|
19
|
+
ensurePrivateDirectory,
|
|
20
|
+
listRooms,
|
|
21
|
+
listSessions,
|
|
22
|
+
mailboxDirectory,
|
|
23
|
+
parseRoleEnvironment,
|
|
24
|
+
readRoom,
|
|
25
|
+
recipientOf,
|
|
26
|
+
roomPaths,
|
|
27
|
+
sweepBus,
|
|
28
|
+
withRoomLock,
|
|
29
|
+
} from './bus.mjs';
|
|
30
|
+
import { listMailbox } from './messages.mjs';
|
|
31
|
+
import {
|
|
32
|
+
buildGrant,
|
|
33
|
+
listGrants,
|
|
34
|
+
parseDuration,
|
|
35
|
+
readDecisions,
|
|
36
|
+
readGrant,
|
|
37
|
+
removeGrant,
|
|
38
|
+
writeGrant,
|
|
39
|
+
} from './delegation.mjs';
|
|
40
|
+
import { resolveRoom } from './room.mjs';
|
|
41
|
+
import { NO_CHANGE, hasNews, roomStatus, statusKey, statusLine } from './status.mjs';
|
|
42
|
+
import { createDirectoryWatch } from './watch.mjs';
|
|
43
|
+
|
|
44
|
+
/** @typedef {'pt-BR' | 'en'} WorkersLocale */
|
|
45
|
+
/** @typedef {import('./bus.mjs').RoomPaths} RoomPaths */
|
|
46
|
+
/** @typedef {import('./bus.mjs').SessionRecord} SessionRecord */
|
|
47
|
+
/** @typedef {import('./bus.mjs').ApprovalKind} ApprovalKind */
|
|
48
|
+
/** @typedef {import('./delegation.mjs').DecisionEntry} DecisionEntry */
|
|
49
|
+
/** @typedef {import('./delegation.mjs').DecisionOutcome} DecisionOutcome */
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {object} WorkersTerminal
|
|
52
|
+
* @property {boolean} isTTY whether standard input is a terminal
|
|
53
|
+
* @property {(prompt: string) => Promise<string>} question
|
|
54
|
+
*/
|
|
55
|
+
/**
|
|
56
|
+
* @typedef {object} WorkersIo
|
|
57
|
+
* @property {string} stateRoot
|
|
58
|
+
* @property {string} cwd
|
|
59
|
+
* @property {NodeJS.ProcessEnv} env
|
|
60
|
+
* @property {WorkersLocale} locale
|
|
61
|
+
* @property {(text: string) => void} out one line per call, without its newline
|
|
62
|
+
* @property {(text: string) => void} err one line per call, without its newline
|
|
63
|
+
* @property {WorkersTerminal} terminal standard input
|
|
64
|
+
* @property {import('./bus.mjs').BusClock} [clock]
|
|
65
|
+
* @property {() => Promise<number[]>} [ancestors] this process's ancestors, nearest first ({@link processAncestors})
|
|
66
|
+
* @property {(callback: () => void, ms: number) => () => void} [schedule]
|
|
67
|
+
* @property {import('./watch.mjs').DirectoryWatch} [watch]
|
|
68
|
+
* @property {import('./room.mjs').GitRunner} [git]
|
|
69
|
+
*/
|
|
70
|
+
/**
|
|
71
|
+
* @typedef {object} WorkersArguments
|
|
72
|
+
* @property {'list' | 'wait' | 'delegate' | 'revoke' | 'decisions'} action
|
|
73
|
+
* @property {string | null} room
|
|
74
|
+
* @property {boolean} json
|
|
75
|
+
* @property {number} timeoutSeconds
|
|
76
|
+
* @property {number} durationMs
|
|
77
|
+
* @property {string[]} names
|
|
78
|
+
*/
|
|
79
|
+
/**
|
|
80
|
+
* What `--json` reports of a room. `label` and `kind` are null only when a
|
|
81
|
+
* launcher's role names a room whose descriptor is gone.
|
|
82
|
+
* @typedef {object} RoomView
|
|
83
|
+
* @property {string} id
|
|
84
|
+
* @property {string | null} label
|
|
85
|
+
* @property {'repository' | 'named' | null} kind
|
|
86
|
+
*/
|
|
87
|
+
/**
|
|
88
|
+
* @typedef {object} RoomContext
|
|
89
|
+
* @property {RoomView} room
|
|
90
|
+
* @property {RoomPaths} paths
|
|
91
|
+
*/
|
|
92
|
+
/**
|
|
93
|
+
* One live session as `aisac workers --json` prints it. No session id: the
|
|
94
|
+
* listing is not refused by the bus guard, so it names nobody's recipient key.
|
|
95
|
+
* @typedef {object} SessionView
|
|
96
|
+
* @property {string} name
|
|
97
|
+
* @property {'manager' | 'worker'} role
|
|
98
|
+
* @property {'claude' | 'codex'} host
|
|
99
|
+
* @property {string | null} hostVersion
|
|
100
|
+
* @property {SessionRecord['state']} state
|
|
101
|
+
* @property {number} stateSince
|
|
102
|
+
* @property {SessionRecord['approval']} approval
|
|
103
|
+
* @property {SessionRecord['turnOrigin']} turnOrigin
|
|
104
|
+
* @property {number} startedAt
|
|
105
|
+
* @property {string} cwd
|
|
106
|
+
* @property {string} sandbox
|
|
107
|
+
* @property {string} approvalPolicy
|
|
108
|
+
* @property {number} queued files waiting in the session's inbox
|
|
109
|
+
* @property {number | null} delegatedUntil the expiry of the worker's live grant
|
|
110
|
+
*/
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The usage lines of `aisac workers`, without the command name, for
|
|
114
|
+
* `aisac --help` (locale-free, like the rest of that text).
|
|
115
|
+
* @type {readonly string[]}
|
|
116
|
+
*/
|
|
117
|
+
export const WORKERS_USAGE = Object.freeze([
|
|
118
|
+
'workers [--room <name>] [--json]',
|
|
119
|
+
'workers --wait [--timeout <seconds>] [--room <name>]',
|
|
120
|
+
'workers delegate [<name>...] [--for <duration>] [--room <name>]',
|
|
121
|
+
'workers delegate --off [<name>...] [--room <name>]',
|
|
122
|
+
'workers decisions [--room <name>] [--json]',
|
|
123
|
+
]);
|
|
124
|
+
|
|
125
|
+
const USAGE_EXIT_CODE = 2;
|
|
126
|
+
const FAILURE_EXIT_CODE = 1;
|
|
127
|
+
const NOTHING_GRANTED_EXIT_CODE = 1;
|
|
128
|
+
const SUCCESS_EXIT_CODE = 0;
|
|
129
|
+
const SECOND_MS = 1_000;
|
|
130
|
+
const MINUTE_MS = 60 * SECOND_MS;
|
|
131
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
132
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
133
|
+
const WAIT_TIMEOUT_MIN_SECONDS = 1;
|
|
134
|
+
const TIMEOUT_DIGITS = /^\d{1,6}$/u;
|
|
135
|
+
/** Either word confirms, whatever the locale: the user may know only one of them. */
|
|
136
|
+
const CONFIRMATION_WORDS = Object.freeze(['delegate', 'delegar']);
|
|
137
|
+
const WRAP_COLUMNS = 96;
|
|
138
|
+
/** A word for `wrap`: a span in backticks with what is attached to it, or a run of non-spaces. */
|
|
139
|
+
const WRAP_WORD = /\S*`[^`]*`\S*|\S+/gu;
|
|
140
|
+
const INDENT = ' ';
|
|
141
|
+
const TEXT_INDENT = ' ';
|
|
142
|
+
const TEXT_GUTTER = ' | ';
|
|
143
|
+
const LABEL_GAP = 2;
|
|
144
|
+
const APPROVED_MARKER = '>> ';
|
|
145
|
+
const PLAIN_MARKER = ' ';
|
|
146
|
+
const SHORT_GRANT_ID = 8;
|
|
147
|
+
/** How far up the process tree a grant looks for a session: deeper than any shell nesting. */
|
|
148
|
+
export const ANCESTRY_DEPTH_MAX = 64;
|
|
149
|
+
/** `ps` answers at once; past this the link counts as unreadable. */
|
|
150
|
+
const PS_TIMEOUT_MS = 2_000;
|
|
151
|
+
/** Where macOS and the BSDs keep `ps`: never looked up on a PATH the caller sets. */
|
|
152
|
+
const PS_PATH = '/bin/ps';
|
|
153
|
+
const PID_DIGITS = /^\d{1,10}$/u;
|
|
154
|
+
const SHORT_ROOM_ID = 8;
|
|
155
|
+
const CLOCK_DIGITS = 2;
|
|
156
|
+
const MONTH_OFFSET = 1;
|
|
157
|
+
const HEX_RADIX = 16;
|
|
158
|
+
const BYTE_HEX_DIGITS = 2;
|
|
159
|
+
const UNIT_HEX_DIGITS = 4;
|
|
160
|
+
const C0_LAST = 0x1f;
|
|
161
|
+
const DELETE = 0x7f;
|
|
162
|
+
const C1_LAST = 0x9f;
|
|
163
|
+
const BYTE_LAST = 0xff;
|
|
164
|
+
/** Zero-width marks, line and paragraph separators, bidirectional overrides, lone surrogates. */
|
|
165
|
+
const INVISIBLE_RANGES = Object.freeze([
|
|
166
|
+
[0x200b, 0x200f],
|
|
167
|
+
[0x2028, 0x202e],
|
|
168
|
+
[0x2066, 0x2069],
|
|
169
|
+
[0xd800, 0xdfff],
|
|
170
|
+
[0xfeff, 0xfeff],
|
|
171
|
+
]);
|
|
172
|
+
const NAMED_ESCAPES = new Map([
|
|
173
|
+
[0x09, '\\t'],
|
|
174
|
+
[0x0a, '\\n'],
|
|
175
|
+
[0x0d, '\\r'],
|
|
176
|
+
]);
|
|
177
|
+
const ERRNO_CODE = /^E[A-Z]+$/u;
|
|
178
|
+
/** @type {Readonly<Record<SessionRecord['host'], string>>} */
|
|
179
|
+
const HOST_NAMES = Object.freeze({ claude: 'Claude Code', codex: 'Codex' });
|
|
180
|
+
/** @type {ReadonlySet<DecisionOutcome>} */
|
|
181
|
+
const MANAGER_OUTCOMES = new Set(['approved', 'denied', 'escalated']);
|
|
182
|
+
|
|
183
|
+
const GRAMMAR = Object.freeze({
|
|
184
|
+
list: { flags: ['--json', '--wait'], values: ['--room', '--timeout'], names: false },
|
|
185
|
+
delegate: { flags: ['--off'], values: ['--room', '--for'], names: true },
|
|
186
|
+
decisions: { flags: ['--json'], values: ['--room'], names: false },
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
const EN = {
|
|
190
|
+
usage: 'usage:',
|
|
191
|
+
hints: /** @type {Readonly<Record<string, string>>} */ ({
|
|
192
|
+
room_name_invalid:
|
|
193
|
+
'a room name has 1 to 32 lowercase letters, digits or hyphens and starts with a letter or a digit.',
|
|
194
|
+
worker_name_invalid:
|
|
195
|
+
'a worker name has 1 to 32 lowercase letters, digits or hyphens and starts with a letter or a digit.',
|
|
196
|
+
timeout_invalid: '--timeout takes whole seconds, from 1 to 21600 (6 hours).',
|
|
197
|
+
duration_invalid: '--for takes minutes or hours (45m, 8h), from 10 minutes to 24 hours.',
|
|
198
|
+
interactive_terminal_required:
|
|
199
|
+
'run `aisac workers delegate` yourself, in a terminal; nothing was granted.',
|
|
200
|
+
delegate_inside_session:
|
|
201
|
+
'a grant is yours alone: type `aisac workers delegate` in a terminal you opened yourself, outside every manager or worker session and what it started; nothing was granted.',
|
|
202
|
+
bus_unavailable: 'the bus directory under the state root could not be read or written.',
|
|
203
|
+
}),
|
|
204
|
+
/** @param {string} names @param {string} room @param {string} live */
|
|
205
|
+
workerNotFound: (names, room, live) =>
|
|
206
|
+
`no live worker named ${names} in room ${room}; live workers: ${live}.`,
|
|
207
|
+
none: 'none',
|
|
208
|
+
/** @param {string} room */
|
|
209
|
+
noLiveWorker: (room) => `no live worker in room ${room}; nothing was granted.`,
|
|
210
|
+
kindRepository: 'repository',
|
|
211
|
+
kindNamed: 'named',
|
|
212
|
+
/** @param {string} room @param {number} count */
|
|
213
|
+
listHeader: (room, count) => `Room ${room}, ${count} live session${count === 1 ? '' : 's'}:`,
|
|
214
|
+
/** @param {string} room */
|
|
215
|
+
emptyRoom: (room) => `No live sessions in room ${room}.`,
|
|
216
|
+
roles: { manager: 'manager', worker: 'worker' },
|
|
217
|
+
labels: {
|
|
218
|
+
state: 'state',
|
|
219
|
+
turn: 'turn',
|
|
220
|
+
approval: 'approval',
|
|
221
|
+
directory: 'directory',
|
|
222
|
+
sandbox: 'sandbox',
|
|
223
|
+
queued: 'queued',
|
|
224
|
+
delegation: 'delegation',
|
|
225
|
+
},
|
|
226
|
+
/** @param {string} state @param {string} clock @param {string} age */
|
|
227
|
+
since: (state, clock, age) => `${state} since ${clock} (${age})`,
|
|
228
|
+
noThreadYet: 'no thread yet',
|
|
229
|
+
turnOrigins: { manager: 'sent by the manager', user: 'typed by the user' },
|
|
230
|
+
pendingApproval: {
|
|
231
|
+
/** @param {string} kind */
|
|
232
|
+
user: (kind) => `${kind}, answered by the user in its terminal`,
|
|
233
|
+
/** @param {string} kind */
|
|
234
|
+
manager: (kind) => `${kind}, held for the manager under the delegation`,
|
|
235
|
+
},
|
|
236
|
+
/** @param {string} sandbox @param {string} policy */
|
|
237
|
+
sandboxValue: (sandbox, policy) => `${sandbox} · approval policy ${policy}`,
|
|
238
|
+
/** @param {number} count */
|
|
239
|
+
queuedValue: (count) => `${count} message${count === 1 ? '' : 's'}`,
|
|
240
|
+
noDelegation: 'none',
|
|
241
|
+
/** @param {string} clock @param {string} age */
|
|
242
|
+
delegatedUntil: (clock, age) => `until ${clock} (${age})`,
|
|
243
|
+
kinds: {
|
|
244
|
+
command: 'command',
|
|
245
|
+
fileChange: 'file change',
|
|
246
|
+
permissions: 'permissions',
|
|
247
|
+
unknown: 'unknown',
|
|
248
|
+
},
|
|
249
|
+
justNow: 'just now',
|
|
250
|
+
/** @param {string} span */
|
|
251
|
+
ago: (span) => `${span} ago`,
|
|
252
|
+
/** @param {string} span */
|
|
253
|
+
ahead: (span) => `in ${span}`,
|
|
254
|
+
/** @param {string} room @param {string} span @param {string} clock */
|
|
255
|
+
delegateTitle: (room, span, clock) =>
|
|
256
|
+
`Delegate the approvals of these workers in room ${room} to the manager for ${span} from your confirmation (until about ${clock}):`,
|
|
257
|
+
/** @param {string} sandbox @param {string} policy @param {string} clock */
|
|
258
|
+
delegateRow: (sandbox, policy, clock) =>
|
|
259
|
+
`sandbox ${sandbox} · approval policy ${policy} · until ${clock}`,
|
|
260
|
+
/** @param {string} clock */
|
|
261
|
+
replacesGrant: (clock) => `(replaces its current grant, until ${clock})`,
|
|
262
|
+
noManager:
|
|
263
|
+
"No manager is open in this room: until one is, approval requests go to the worker's terminal as before.",
|
|
264
|
+
grantSentences: [
|
|
265
|
+
"Until then, the manager session may answer these workers' approval prompts in your place, one request at a time, and every decision is recorded with the request's text: read it with `aisac workers decisions`.",
|
|
266
|
+
"These always wait for you in the worker's terminal: secrets, pushes to main or master and force pushes, destructive commands, anything that publishes, deploys, changes infrastructure or a remote database, merges or releases, sudo, commands the client cannot read in full, and every request for wider permissions.",
|
|
267
|
+
'The reserve reads the command line, not what a script does: `./deploy.sh` or `make release` reach the manager, so leave out any worker whose task could lead to one.',
|
|
268
|
+
],
|
|
269
|
+
prompt: 'Type "delegate" to grant it (anything else cancels): ',
|
|
270
|
+
nothingGranted: 'Nothing granted.',
|
|
271
|
+
/** @param {string} name */
|
|
272
|
+
closedMeanwhile: (name) => `${name} closed before the confirmation: no grant.`,
|
|
273
|
+
/** @param {string} names @param {string} clock @param {string} age */
|
|
274
|
+
granted: (names, clock, age) =>
|
|
275
|
+
`Delegated to the manager until ${clock} (${age}): ${names}. End it early with \`aisac workers delegate --off\`.`,
|
|
276
|
+
/** @param {string} names */
|
|
277
|
+
revoked: (names) =>
|
|
278
|
+
`Delegation ended: ${names}. Each worker's adapter sends any request it holds to that worker's terminal, where it waits for you.`,
|
|
279
|
+
/** @param {string} room */
|
|
280
|
+
nothingToRevoke: (room) => `No live delegation to end in room ${room}.`,
|
|
281
|
+
/** @param {string} room @param {number} count @param {number} approved */
|
|
282
|
+
decisionsHeader: (room, count, approved) =>
|
|
283
|
+
`Decision record of room ${room}, oldest first: ${count} entr${count === 1 ? 'y' : 'ies'}, ${approved} approved in your name${approved > 0 ? ' (marked >>)' : ''}.`,
|
|
284
|
+
/** @param {string} room */
|
|
285
|
+
noDecisions: (room) => `No delegated approval was recorded in room ${room}.`,
|
|
286
|
+
outcomes: {
|
|
287
|
+
approved: 'APPROVED BY THE MANAGER',
|
|
288
|
+
denied: 'denied by the manager',
|
|
289
|
+
escalated: 'escalated to you by the manager',
|
|
290
|
+
timed_out: 'not decided in time, sent to the terminal',
|
|
291
|
+
reserved: 'reserved for you',
|
|
292
|
+
withdrawn: 'withdrawn',
|
|
293
|
+
},
|
|
294
|
+
/** @param {string} reserveClass */
|
|
295
|
+
reserveClass: (reserveClass) => `class ${reserveClass}`,
|
|
296
|
+
managerReason: "manager's reason:",
|
|
297
|
+
reason: 'reason:',
|
|
298
|
+
commandText: 'command:',
|
|
299
|
+
filesText: 'files:',
|
|
300
|
+
otherText: 'text:',
|
|
301
|
+
ids: 'ids:',
|
|
302
|
+
escapedNote: 'control characters in this entry are shown escaped (\\xHH, \\uHHHH).',
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
/** @typedef {typeof EN} Messages */
|
|
306
|
+
|
|
307
|
+
/** @type {Messages} */
|
|
308
|
+
const PT_BR = {
|
|
309
|
+
usage: 'uso:',
|
|
310
|
+
hints: {
|
|
311
|
+
room_name_invalid:
|
|
312
|
+
'o nome de uma sala tem de 1 a 32 letras minúsculas, dígitos ou hífens e começa com uma letra ou um dígito.',
|
|
313
|
+
worker_name_invalid:
|
|
314
|
+
'o nome de um worker tem de 1 a 32 letras minúsculas, dígitos ou hífens e começa com uma letra ou um dígito.',
|
|
315
|
+
timeout_invalid: '--timeout recebe segundos inteiros, de 1 a 21600 (6 horas).',
|
|
316
|
+
duration_invalid: '--for recebe minutos ou horas (45m, 8h), de 10 minutos a 24 horas.',
|
|
317
|
+
interactive_terminal_required:
|
|
318
|
+
'rode `aisac workers delegate` você mesmo, num terminal; nada foi delegado.',
|
|
319
|
+
delegate_inside_session:
|
|
320
|
+
'a delegação é só sua: digite `aisac workers delegate` num terminal que você mesmo abriu, fora de qualquer sessão de gerente ou de worker e do que ela iniciou; nada foi delegado.',
|
|
321
|
+
bus_unavailable: 'não foi possível ler ou gravar o diretório do bus no diretório de estado.',
|
|
322
|
+
},
|
|
323
|
+
workerNotFound: (names, room, live) =>
|
|
324
|
+
`nenhum worker ativo chamado ${names} na sala ${room}; workers ativos: ${live}.`,
|
|
325
|
+
none: 'nenhum',
|
|
326
|
+
noLiveWorker: (room) => `nenhum worker ativo na sala ${room}; nada foi delegado.`,
|
|
327
|
+
kindRepository: 'repositório',
|
|
328
|
+
kindNamed: 'nomeada',
|
|
329
|
+
listHeader: (room, count) =>
|
|
330
|
+
`Sala ${room}, ${count} ${count === 1 ? 'sessão ativa' : 'sessões ativas'}:`,
|
|
331
|
+
emptyRoom: (room) => `Nenhuma sessão ativa na sala ${room}.`,
|
|
332
|
+
roles: { manager: 'gerente', worker: 'worker' },
|
|
333
|
+
labels: {
|
|
334
|
+
state: 'estado',
|
|
335
|
+
turn: 'turno',
|
|
336
|
+
approval: 'aprovação',
|
|
337
|
+
directory: 'diretório',
|
|
338
|
+
sandbox: 'sandbox',
|
|
339
|
+
queued: 'fila',
|
|
340
|
+
delegation: 'delegação',
|
|
341
|
+
},
|
|
342
|
+
since: (state, clock, age) => `${state} desde ${clock} (${age})`,
|
|
343
|
+
noThreadYet: 'ainda sem thread',
|
|
344
|
+
turnOrigins: { manager: 'enviado pelo gerente', user: 'digitado pelo usuário' },
|
|
345
|
+
pendingApproval: {
|
|
346
|
+
user: (kind) => `${kind}, respondida pelo usuário no terminal dele`,
|
|
347
|
+
manager: (kind) => `${kind}, retida para o gerente pela delegação`,
|
|
348
|
+
},
|
|
349
|
+
sandboxValue: (sandbox, policy) => `${sandbox} · política de aprovação ${policy}`,
|
|
350
|
+
queuedValue: (count) => `${count} ${count === 1 ? 'mensagem' : 'mensagens'}`,
|
|
351
|
+
noDelegation: 'nenhuma',
|
|
352
|
+
delegatedUntil: (clock, age) => `até ${clock} (${age})`,
|
|
353
|
+
kinds: {
|
|
354
|
+
command: 'comando',
|
|
355
|
+
fileChange: 'alteração de arquivos',
|
|
356
|
+
permissions: 'permissões',
|
|
357
|
+
unknown: 'desconhecido',
|
|
358
|
+
},
|
|
359
|
+
justNow: 'agora',
|
|
360
|
+
ago: (span) => `há ${span}`,
|
|
361
|
+
ahead: (span) => `daqui a ${span}`,
|
|
362
|
+
delegateTitle: (room, span, clock) =>
|
|
363
|
+
`Delegar ao gerente as aprovações destes workers da sala ${room} por ${span} a partir da sua confirmação (até por volta de ${clock}):`,
|
|
364
|
+
delegateRow: (sandbox, policy, clock) =>
|
|
365
|
+
`sandbox ${sandbox} · política de aprovação ${policy} · até ${clock}`,
|
|
366
|
+
replacesGrant: (clock) => `(substitui a delegação atual dele, até ${clock})`,
|
|
367
|
+
noManager:
|
|
368
|
+
'Nenhum gerente está aberto nesta sala: enquanto não houver um, os pedidos de aprovação vão para o terminal do worker, como antes.',
|
|
369
|
+
grantSentences: [
|
|
370
|
+
'Até lá, a sessão do gerente pode responder no seu lugar aos pedidos de aprovação destes workers, um pedido por vez, e cada decisão fica registrada com o texto do pedido: veja com `aisac workers decisions`.',
|
|
371
|
+
'Estes continuam esperando por você no terminal do worker: segredos, push na main ou na master e push forçado, comandos destrutivos, tudo o que publica, faz deploy, muda infraestrutura ou um banco de dados remoto, faz merge ou release, sudo, comandos que o cliente não consegue ler por inteiro e todo pedido de permissões maiores.',
|
|
372
|
+
'A reserva lê a linha de comando, não o que um script faz: `./deploy.sh` ou `make release` chegam ao gerente, então deixe de fora o worker cuja tarefa possa levar a um deles.',
|
|
373
|
+
],
|
|
374
|
+
prompt: 'Digite "delegar" para confirmar (qualquer outra coisa cancela): ',
|
|
375
|
+
nothingGranted: 'Nada foi delegado.',
|
|
376
|
+
closedMeanwhile: (name) => `${name} foi fechado antes da confirmação: sem delegação.`,
|
|
377
|
+
granted: (names, clock, age) =>
|
|
378
|
+
`Delegado ao gerente até ${clock} (${age}): ${names}. Para encerrar antes, use \`aisac workers delegate --off\`.`,
|
|
379
|
+
revoked: (names) =>
|
|
380
|
+
`Delegação encerrada: ${names}. O adaptador de cada worker manda o pedido que estiver retido para o terminal dele, onde ele espera por você.`,
|
|
381
|
+
nothingToRevoke: (room) => `Nenhuma delegação ativa para encerrar na sala ${room}.`,
|
|
382
|
+
decisionsHeader: (room, count, approved) =>
|
|
383
|
+
`Registro de decisões da sala ${room}, do mais antigo para o mais recente: ${count} ${count === 1 ? 'entrada' : 'entradas'}, ${approved} ${approved === 1 ? 'aprovada' : 'aprovadas'} em seu nome${approved > 0 ? ' (marcadas com >>)' : ''}.`,
|
|
384
|
+
noDecisions: (room) => `Nenhuma aprovação delegada foi registrada na sala ${room}.`,
|
|
385
|
+
outcomes: {
|
|
386
|
+
approved: 'APROVADO PELO GERENTE',
|
|
387
|
+
denied: 'negado pelo gerente',
|
|
388
|
+
escalated: 'repassado a você pelo gerente',
|
|
389
|
+
timed_out: 'não decidido a tempo, foi para o terminal',
|
|
390
|
+
reserved: 'reservado para você',
|
|
391
|
+
withdrawn: 'retirado',
|
|
392
|
+
},
|
|
393
|
+
reserveClass: (reserveClass) => `classe ${reserveClass}`,
|
|
394
|
+
managerReason: 'motivo do gerente:',
|
|
395
|
+
reason: 'motivo:',
|
|
396
|
+
commandText: 'comando:',
|
|
397
|
+
filesText: 'arquivos:',
|
|
398
|
+
otherText: 'texto:',
|
|
399
|
+
ids: 'ids:',
|
|
400
|
+
escapedNote: 'os caracteres de controle desta entrada aparecem escapados (\\xHH, \\uHHHH).',
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
/** @type {Readonly<Record<WorkersLocale, Messages>>} */
|
|
404
|
+
const MESSAGES = Object.freeze({ en: EN, 'pt-BR': PT_BR });
|
|
405
|
+
|
|
406
|
+
/** A coded failure of `aisac workers`. The code is the public message. */
|
|
407
|
+
export class WorkersError extends Error {
|
|
408
|
+
/**
|
|
409
|
+
* Every one of them is a usage error: it exits 2.
|
|
410
|
+
* @param {string} code
|
|
411
|
+
* @param {{ usage?: boolean, detail?: string, hint?: string }} [options]
|
|
412
|
+
*/
|
|
413
|
+
constructor(code, options = {}) {
|
|
414
|
+
super(code);
|
|
415
|
+
this.name = 'WorkersError';
|
|
416
|
+
this.code = code;
|
|
417
|
+
this.exitCode = USAGE_EXIT_CODE;
|
|
418
|
+
this.showUsage = options.usage ?? false;
|
|
419
|
+
this.detail = options.detail ?? null;
|
|
420
|
+
this.hint = options.hint ?? null;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** @param {string} code @param {string} [detail] */
|
|
425
|
+
function usageError(code, detail) {
|
|
426
|
+
return new WorkersError(code, detail === undefined ? { usage: true } : { usage: true, detail });
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ---------------------------------------------------------------- arguments
|
|
430
|
+
|
|
431
|
+
/** @param {string | undefined} value */
|
|
432
|
+
function parseTimeout(value) {
|
|
433
|
+
if (value === undefined) return LIMITS.wakeTimeoutDefaultSeconds;
|
|
434
|
+
const seconds = TIMEOUT_DIGITS.test(value) ? Number(value) : Number.NaN;
|
|
435
|
+
if (
|
|
436
|
+
!Number.isSafeInteger(seconds) ||
|
|
437
|
+
seconds < WAIT_TIMEOUT_MIN_SECONDS ||
|
|
438
|
+
seconds > LIMITS.wakeTimeoutMaxSeconds
|
|
439
|
+
)
|
|
440
|
+
throw new WorkersError('timeout_invalid');
|
|
441
|
+
return seconds;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** @param {string | undefined} value */
|
|
445
|
+
function parseFor(value) {
|
|
446
|
+
if (value === undefined) return LIMITS.delegationDefaultMs;
|
|
447
|
+
const milliseconds = parseDuration(value);
|
|
448
|
+
if (milliseconds === null) throw new WorkersError('duration_invalid');
|
|
449
|
+
return milliseconds;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* @param {'list' | 'delegate' | 'decisions'} subcommand
|
|
454
|
+
* @param {Set<string>} flags
|
|
455
|
+
* @param {Map<string, string>} values
|
|
456
|
+
* @param {string[]} names
|
|
457
|
+
* @returns {WorkersArguments}
|
|
458
|
+
*/
|
|
459
|
+
function toArguments(subcommand, flags, values, names) {
|
|
460
|
+
const room = values.get('--room') ?? null;
|
|
461
|
+
if (room !== null && !NAME_PATTERN.test(room)) throw new WorkersError('room_name_invalid');
|
|
462
|
+
const base = {
|
|
463
|
+
room,
|
|
464
|
+
json: flags.has('--json'),
|
|
465
|
+
names,
|
|
466
|
+
timeoutSeconds: LIMITS.wakeTimeoutDefaultSeconds,
|
|
467
|
+
durationMs: LIMITS.delegationDefaultMs,
|
|
468
|
+
};
|
|
469
|
+
if (subcommand === 'decisions') return { ...base, action: 'decisions' };
|
|
470
|
+
if (subcommand === 'delegate') {
|
|
471
|
+
if (!flags.has('--off'))
|
|
472
|
+
return { ...base, action: 'delegate', durationMs: parseFor(values.get('--for')) };
|
|
473
|
+
if (values.has('--for')) throw usageError('for_with_off');
|
|
474
|
+
return { ...base, action: 'revoke' };
|
|
475
|
+
}
|
|
476
|
+
if (!flags.has('--wait')) {
|
|
477
|
+
if (values.has('--timeout')) throw usageError('timeout_requires_wait');
|
|
478
|
+
return { ...base, action: 'list' };
|
|
479
|
+
}
|
|
480
|
+
if (flags.has('--json')) throw usageError('json_with_wait');
|
|
481
|
+
return { ...base, action: 'wait', timeoutSeconds: parseTimeout(values.get('--timeout')) };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Parse everything after `workers` (FR1). Pure: nothing is read or written.
|
|
486
|
+
* @param {readonly string[]} args
|
|
487
|
+
* @returns {WorkersArguments}
|
|
488
|
+
*/
|
|
489
|
+
export function parseWorkersArguments(args) {
|
|
490
|
+
const [first] = args;
|
|
491
|
+
const subcommand = first === 'delegate' || first === 'decisions' ? first : 'list';
|
|
492
|
+
const words = subcommand === 'list' ? args : args.slice(1);
|
|
493
|
+
const grammar = GRAMMAR[subcommand];
|
|
494
|
+
/** @type {Set<string>} */
|
|
495
|
+
const flags = new Set();
|
|
496
|
+
/** @type {Map<string, string>} */
|
|
497
|
+
const values = new Map();
|
|
498
|
+
/** @type {string[]} */
|
|
499
|
+
const names = [];
|
|
500
|
+
for (let index = 0; index < words.length; index += 1) {
|
|
501
|
+
const word = /** @type {string} */ (words[index]);
|
|
502
|
+
if (flags.has(word) || values.has(word)) throw usageError('duplicate_option', word);
|
|
503
|
+
if (grammar.flags.includes(word)) {
|
|
504
|
+
flags.add(word);
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
if (grammar.values.includes(word)) {
|
|
508
|
+
const value = words[index + 1];
|
|
509
|
+
if (value === undefined || value.startsWith('-'))
|
|
510
|
+
throw usageError('option_value_required', word);
|
|
511
|
+
values.set(word, value);
|
|
512
|
+
index += 1;
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
if (word.startsWith('-')) throw usageError('unknown_option', word);
|
|
516
|
+
if (!grammar.names) throw usageError('unexpected_argument', word);
|
|
517
|
+
if (!NAME_PATTERN.test(word)) throw new WorkersError('worker_name_invalid');
|
|
518
|
+
if (!names.includes(word)) names.push(word);
|
|
519
|
+
}
|
|
520
|
+
return toArguments(subcommand, flags, values, names);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// ------------------------------------------------------------ text helpers
|
|
524
|
+
|
|
525
|
+
/** @param {number} codePoint */
|
|
526
|
+
function isUnsafe(codePoint) {
|
|
527
|
+
if (codePoint <= C0_LAST || (codePoint >= DELETE && codePoint <= C1_LAST)) return true;
|
|
528
|
+
return INVISIBLE_RANGES.some(([first, last]) => codePoint >= first && codePoint <= last);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** @param {number} codePoint @param {number} digits */
|
|
532
|
+
function hex(codePoint, digits) {
|
|
533
|
+
return codePoint.toString(HEX_RADIX).padStart(digits, '0');
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Text that came from a file of the bus, made safe to print on a terminal:
|
|
538
|
+
* control characters, escape sequences and invisible format characters are
|
|
539
|
+
* written out as `\xHH` or `\uHHHH`, so they can repaint nothing.
|
|
540
|
+
* @param {string} text
|
|
541
|
+
* @returns {{ text: string, escaped: boolean }}
|
|
542
|
+
*/
|
|
543
|
+
export function visible(text) {
|
|
544
|
+
let escaped = false;
|
|
545
|
+
let result = '';
|
|
546
|
+
for (const character of text) {
|
|
547
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
548
|
+
if (!isUnsafe(codePoint)) {
|
|
549
|
+
result += character;
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
escaped = true;
|
|
553
|
+
result +=
|
|
554
|
+
NAMED_ESCAPES.get(codePoint) ??
|
|
555
|
+
(codePoint <= BYTE_LAST
|
|
556
|
+
? `\\x${hex(codePoint, BYTE_HEX_DIGITS)}`
|
|
557
|
+
: `\\u${hex(codePoint, UNIT_HEX_DIGITS)}`);
|
|
558
|
+
}
|
|
559
|
+
return { text: result, escaped };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** @param {string} text */
|
|
563
|
+
function safe(text) {
|
|
564
|
+
return visible(text).text;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* One JSON line whose characters a terminal cannot act on. JSON.stringify
|
|
569
|
+
* already escapes C0 controls; DEL, C1 controls and invisible format
|
|
570
|
+
* characters are escaped too. The value parses back unchanged.
|
|
571
|
+
* @param {unknown} value
|
|
572
|
+
*/
|
|
573
|
+
function jsonLine(value) {
|
|
574
|
+
let result = '';
|
|
575
|
+
for (const character of JSON.stringify(value)) {
|
|
576
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
577
|
+
result += isUnsafe(codePoint) ? `\\u${hex(codePoint, UNIT_HEX_DIGITS)}` : character;
|
|
578
|
+
}
|
|
579
|
+
return result;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Prose cut at word boundaries to fit the terminal. A command in backticks is
|
|
584
|
+
* one word, so it is never split across two lines.
|
|
585
|
+
* @param {string} text
|
|
586
|
+
*/
|
|
587
|
+
function wrap(text) {
|
|
588
|
+
/** @type {string[]} */
|
|
589
|
+
const lines = [];
|
|
590
|
+
let line = '';
|
|
591
|
+
for (const word of text.match(WRAP_WORD) ?? []) {
|
|
592
|
+
if (line.length > 0 && line.length + 1 + word.length > WRAP_COLUMNS) {
|
|
593
|
+
lines.push(line);
|
|
594
|
+
line = word;
|
|
595
|
+
} else line = line.length === 0 ? word : `${line} ${word}`;
|
|
596
|
+
}
|
|
597
|
+
if (line.length > 0) lines.push(line);
|
|
598
|
+
return lines;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** @param {number} value */
|
|
602
|
+
function twoDigits(value) {
|
|
603
|
+
return String(value).padStart(CLOCK_DIGITS, '0');
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** @param {number} at */
|
|
607
|
+
function localDate(at) {
|
|
608
|
+
const date = new Date(at);
|
|
609
|
+
return `${date.getFullYear()}-${twoDigits(date.getMonth() + MONTH_OFFSET)}-${twoDigits(date.getDate())}`;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** @param {number} at */
|
|
613
|
+
function localTime(at) {
|
|
614
|
+
const date = new Date(at);
|
|
615
|
+
return `${twoDigits(date.getHours())}:${twoDigits(date.getMinutes())}`;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** Local clock time, with the date when it is not today. @param {number} at @param {number} now */
|
|
619
|
+
function clockText(at, now) {
|
|
620
|
+
return localDate(at) === localDate(now) ? localTime(at) : `${localDate(at)} ${localTime(at)}`;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** @param {number} at */
|
|
624
|
+
function stampText(at) {
|
|
625
|
+
return `${localDate(at)} ${localTime(at)}:${twoDigits(new Date(at).getSeconds())}`;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/** A span of time in the largest two units: `12 s`, `3 min`, `7 h 58 min`, `1 d 2 h`. @param {number} ms */
|
|
629
|
+
function spanText(ms) {
|
|
630
|
+
if (ms < MINUTE_MS) return `${Math.floor(ms / SECOND_MS)} s`;
|
|
631
|
+
if (ms < HOUR_MS) return `${Math.floor(ms / MINUTE_MS)} min`;
|
|
632
|
+
if (ms < DAY_MS) {
|
|
633
|
+
const hours = Math.floor(ms / HOUR_MS);
|
|
634
|
+
const minutes = Math.floor((ms - hours * HOUR_MS) / MINUTE_MS);
|
|
635
|
+
return minutes === 0 ? `${hours} h` : `${hours} h ${minutes} min`;
|
|
636
|
+
}
|
|
637
|
+
const days = Math.floor(ms / DAY_MS);
|
|
638
|
+
const hours = Math.floor((ms - days * DAY_MS) / HOUR_MS);
|
|
639
|
+
return hours === 0 ? `${days} d` : `${days} d ${hours} h`;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** @param {number} at @param {number} now @param {Messages} text */
|
|
643
|
+
function ageText(at, now, text) {
|
|
644
|
+
const delta = now - at;
|
|
645
|
+
if (Math.abs(delta) < SECOND_MS) return text.justNow;
|
|
646
|
+
return delta > 0 ? text.ago(spanText(delta)) : text.ahead(spanText(-delta));
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** @param {RoomView} room @param {Messages} text */
|
|
650
|
+
function roomTitle(room, text) {
|
|
651
|
+
const name = `"${safe(room.label ?? room.id.slice(0, SHORT_ROOM_ID))}"`;
|
|
652
|
+
if (room.kind === null) return name;
|
|
653
|
+
return `${name} (${room.kind === 'named' ? text.kindNamed : text.kindRepository})`;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** @param {string[]} names */
|
|
657
|
+
function nameList(names) {
|
|
658
|
+
return names.join(', ');
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// -------------------------------------------------------------------- room
|
|
662
|
+
|
|
663
|
+
/** @param {WorkersIo} io */
|
|
664
|
+
function nowOf(io) {
|
|
665
|
+
return io.clock?.now ?? (() => Date.now());
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** @param {WorkersIo} io */
|
|
669
|
+
function gitOption(io) {
|
|
670
|
+
return io.git === undefined ? {} : { git: io.git };
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* The role a launcher gave this session, when it belongs to this state root.
|
|
675
|
+
* @param {NodeJS.ProcessEnv} env
|
|
676
|
+
* @param {string} stateRoot
|
|
677
|
+
*/
|
|
678
|
+
function launcherRole(env, stateRoot) {
|
|
679
|
+
const role =
|
|
680
|
+
parseRoleEnvironment(env[MANAGER_ROLE_ENV], 'manager') ??
|
|
681
|
+
parseRoleEnvironment(env[WORKER_ROLE_ENV], 'worker');
|
|
682
|
+
return role !== null && role.stateRoot === stateRoot ? role : null;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Which room (D3, FR9): `--room`, else the room of the role the launcher gave
|
|
687
|
+
* this session, else the repository (or the directory) of `cwd`.
|
|
688
|
+
* @param {WorkersArguments} options
|
|
689
|
+
* @param {WorkersIo} io
|
|
690
|
+
* @returns {Promise<RoomContext>}
|
|
691
|
+
*/
|
|
692
|
+
async function openRoom(options, io) {
|
|
693
|
+
const stateRoot = resolve(io.stateRoot);
|
|
694
|
+
if (options.room === null) {
|
|
695
|
+
const role = launcherRole(io.env, stateRoot);
|
|
696
|
+
if (role !== null) {
|
|
697
|
+
const paths = roomPaths(stateRoot, role.roomId);
|
|
698
|
+
const descriptor = await readRoom(paths);
|
|
699
|
+
const room =
|
|
700
|
+
descriptor !== null && descriptor.id === role.roomId
|
|
701
|
+
? descriptor
|
|
702
|
+
: { id: role.roomId, label: null, kind: null };
|
|
703
|
+
return { room, paths };
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
const room = await resolveRoom({ cwd: io.cwd, roomName: options.room, ...gitOption(io) });
|
|
707
|
+
return {
|
|
708
|
+
room: { id: room.id, label: room.label, kind: room.kind },
|
|
709
|
+
paths: roomPaths(stateRoot, room.id),
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* The room's live sessions after a sweep, the manager first, then the workers
|
|
715
|
+
* by name.
|
|
716
|
+
* @param {RoomContext} context
|
|
717
|
+
* @param {WorkersIo} io
|
|
718
|
+
*/
|
|
719
|
+
async function sweptSessions(context, io) {
|
|
720
|
+
await sweepBus(resolve(io.stateRoot), io.clock);
|
|
721
|
+
const sessions = await listSessions(context.paths, io.clock);
|
|
722
|
+
// The manager sorts first; names are plain ASCII, so code unit order is stable.
|
|
723
|
+
const key = (/** @type {SessionRecord} */ record) =>
|
|
724
|
+
`${record.role === 'manager' ? 0 : 1}${record.name}`;
|
|
725
|
+
return [...sessions].sort((left, right) => (key(left) < key(right) ? -1 : 1));
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// ------------------------------------------------------------------ listing
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* @param {SessionRecord} record
|
|
732
|
+
* @param {number} queued
|
|
733
|
+
* @param {number | null} delegatedUntil
|
|
734
|
+
* @returns {SessionView}
|
|
735
|
+
*/
|
|
736
|
+
function sessionView(record, queued, delegatedUntil) {
|
|
737
|
+
return {
|
|
738
|
+
name: record.name,
|
|
739
|
+
role: record.role,
|
|
740
|
+
host: record.host,
|
|
741
|
+
hostVersion: record.hostVersion,
|
|
742
|
+
state: record.state,
|
|
743
|
+
stateSince: record.stateSince,
|
|
744
|
+
approval: record.approval,
|
|
745
|
+
turnOrigin: record.turnOrigin,
|
|
746
|
+
startedAt: record.startedAt,
|
|
747
|
+
cwd: record.cwd,
|
|
748
|
+
sandbox: record.sandbox,
|
|
749
|
+
approvalPolicy: record.approvalPolicy,
|
|
750
|
+
queued,
|
|
751
|
+
delegatedUntil,
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/** @param {SessionView} view @param {number} now @param {Messages} text */
|
|
756
|
+
function stateText(view, now, text) {
|
|
757
|
+
const since = text.since(
|
|
758
|
+
view.state,
|
|
759
|
+
clockText(view.stateSince, now),
|
|
760
|
+
ageText(view.stateSince, now, text),
|
|
761
|
+
);
|
|
762
|
+
return view.state === 'starting' ? `${since}: ${text.noThreadYet}` : since;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Who started the running turn, and what an open approval waits for.
|
|
767
|
+
* @param {SessionView} view @param {Messages} text
|
|
768
|
+
* @returns {[string, string][]}
|
|
769
|
+
*/
|
|
770
|
+
function detailRows(view, text) {
|
|
771
|
+
if (view.state === 'busy' && view.turnOrigin !== null)
|
|
772
|
+
return [[text.labels.turn, text.turnOrigins[view.turnOrigin]]];
|
|
773
|
+
if (view.state !== 'waiting_approval' || view.approval === null) return [];
|
|
774
|
+
const kind = text.kinds[view.approval.kind];
|
|
775
|
+
return [[text.labels.approval, text.pendingApproval[view.approval.decider](kind)]];
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/** @param {SessionView} view @param {number} now @param {Messages} text */
|
|
779
|
+
function delegationText(view, now, text) {
|
|
780
|
+
if (view.delegatedUntil === null) return text.noDelegation;
|
|
781
|
+
return text.delegatedUntil(
|
|
782
|
+
clockText(view.delegatedUntil, now),
|
|
783
|
+
ageText(view.delegatedUntil, now, text),
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** @param {SessionView} view @param {number} now @param {Messages} text */
|
|
788
|
+
function sessionBlock(view, now, text) {
|
|
789
|
+
const version = view.hostVersion === null ? '' : ` ${safe(view.hostVersion)}`;
|
|
790
|
+
/** @type {[string, string][]} */
|
|
791
|
+
const rows = [
|
|
792
|
+
[text.labels.state, stateText(view, now, text)],
|
|
793
|
+
...detailRows(view, text),
|
|
794
|
+
[text.labels.directory, safe(view.cwd)],
|
|
795
|
+
[text.labels.sandbox, text.sandboxValue(safe(view.sandbox), safe(view.approvalPolicy))],
|
|
796
|
+
[text.labels.queued, text.queuedValue(view.queued)],
|
|
797
|
+
];
|
|
798
|
+
if (view.role === 'worker') rows.push([text.labels.delegation, delegationText(view, now, text)]);
|
|
799
|
+
const width = Math.max(...Object.values(text.labels).map((label) => label.length)) + LABEL_GAP;
|
|
800
|
+
return [
|
|
801
|
+
`${view.name} (${text.roles[view.role]}, ${HOST_NAMES[view.host]}${version})`,
|
|
802
|
+
...rows.map(([label, value]) => `${INDENT}${label.padEnd(width)}${value}`),
|
|
803
|
+
];
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* `aisac workers [--json]` (FR1): sweep, then the room's live sessions.
|
|
808
|
+
* @param {RoomContext} context @param {WorkersArguments} options @param {WorkersIo} io
|
|
809
|
+
*/
|
|
810
|
+
async function listCommand(context, options, io) {
|
|
811
|
+
const sessions = await sweptSessions(context, io);
|
|
812
|
+
const now = nowOf(io)();
|
|
813
|
+
const grants = new Map(
|
|
814
|
+
(await listGrants(context.paths, now)).map((grant) => [grant.workerSessionId, grant.expiresAt]),
|
|
815
|
+
);
|
|
816
|
+
/** @type {SessionView[]} */
|
|
817
|
+
const views = [];
|
|
818
|
+
for (const record of sessions) {
|
|
819
|
+
const { names } = await listMailbox(context.paths, 'inbox', recipientOf(record));
|
|
820
|
+
views.push(sessionView(record, names.length, grants.get(record.sessionId) ?? null));
|
|
821
|
+
}
|
|
822
|
+
if (options.json) {
|
|
823
|
+
io.out(jsonLine({ room: context.room, sessions: views }));
|
|
824
|
+
return SUCCESS_EXIT_CODE;
|
|
825
|
+
}
|
|
826
|
+
const text = MESSAGES[io.locale];
|
|
827
|
+
const title = roomTitle(context.room, text);
|
|
828
|
+
if (views.length === 0) {
|
|
829
|
+
io.out(text.emptyRoom(title));
|
|
830
|
+
return SUCCESS_EXIT_CODE;
|
|
831
|
+
}
|
|
832
|
+
io.out(text.listHeader(title, views.length));
|
|
833
|
+
for (const view of views) {
|
|
834
|
+
io.out('');
|
|
835
|
+
for (const line of sessionBlock(view, now, text)) io.out(line);
|
|
836
|
+
}
|
|
837
|
+
return SUCCESS_EXIT_CODE;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// --------------------------------------------------------------------- wake
|
|
841
|
+
|
|
842
|
+
/** @type {(callback: () => void, ms: number) => () => void} */
|
|
843
|
+
function realSchedule(callback, ms) {
|
|
844
|
+
const timer = setTimeout(callback, ms);
|
|
845
|
+
return () => clearTimeout(timer);
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* `aisac workers --wait` (MG5, FR9): block until the room has news for the
|
|
850
|
+
* manager, print one content-free line and exit 0; `no_change` at the
|
|
851
|
+
* timeout. News that is already there when the wait starts ends it at once:
|
|
852
|
+
* a manager that starts waiting with unread replies is to be woken.
|
|
853
|
+
* @param {RoomContext} context @param {WorkersArguments} options @param {WorkersIo} io
|
|
854
|
+
* @returns {Promise<number>}
|
|
855
|
+
*/
|
|
856
|
+
function waitCommand(context, options, io) {
|
|
857
|
+
const watch = io.watch ?? createDirectoryWatch();
|
|
858
|
+
const schedule = io.schedule ?? realSchedule;
|
|
859
|
+
const clock = io.clock;
|
|
860
|
+
return new Promise((resolvePromise) => {
|
|
861
|
+
let done = false;
|
|
862
|
+
let dirty = false;
|
|
863
|
+
/** @type {string | null} */
|
|
864
|
+
let startKey = null;
|
|
865
|
+
/** @type {Promise<void> | null} */
|
|
866
|
+
let reading = null;
|
|
867
|
+
/** @type {() => void} */
|
|
868
|
+
let stopWatch = () => undefined;
|
|
869
|
+
/** @type {() => void} */
|
|
870
|
+
let cancelTimer = () => undefined;
|
|
871
|
+
/** @param {string} line */
|
|
872
|
+
const finish = (line) => {
|
|
873
|
+
if (done) return;
|
|
874
|
+
done = true;
|
|
875
|
+
stopWatch();
|
|
876
|
+
cancelTimer();
|
|
877
|
+
io.out(line);
|
|
878
|
+
resolvePromise(SUCCESS_EXIT_CODE);
|
|
879
|
+
};
|
|
880
|
+
const readOnce = async () => {
|
|
881
|
+
const status = await roomStatus(context.paths, context.room.id, clock);
|
|
882
|
+
const key = statusKey(status);
|
|
883
|
+
if (startKey === null && !hasNews(status)) startKey = key;
|
|
884
|
+
else if (hasNews(status) && key !== startKey) finish(statusLine(status) ?? NO_CHANGE);
|
|
885
|
+
};
|
|
886
|
+
const readUntilSettled = async () => {
|
|
887
|
+
do {
|
|
888
|
+
dirty = false;
|
|
889
|
+
// A reading that fails leaves the wait as it was; the next change reads again.
|
|
890
|
+
await readOnce().catch(() => undefined);
|
|
891
|
+
} while (dirty && !done);
|
|
892
|
+
// In the same step as the last look at `dirty`: a change after it starts a new reading.
|
|
893
|
+
reading = null;
|
|
894
|
+
};
|
|
895
|
+
// Returned so that a caller (the tests' watch) can await the reading.
|
|
896
|
+
const check = () => {
|
|
897
|
+
if (done) return Promise.resolve();
|
|
898
|
+
if (reading !== null) {
|
|
899
|
+
dirty = true;
|
|
900
|
+
return reading;
|
|
901
|
+
}
|
|
902
|
+
reading = readUntilSettled();
|
|
903
|
+
return reading;
|
|
904
|
+
};
|
|
905
|
+
// The watch starts before the first reading, so no change falls between the two.
|
|
906
|
+
stopWatch = watch(
|
|
907
|
+
[mailboxDirectory(context.paths, 'inbox', MANAGER_RECIPIENT), context.paths.sessions],
|
|
908
|
+
check,
|
|
909
|
+
);
|
|
910
|
+
cancelTimer = schedule(() => finish(NO_CHANGE), options.timeoutSeconds * SECOND_MS);
|
|
911
|
+
if (done) cancelTimer();
|
|
912
|
+
void check();
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// --------------------------------------------------------------- delegation
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* The workers a delegation names, all live; without names, every live worker.
|
|
920
|
+
* @param {SessionRecord[]} workers @param {string[]} names @param {RoomContext} context @param {Messages} text
|
|
921
|
+
*/
|
|
922
|
+
function pickWorkers(workers, names, context, text) {
|
|
923
|
+
if (names.length === 0) return workers;
|
|
924
|
+
const unknown = names.filter((name) => !workers.some((worker) => worker.name === name));
|
|
925
|
+
if (unknown.length > 0)
|
|
926
|
+
throw new WorkersError('worker_not_found', {
|
|
927
|
+
hint: text.workerNotFound(
|
|
928
|
+
nameList(unknown),
|
|
929
|
+
roomTitle(context.room, text),
|
|
930
|
+
workers.length === 0 ? text.none : nameList(workers.map((worker) => worker.name)),
|
|
931
|
+
),
|
|
932
|
+
});
|
|
933
|
+
return workers.filter((worker) => names.includes(worker.name));
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* What the user reads before typing the confirmation (FR13 "The grant").
|
|
938
|
+
* @param {{ context: RoomContext, targets: SessionRecord[], current: Map<string, number>, managerLive: boolean, durationMs: number, now: number, text: Messages }} input
|
|
939
|
+
*/
|
|
940
|
+
function grantPreview({ context, targets, current, managerLive, durationMs, now, text }) {
|
|
941
|
+
const expiry = clockText(now + durationMs, now);
|
|
942
|
+
const width = Math.max(...targets.map((worker) => worker.name.length)) + LABEL_GAP;
|
|
943
|
+
const lines = [
|
|
944
|
+
...wrap(text.delegateTitle(roomTitle(context.room, text), spanText(durationMs), expiry)),
|
|
945
|
+
'',
|
|
946
|
+
];
|
|
947
|
+
for (const worker of targets) {
|
|
948
|
+
lines.push(
|
|
949
|
+
`${INDENT}${worker.name.padEnd(width)}${text.delegateRow(safe(worker.sandbox), safe(worker.approvalPolicy), expiry)}`,
|
|
950
|
+
);
|
|
951
|
+
const existing = current.get(worker.sessionId);
|
|
952
|
+
if (existing !== undefined)
|
|
953
|
+
lines.push(`${INDENT}${' '.repeat(width)}${text.replacesGrant(clockText(existing, now))}`);
|
|
954
|
+
}
|
|
955
|
+
lines.push('');
|
|
956
|
+
if (!managerLive) lines.push(...wrap(text.noManager), '');
|
|
957
|
+
for (const sentence of text.grantSentences) lines.push(...wrap(sentence));
|
|
958
|
+
lines.push('');
|
|
959
|
+
return lines;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/** @param {WorkersIo} io @param {Messages} text */
|
|
963
|
+
async function confirmed(io, text) {
|
|
964
|
+
const answer = await io.terminal.question(text.prompt).catch(() => '');
|
|
965
|
+
return CONFIRMATION_WORDS.includes(answer.trim().toLowerCase());
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* `aisac workers delegate` (MG6, FR13 "The grant"). The caller has already
|
|
970
|
+
* checked that standard input is a terminal.
|
|
971
|
+
* @param {RoomContext} context @param {WorkersArguments} options @param {WorkersIo} io
|
|
972
|
+
*/
|
|
973
|
+
async function delegateCommand(context, options, io) {
|
|
974
|
+
const text = MESSAGES[io.locale];
|
|
975
|
+
const now = nowOf(io);
|
|
976
|
+
const sessions = await sweptSessions(context, io);
|
|
977
|
+
const workers = sessions.filter((entry) => entry.role === 'worker');
|
|
978
|
+
const targets = pickWorkers(workers, options.names, context, text);
|
|
979
|
+
if (targets.length === 0)
|
|
980
|
+
throw new WorkersError('no_live_worker', {
|
|
981
|
+
hint: text.noLiveWorker(roomTitle(context.room, text)),
|
|
982
|
+
});
|
|
983
|
+
const shownAt = now();
|
|
984
|
+
const current = new Map(
|
|
985
|
+
(await listGrants(context.paths, shownAt)).map((grant) => [
|
|
986
|
+
grant.workerSessionId,
|
|
987
|
+
grant.expiresAt,
|
|
988
|
+
]),
|
|
989
|
+
);
|
|
990
|
+
const managerLive = sessions.some((entry) => entry.role === 'manager');
|
|
991
|
+
const preview = grantPreview({
|
|
992
|
+
context,
|
|
993
|
+
targets,
|
|
994
|
+
current,
|
|
995
|
+
managerLive,
|
|
996
|
+
durationMs: options.durationMs,
|
|
997
|
+
now: shownAt,
|
|
998
|
+
text,
|
|
999
|
+
});
|
|
1000
|
+
for (const line of preview) io.out(line);
|
|
1001
|
+
if (!(await confirmed(io, text))) {
|
|
1002
|
+
io.out(text.nothingGranted);
|
|
1003
|
+
return NOTHING_GRANTED_EXIT_CODE;
|
|
1004
|
+
}
|
|
1005
|
+
return writeGrants(context, targets, options.durationMs, io);
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/**
|
|
1009
|
+
* One grant per worker still live after the confirmation; a grant already
|
|
1010
|
+
* there is replaced. The audit gets ids only.
|
|
1011
|
+
* @param {RoomContext} context @param {SessionRecord[]} targets @param {number} durationMs @param {WorkersIo} io
|
|
1012
|
+
*/
|
|
1013
|
+
async function writeGrants(context, targets, durationMs, io) {
|
|
1014
|
+
const text = MESSAGES[io.locale];
|
|
1015
|
+
const grantedAt = nowOf(io)();
|
|
1016
|
+
// Under the room's lock, so no session registers or closes between the
|
|
1017
|
+
// check of who is live and the grants written for them.
|
|
1018
|
+
const granted = await withRoomLock(
|
|
1019
|
+
context.paths,
|
|
1020
|
+
async () => {
|
|
1021
|
+
// A private real directory of this user, as opening the room leaves
|
|
1022
|
+
// it: a grant never follows a link planted in its place.
|
|
1023
|
+
await ensurePrivateDirectory(context.paths.delegation);
|
|
1024
|
+
const live = new Set(
|
|
1025
|
+
(await listSessions(context.paths, { ...io.clock, sweep: false })).map(
|
|
1026
|
+
(entry) => entry.sessionId,
|
|
1027
|
+
),
|
|
1028
|
+
);
|
|
1029
|
+
/** @type {SessionRecord[]} */
|
|
1030
|
+
const written = [];
|
|
1031
|
+
for (const worker of targets) {
|
|
1032
|
+
if (!live.has(worker.sessionId)) {
|
|
1033
|
+
io.out(text.closedMeanwhile(worker.name));
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
const grant = buildGrant({ workerSessionId: worker.sessionId, durationMs, now: grantedAt });
|
|
1037
|
+
await writeGrant(context.paths, grant);
|
|
1038
|
+
written.push(worker);
|
|
1039
|
+
}
|
|
1040
|
+
return written;
|
|
1041
|
+
},
|
|
1042
|
+
io.clock,
|
|
1043
|
+
);
|
|
1044
|
+
// After the lock: the audit's rotation takes a lock of its own (bus.mjs).
|
|
1045
|
+
for (const worker of granted)
|
|
1046
|
+
await audit(context.paths, { event: 'delegated', sessionId: worker.sessionId }, io.clock);
|
|
1047
|
+
if (granted.length === 0) {
|
|
1048
|
+
io.out(text.nothingGranted);
|
|
1049
|
+
return NOTHING_GRANTED_EXIT_CODE;
|
|
1050
|
+
}
|
|
1051
|
+
const expiresAt = grantedAt + durationMs;
|
|
1052
|
+
for (const line of wrap(
|
|
1053
|
+
text.granted(
|
|
1054
|
+
nameList(granted.map((worker) => worker.name)),
|
|
1055
|
+
clockText(expiresAt, grantedAt),
|
|
1056
|
+
ageText(expiresAt, grantedAt, text),
|
|
1057
|
+
),
|
|
1058
|
+
))
|
|
1059
|
+
io.out(line);
|
|
1060
|
+
return SUCCESS_EXIT_CODE;
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* `aisac workers delegate --off` (MG6, FR13): end the grants of the named
|
|
1065
|
+
* workers, or of every worker of the room. It only takes authority away, so
|
|
1066
|
+
* it needs no terminal. Names that are not live workers are reported after
|
|
1067
|
+
* the other grants were ended. The grants end under the room's lock, so a
|
|
1068
|
+
* grant written at the same moment lands either before (and ends here) or
|
|
1069
|
+
* after this command, never in between.
|
|
1070
|
+
* @param {RoomContext} context @param {WorkersArguments} options @param {WorkersIo} io
|
|
1071
|
+
*/
|
|
1072
|
+
async function revokeCommand(context, options, io) {
|
|
1073
|
+
const text = MESSAGES[io.locale];
|
|
1074
|
+
const sessions = await sweptSessions(context, io);
|
|
1075
|
+
const workers = sessions.filter((entry) => entry.role === 'worker');
|
|
1076
|
+
const unknown = options.names.filter((name) => !workers.some((worker) => worker.name === name));
|
|
1077
|
+
const targets =
|
|
1078
|
+
options.names.length === 0
|
|
1079
|
+
? workers
|
|
1080
|
+
: workers.filter((worker) => options.names.includes(worker.name));
|
|
1081
|
+
// Without a worker there is no grant to end and nothing to lock: the room may not exist.
|
|
1082
|
+
const ended =
|
|
1083
|
+
targets.length === 0
|
|
1084
|
+
? []
|
|
1085
|
+
: await withRoomLock(
|
|
1086
|
+
context.paths,
|
|
1087
|
+
async () => {
|
|
1088
|
+
/** @type {SessionRecord[]} */
|
|
1089
|
+
const removed = [];
|
|
1090
|
+
for (const worker of targets) {
|
|
1091
|
+
const grant = await readGrant(context.paths, worker.sessionId, nowOf(io)());
|
|
1092
|
+
if (grant === null || !(await removeGrant(context.paths, worker.sessionId))) continue;
|
|
1093
|
+
removed.push(worker);
|
|
1094
|
+
}
|
|
1095
|
+
return removed;
|
|
1096
|
+
},
|
|
1097
|
+
io.clock,
|
|
1098
|
+
);
|
|
1099
|
+
// After the lock: the audit's rotation takes a lock of its own (bus.mjs).
|
|
1100
|
+
for (const worker of ended)
|
|
1101
|
+
await audit(
|
|
1102
|
+
context.paths,
|
|
1103
|
+
{ event: 'delegation_ended', sessionId: worker.sessionId, reason: 'revoked' },
|
|
1104
|
+
io.clock,
|
|
1105
|
+
);
|
|
1106
|
+
const title = roomTitle(context.room, text);
|
|
1107
|
+
const summary =
|
|
1108
|
+
ended.length === 0
|
|
1109
|
+
? text.nothingToRevoke(title)
|
|
1110
|
+
: text.revoked(nameList(ended.map((worker) => worker.name)));
|
|
1111
|
+
for (const line of wrap(summary)) io.out(line);
|
|
1112
|
+
if (unknown.length === 0) return SUCCESS_EXIT_CODE;
|
|
1113
|
+
throw new WorkersError('worker_not_found', {
|
|
1114
|
+
hint: text.workerNotFound(
|
|
1115
|
+
nameList(unknown),
|
|
1116
|
+
title,
|
|
1117
|
+
workers.length === 0 ? text.none : nameList(workers.map((worker) => worker.name)),
|
|
1118
|
+
),
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
// ---------------------------------------------------------------- decisions
|
|
1123
|
+
|
|
1124
|
+
/** @param {DecisionEntry} entry @param {Messages} text */
|
|
1125
|
+
function outcomeText(entry, text) {
|
|
1126
|
+
const outcome = text.outcomes[entry.outcome];
|
|
1127
|
+
const kind = text.kinds[entry.kind];
|
|
1128
|
+
const parts = [outcome, kind];
|
|
1129
|
+
if (entry.reserveClass !== null) parts.push(text.reserveClass(entry.reserveClass));
|
|
1130
|
+
return parts.join(' · ');
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* A labelled text, one gutter line per line of it, every line escaped: an
|
|
1135
|
+
* injected newline can never start a line that looks like an entry.
|
|
1136
|
+
* @param {string} label @param {string} value
|
|
1137
|
+
* @returns {{ lines: string[], escaped: boolean }}
|
|
1138
|
+
*/
|
|
1139
|
+
function gutterBlock(label, value) {
|
|
1140
|
+
let escaped = false;
|
|
1141
|
+
const lines = [`${TEXT_INDENT}${label}`];
|
|
1142
|
+
for (const part of value.split('\n')) {
|
|
1143
|
+
const shown = visible(part);
|
|
1144
|
+
escaped ||= shown.escaped;
|
|
1145
|
+
lines.push(`${TEXT_GUTTER}${shown.text}`);
|
|
1146
|
+
}
|
|
1147
|
+
return { lines, escaped };
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
/** @param {DecisionEntry} entry */
|
|
1151
|
+
function idsText(entry) {
|
|
1152
|
+
const parts = [`grant ${entry.grantId.slice(0, SHORT_GRANT_ID)}`];
|
|
1153
|
+
if (entry.approvalId !== null) parts.push(`approval ${entry.approvalId}`);
|
|
1154
|
+
if (entry.turnId !== null) parts.push(`turn ${entry.turnId}`);
|
|
1155
|
+
if (entry.itemId !== null) parts.push(`item ${entry.itemId}`);
|
|
1156
|
+
return visible(parts.join(' · '));
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
/** @param {DecisionEntry} entry @param {Messages} text */
|
|
1160
|
+
function textLabel(entry, text) {
|
|
1161
|
+
if (entry.kind === 'command') return text.commandText;
|
|
1162
|
+
return entry.kind === 'fileChange' ? text.filesText : text.otherText;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
/** @param {DecisionEntry} entry @param {Messages} text */
|
|
1166
|
+
function decisionBlock(entry, text) {
|
|
1167
|
+
const marker = entry.outcome === 'approved' ? APPROVED_MARKER : PLAIN_MARKER;
|
|
1168
|
+
const lines = [
|
|
1169
|
+
`${marker}${stampText(entry.at)} ${entry.workerName} ${outcomeText(entry, text)}`,
|
|
1170
|
+
];
|
|
1171
|
+
let escaped = false;
|
|
1172
|
+
if (entry.reason !== null) {
|
|
1173
|
+
const label = MANAGER_OUTCOMES.has(entry.outcome) ? text.managerReason : text.reason;
|
|
1174
|
+
const block = gutterBlock(label, entry.reason);
|
|
1175
|
+
lines.push(...block.lines);
|
|
1176
|
+
escaped ||= block.escaped;
|
|
1177
|
+
}
|
|
1178
|
+
if (entry.text.length > 0) {
|
|
1179
|
+
const block = gutterBlock(textLabel(entry, text), entry.text);
|
|
1180
|
+
lines.push(...block.lines);
|
|
1181
|
+
escaped ||= block.escaped;
|
|
1182
|
+
}
|
|
1183
|
+
const ids = idsText(entry);
|
|
1184
|
+
lines.push(`${TEXT_INDENT}${text.ids} ${ids.text}`);
|
|
1185
|
+
if (escaped || ids.escaped) lines.push(`${TEXT_INDENT}${text.escapedNote}`);
|
|
1186
|
+
return lines;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
/**
|
|
1190
|
+
* `aisac workers decisions [--json]` (MG6, FR13 "The decision record", Q13).
|
|
1191
|
+
* @param {RoomContext} context @param {WorkersArguments} options @param {WorkersIo} io
|
|
1192
|
+
*/
|
|
1193
|
+
async function decisionsCommand(context, options, io) {
|
|
1194
|
+
const entries = await readDecisions(context.paths);
|
|
1195
|
+
if (options.json) {
|
|
1196
|
+
for (const entry of entries) io.out(jsonLine(entry));
|
|
1197
|
+
return SUCCESS_EXIT_CODE;
|
|
1198
|
+
}
|
|
1199
|
+
const text = MESSAGES[io.locale];
|
|
1200
|
+
const title = roomTitle(context.room, text);
|
|
1201
|
+
if (entries.length === 0) {
|
|
1202
|
+
io.out(text.noDecisions(title));
|
|
1203
|
+
return SUCCESS_EXIT_CODE;
|
|
1204
|
+
}
|
|
1205
|
+
const approved = entries.filter((entry) => entry.outcome === 'approved').length;
|
|
1206
|
+
for (const line of wrap(text.decisionsHeader(title, entries.length, approved))) io.out(line);
|
|
1207
|
+
for (const entry of entries) {
|
|
1208
|
+
io.out('');
|
|
1209
|
+
for (const line of decisionBlock(entry, text)) io.out(line);
|
|
1210
|
+
}
|
|
1211
|
+
return SUCCESS_EXIT_CODE;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
// ------------------------------------------------------ inside a session (D16)
|
|
1215
|
+
|
|
1216
|
+
/** @param {string} text @returns {number | null} */
|
|
1217
|
+
function pidOf(text) {
|
|
1218
|
+
if (!PID_DIGITS.test(text)) return null;
|
|
1219
|
+
const pid = Number(text);
|
|
1220
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
/**
|
|
1224
|
+
* The parent field of `/proc/<pid>/stat`. The command name before it sits in
|
|
1225
|
+
* parentheses and may hold spaces and parentheses, so the fields that follow
|
|
1226
|
+
* start after the last `)`: state, then parent.
|
|
1227
|
+
* @param {string} stat
|
|
1228
|
+
*/
|
|
1229
|
+
function procParentField(stat) {
|
|
1230
|
+
const end = stat.lastIndexOf(')');
|
|
1231
|
+
if (end < 0) return '';
|
|
1232
|
+
return (
|
|
1233
|
+
stat
|
|
1234
|
+
.slice(end + 1)
|
|
1235
|
+
.trim()
|
|
1236
|
+
.split(/\s+/u)[1] ?? ''
|
|
1237
|
+
);
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
/**
|
|
1241
|
+
* @param {string} file @param {string[]} args @param {{ timeout: number }} options
|
|
1242
|
+
* @returns {Promise<string>} standard output
|
|
1243
|
+
*/
|
|
1244
|
+
function runFile(file, args, options) {
|
|
1245
|
+
return new Promise((resolvePromise, reject) => {
|
|
1246
|
+
execFile(file, args, { ...options, encoding: 'utf8' }, (error, stdout) => {
|
|
1247
|
+
if (error) reject(error);
|
|
1248
|
+
else resolvePromise(stdout);
|
|
1249
|
+
});
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* The parent of one process: from `/proc/<pid>/stat` on Linux, from
|
|
1255
|
+
* `ps -o ppid= -p <pid>` elsewhere. Null when it cannot be read.
|
|
1256
|
+
* @param {number} pid
|
|
1257
|
+
* @param {{ platform?: NodeJS.Platform, readText?: (path: string) => Promise<string>, run?: typeof runFile }} [options]
|
|
1258
|
+
* @returns {Promise<number | null>}
|
|
1259
|
+
*/
|
|
1260
|
+
export async function readParentPid(pid, options = {}) {
|
|
1261
|
+
const platform = options.platform ?? process.platform;
|
|
1262
|
+
try {
|
|
1263
|
+
if (platform === 'linux') {
|
|
1264
|
+
const readText = options.readText ?? ((path) => readFile(path, 'utf8'));
|
|
1265
|
+
return pidOf(procParentField(await readText(`/proc/${pid}/stat`)));
|
|
1266
|
+
}
|
|
1267
|
+
const run = options.run ?? runFile;
|
|
1268
|
+
const output = await run(PS_PATH, ['-o', 'ppid=', '-p', String(pid)], {
|
|
1269
|
+
timeout: PS_TIMEOUT_MS,
|
|
1270
|
+
});
|
|
1271
|
+
return pidOf(output.trim());
|
|
1272
|
+
} catch {
|
|
1273
|
+
return null;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
/** @param {(pid: number) => Promise<number | null>} parentOf @param {number} pid */
|
|
1278
|
+
async function parentOrNull(parentOf, pid) {
|
|
1279
|
+
try {
|
|
1280
|
+
return await parentOf(pid);
|
|
1281
|
+
} catch {
|
|
1282
|
+
return null;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
/**
|
|
1287
|
+
* The ancestors of a process, nearest first. The walk ends at its bound, at a
|
|
1288
|
+
* parent already seen, or at the first parent it cannot read; what it read
|
|
1289
|
+
* before that is kept.
|
|
1290
|
+
* @param {{ pid?: number, parentOf?: (pid: number) => Promise<number | null> }} [options]
|
|
1291
|
+
* @returns {Promise<number[]>}
|
|
1292
|
+
*/
|
|
1293
|
+
export async function processAncestors(options = {}) {
|
|
1294
|
+
const parentOf = options.parentOf ?? ((pid) => readParentPid(pid));
|
|
1295
|
+
let current = options.pid ?? process.pid;
|
|
1296
|
+
const seen = new Set([current]);
|
|
1297
|
+
/** @type {number[]} */
|
|
1298
|
+
const ancestors = [];
|
|
1299
|
+
while (ancestors.length < ANCESTRY_DEPTH_MAX) {
|
|
1300
|
+
const parent = await parentOrNull(parentOf, current);
|
|
1301
|
+
if (parent === null || seen.has(parent)) break;
|
|
1302
|
+
seen.add(parent);
|
|
1303
|
+
ancestors.push(parent);
|
|
1304
|
+
current = parent;
|
|
1305
|
+
}
|
|
1306
|
+
return ancestors;
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/** @param {WorkersIo} io @returns {Promise<number[]>} */
|
|
1310
|
+
async function ancestorsOf(io) {
|
|
1311
|
+
try {
|
|
1312
|
+
return await (io.ancestors ?? (() => processAncestors()))();
|
|
1313
|
+
} catch {
|
|
1314
|
+
return [];
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* Whether this command runs inside a manager or worker session (D16): the
|
|
1320
|
+
* role a launcher hands to its processes is in the environment, or the
|
|
1321
|
+
* launcher or role process of a live session, in any room of the state root,
|
|
1322
|
+
* is among this command's ancestors. A chain that cannot be read counts as
|
|
1323
|
+
* outside: the terminal and the typed word are still required.
|
|
1324
|
+
* @param {WorkersIo} io
|
|
1325
|
+
*/
|
|
1326
|
+
async function insideSession(io) {
|
|
1327
|
+
if (io.env[MANAGER_ROLE_ENV] !== undefined || io.env[WORKER_ROLE_ENV] !== undefined) return true;
|
|
1328
|
+
const ancestors = new Set(await ancestorsOf(io));
|
|
1329
|
+
if (ancestors.size === 0) return false;
|
|
1330
|
+
for (const { paths } of await listRooms(resolve(io.stateRoot)))
|
|
1331
|
+
for (const record of await listSessions(paths, { ...io.clock, sweep: false }))
|
|
1332
|
+
if (
|
|
1333
|
+
ancestors.has(record.launcherPid) ||
|
|
1334
|
+
(record.childPid !== null && ancestors.has(record.childPid))
|
|
1335
|
+
)
|
|
1336
|
+
return true;
|
|
1337
|
+
return false;
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
// ---------------------------------------------------------------- the command
|
|
1341
|
+
|
|
1342
|
+
/** @param {unknown} error @param {WorkersIo} io */
|
|
1343
|
+
function reportFailure(error, io) {
|
|
1344
|
+
const text = MESSAGES[io.locale];
|
|
1345
|
+
if (error instanceof WorkersError) {
|
|
1346
|
+
const detail = error.detail === null ? '' : `: ${safe(error.detail)}`;
|
|
1347
|
+
const hint = error.hint ?? text.hints[error.code] ?? null;
|
|
1348
|
+
io.err(`aisac: ${error.code}${detail}${hint === null ? '' : `: ${hint}`}`);
|
|
1349
|
+
if (error.showUsage) {
|
|
1350
|
+
io.err(text.usage);
|
|
1351
|
+
for (const line of WORKERS_USAGE) io.err(`${INDENT}aisac ${line}`);
|
|
1352
|
+
}
|
|
1353
|
+
return error.exitCode;
|
|
1354
|
+
}
|
|
1355
|
+
const code = /** @type {{ code?: unknown }} */ (error ?? {}).code;
|
|
1356
|
+
if (error instanceof BusError || (typeof code === 'string' && ERRNO_CODE.test(code))) {
|
|
1357
|
+
const publicCode = error instanceof BusError ? error.code : 'bus_unavailable';
|
|
1358
|
+
const hint = text.hints[publicCode];
|
|
1359
|
+
io.err(`aisac: ${publicCode}${hint === undefined ? '' : `: ${hint}`}`);
|
|
1360
|
+
return FAILURE_EXIT_CODE;
|
|
1361
|
+
}
|
|
1362
|
+
throw error;
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
/** @param {RoomContext} context @param {WorkersArguments} options @param {WorkersIo} io */
|
|
1366
|
+
function runAction(context, options, io) {
|
|
1367
|
+
switch (options.action) {
|
|
1368
|
+
case 'wait':
|
|
1369
|
+
return waitCommand(context, options, io);
|
|
1370
|
+
case 'delegate':
|
|
1371
|
+
return delegateCommand(context, options, io);
|
|
1372
|
+
case 'revoke':
|
|
1373
|
+
return revokeCommand(context, options, io);
|
|
1374
|
+
case 'decisions':
|
|
1375
|
+
return decisionsCommand(context, options, io);
|
|
1376
|
+
default:
|
|
1377
|
+
return listCommand(context, options, io);
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/**
|
|
1382
|
+
* `aisac workers` (FR1, FR9, FR13). Usage errors exit 2, a declined
|
|
1383
|
+
* confirmation exits 1, a bus that cannot be read or written exits 1.
|
|
1384
|
+
* @param {string[]} args everything after `workers`
|
|
1385
|
+
* @param {WorkersIo} io
|
|
1386
|
+
* @returns {Promise<number>} the exit code
|
|
1387
|
+
*/
|
|
1388
|
+
export async function workersCommand(args, io) {
|
|
1389
|
+
try {
|
|
1390
|
+
const isGrant = args[0] === 'delegate' && !args.includes('--off');
|
|
1391
|
+
// A grant is the user's alone (D16): without a terminal on standard input
|
|
1392
|
+
// nothing else is read or written, and no flag changes that.
|
|
1393
|
+
if (isGrant && io.terminal.isTTY !== true)
|
|
1394
|
+
throw new WorkersError('interactive_terminal_required');
|
|
1395
|
+
// Nor from inside a session, where an agent may have a terminal of its own.
|
|
1396
|
+
if (isGrant && (await insideSession(io))) throw new WorkersError('delegate_inside_session');
|
|
1397
|
+
const options = parseWorkersArguments(args);
|
|
1398
|
+
const context = await openRoom(options, io);
|
|
1399
|
+
return await runAction(context, options, io);
|
|
1400
|
+
} catch (error) {
|
|
1401
|
+
return reportFailure(error, io);
|
|
1402
|
+
}
|
|
1403
|
+
}
|