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

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,496 @@
1
+ // The launcher's part of the manager feature (spec aisac-engineering-manager
2
+ // D2, D11, D14, FR1, FR2, FR6, FR8): the `--manager`, `--worker` and `--room`
3
+ // flags, the registration of the session, and what the launch hands to the
4
+ // role process. A role lasts one launch, never blocks one, and reaches its
5
+ // process only through the environment the launcher writes.
6
+
7
+ import { readdir } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ import {
10
+ BusError,
11
+ MANAGER_NAME,
12
+ MANAGER_ROLE_ENV,
13
+ NAME_PATTERN,
14
+ WORKER_MODULE_ENV,
15
+ WORKER_ROLE_ENV,
16
+ audit,
17
+ ensureRoom,
18
+ listRooms,
19
+ listSessions,
20
+ newSessionId,
21
+ registerSession,
22
+ removeSession,
23
+ roleEnvironmentValue,
24
+ sweepBus,
25
+ } from './bus.mjs';
26
+ import { MESSAGE_FILE_PATTERN } from './messages.mjs';
27
+ import { resolveRoom } from './room.mjs';
28
+
29
+ export const MANAGER_FLAG = '--manager';
30
+ export const WORKER_FLAG = '--worker';
31
+ export const ROOM_FLAG = '--room';
32
+ /** The name of the manager's stdio MCP server in the session's `mcp.json` (FR6). */
33
+ export const MANAGER_SERVER_NAME = 'aisac_manager';
34
+ /**
35
+ * The tools the launcher pre-allows (FR8): the three that only read, and
36
+ * `manager_decide`, whose authorization is the user's delegation (Q12).
37
+ * `manager_send` and `manager_cancel` are left to the host's permission flow.
38
+ */
39
+ export const MANAGER_ALLOWED_TOOLS = Object.freeze([
40
+ 'manager_workers',
41
+ 'manager_wait',
42
+ 'manager_read',
43
+ 'manager_decide',
44
+ ]);
45
+ /**
46
+ * The first Codex release measured with the worker role (D14). An older one starts
47
+ * Codex without the role. A later one gets it whenever this client runs that Codex at
48
+ * all: the launcher has already refused a release whose protocol it does not know.
49
+ */
50
+ export const MIN_WORKER_CODEX_VERSION = '0.166.0';
51
+ /**
52
+ * The Codex releases the role's host gate ran on (docs/reference/codex-manager-gate.md).
53
+ * Doctor shows them; they do not decide who gets the role.
54
+ */
55
+ export const MEASURED_WORKER_CODEX_VERSIONS = Object.freeze(['0.166.0', '0.167.1']);
56
+ const STABLE_VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/u;
57
+
58
+ const USAGE_EXIT_CODE = 2;
59
+ /** Registration failures that stop the launch before any host starts (FR1). */
60
+ const REFUSED_REGISTRATIONS = ['worker_name_taken', 'manager_already_active', 'room_full'];
61
+ /** The Codex subcommands a worker runs under: none (the terminal), `resume` and `fork`. */
62
+ const WORKER_CODEX_SUBCOMMANDS = new Set(['resume', 'fork']);
63
+ /**
64
+ * The other subcommands of the Codex releases measured with the role (D14). None opens
65
+ * the terminal bridge's socket, so no adapter would run the role. A first word not
66
+ * listed here is the prompt.
67
+ */
68
+ const CODEX_SUBCOMMANDS = new Set([
69
+ 'a',
70
+ 'agents',
71
+ 'app',
72
+ 'app-server',
73
+ 'apply',
74
+ 'archive',
75
+ 'cloud',
76
+ 'cloud-tasks',
77
+ 'completion',
78
+ 'debug',
79
+ 'delete',
80
+ 'doctor',
81
+ 'e',
82
+ 'exec',
83
+ 'exec-server',
84
+ 'execpolicy',
85
+ 'features',
86
+ 'help',
87
+ 'history',
88
+ 'login',
89
+ 'logout',
90
+ 'mcp',
91
+ 'mcp-server',
92
+ 'migrate-nfs-db',
93
+ 'plugin',
94
+ 'queue',
95
+ 'remote-control',
96
+ 'responses-api-proxy',
97
+ 'review',
98
+ 'sandbox',
99
+ 'stdio-to-uds',
100
+ 'tcp-tunnel',
101
+ 'unarchive',
102
+ 'update',
103
+ ]);
104
+ /** The options of the Codex command line that take the next argument as their value. */
105
+ const CODEX_VALUE_OPTIONS = new Set([
106
+ '-c',
107
+ '--config',
108
+ '--enable',
109
+ '--disable',
110
+ '-i',
111
+ '--image',
112
+ '-m',
113
+ '--model',
114
+ '--local-provider',
115
+ '-p',
116
+ '--profile',
117
+ '-s',
118
+ '--sandbox',
119
+ '-a',
120
+ '--ask-for-approval',
121
+ '-C',
122
+ '--cd',
123
+ '--add-dir',
124
+ '--remote',
125
+ '--remote-auth-token-env',
126
+ ]);
127
+
128
+ /** @typedef {import('./bus.mjs').BusLocale} BusLocale */
129
+ /** @typedef {import('./bus.mjs').RoomPaths} RoomPaths */
130
+ /** @typedef {import('./bus.mjs').SessionRecord} SessionRecord */
131
+ /** @typedef {{ kind: 'manager' } | { kind: 'worker', name: string }} RoleFlag */
132
+ /**
133
+ * @typedef {object} RoleRequest
134
+ * @property {RoleFlag} role
135
+ * @property {string | null} roomName
136
+ */
137
+ /**
138
+ * @typedef {object} ActiveRole
139
+ * @property {true} active
140
+ * @property {'manager' | 'worker'} kind
141
+ * @property {string} name
142
+ * @property {string} roomLabel
143
+ * @property {RoomPaths} paths
144
+ * @property {string} sessionId
145
+ * @property {string} environmentValue the JSON the role process parses
146
+ */
147
+ /**
148
+ * @typedef {object} InactiveRole
149
+ * @property {false} active
150
+ * @property {'manager' | 'worker'} kind
151
+ * @property {'license_inactive' | 'host_unqualified' | 'bus_unavailable'} reason
152
+ */
153
+
154
+ /** @param {string} code @returns {never} */
155
+ function usageError(code) {
156
+ throw Object.assign(new Error(code), { exitCode: USAGE_EXIT_CODE });
157
+ }
158
+
159
+ /**
160
+ * The value of a flag given as `--flag value` or `--flag=value`.
161
+ * @param {string[]} args @param {number} index @param {string} flag
162
+ * @returns {{ value: string, next: number }}
163
+ */
164
+ function flagValue(args, index, flag) {
165
+ const argument = /** @type {string} */ (args[index]);
166
+ const value = argument === flag ? args[index + 1] : argument.slice(flag.length + 1);
167
+ if (value === undefined || value === '') usageError(`option_value_required:${flag}`);
168
+ return { value: /** @type {string} */ (value), next: argument === flag ? index + 1 : index };
169
+ }
170
+
171
+ /**
172
+ * Take `--manager`, `--worker <name>` and `--room <name>` out of a launch's
173
+ * arguments (D2): launcher flags, consumed before the native arguments the way
174
+ * `--host` is. Everything after `--` belongs to the host.
175
+ * @param {string[]} args
176
+ * @param {'claude' | 'codex'} host
177
+ * @returns {{ request: RoleRequest | null, args: string[] }}
178
+ */
179
+ export function takeRoleFlags(args, host) {
180
+ /** @type {string[]} */
181
+ const rest = [];
182
+ /** @type {RoleFlag | null} */
183
+ let role = null;
184
+ /** @type {string | null} */
185
+ let roomName = null;
186
+ for (let index = 0; index < args.length; index += 1) {
187
+ const argument = /** @type {string} */ (args[index]);
188
+ if (argument === '--') {
189
+ rest.push(...args.slice(index));
190
+ break;
191
+ }
192
+ if (argument === MANAGER_FLAG) {
193
+ if (role !== null) usageError('role_flag_duplicate');
194
+ role = { kind: 'manager' };
195
+ } else if (argument === WORKER_FLAG || argument.startsWith(`${WORKER_FLAG}=`)) {
196
+ if (role !== null) usageError('role_flag_duplicate');
197
+ const taken = flagValue(args, index, WORKER_FLAG);
198
+ index = taken.next;
199
+ if (!NAME_PATTERN.test(taken.value) || taken.value === MANAGER_NAME)
200
+ usageError('worker_name_invalid');
201
+ role = { kind: 'worker', name: taken.value };
202
+ } else if (argument === ROOM_FLAG || argument.startsWith(`${ROOM_FLAG}=`)) {
203
+ if (roomName !== null) usageError('room_flag_duplicate');
204
+ const taken = flagValue(args, index, ROOM_FLAG);
205
+ index = taken.next;
206
+ if (!NAME_PATTERN.test(taken.value)) usageError('room_name_invalid');
207
+ roomName = taken.value;
208
+ } else rest.push(argument);
209
+ }
210
+ if (role === null) {
211
+ if (roomName !== null) usageError('room_flag_requires_role');
212
+ return { request: null, args: rest };
213
+ }
214
+ // v1: the manager is a Claude Code session and a worker is a Codex session (FR1).
215
+ if ((role.kind === 'manager') !== (host === 'claude')) usageError('role_unsupported_for_host');
216
+ // A worker is the interactive terminal; checked before anything is registered.
217
+ if (role.kind === 'worker') {
218
+ const subcommand = codexSubcommand(rest);
219
+ if (subcommand !== null && !WORKER_CODEX_SUBCOMMANDS.has(subcommand))
220
+ usageError('role_unsupported_for_command');
221
+ }
222
+ return { request: { role, roomName }, args: rest };
223
+ }
224
+
225
+ /**
226
+ * The Codex subcommand the native arguments name, or null for the interactive
227
+ * terminal (no subcommand, or a first word that is the prompt). A leading `--`
228
+ * is the launcher's separator; a later one is Codex's own, after which the
229
+ * words are the prompt.
230
+ * @param {string[]} args the native arguments, as `takeRoleFlags` leaves them
231
+ * @returns {string | null}
232
+ */
233
+ function codexSubcommand(args) {
234
+ const native = args[0] === '--' ? args.slice(1) : args;
235
+ for (let index = 0; index < native.length; index += 1) {
236
+ const argument = /** @type {string} */ (native[index]);
237
+ if (argument === '--') return null;
238
+ if (argument.startsWith('-')) {
239
+ if (!argument.includes('=') && CODEX_VALUE_OPTIONS.has(argument)) index += 1;
240
+ continue;
241
+ }
242
+ return CODEX_SUBCOMMANDS.has(argument) || WORKER_CODEX_SUBCOMMANDS.has(argument)
243
+ ? argument
244
+ : null;
245
+ }
246
+ return null;
247
+ }
248
+
249
+ /**
250
+ * Whether this Codex version gets the worker role (D14): the first release measured
251
+ * with it, or a later one. A null or malformed version never does. The caller has
252
+ * already checked that this client runs the version.
253
+ * @param {string | null | undefined} version
254
+ */
255
+ export function supportsWorkerRole(version) {
256
+ const match = STABLE_VERSION_PATTERN.exec(version ?? '');
257
+ const minimum = STABLE_VERSION_PATTERN.exec(MIN_WORKER_CODEX_VERSION);
258
+ if (match === null || minimum === null) return false;
259
+ for (let index = 1; index < match.length; index += 1) {
260
+ const difference = Number(match[index]) - Number(minimum[index]);
261
+ if (difference !== 0) return difference > 0;
262
+ }
263
+ return true;
264
+ }
265
+
266
+ /**
267
+ * Register this launch's session in its room, when the launch may have the
268
+ * role. A role that cannot be given never blocks the launch: the result says
269
+ * why and the host starts without it. Only a taken name, a second manager or
270
+ * a full room stop the launch, with exit 2, before any host starts (FR1).
271
+ * @param {object} input
272
+ * @param {string} input.root the client's state root
273
+ * @param {RoleRequest} input.request
274
+ * @param {{ name: 'claude' | 'codex', version: string | null }} input.host
275
+ * @param {string} input.cwd
276
+ * @param {BusLocale} input.locale
277
+ * @param {boolean} input.licensed the launch's license check passed (D11)
278
+ * @param {boolean} input.qualified the host version gets the role (D14)
279
+ * @param {import('./bus.mjs').BusClock} [input.clock]
280
+ * @param {import('./room.mjs').GitRunner} [input.git]
281
+ * @returns {Promise<ActiveRole | InactiveRole>}
282
+ */
283
+ export async function prepareRole({
284
+ root,
285
+ request,
286
+ host,
287
+ cwd,
288
+ locale,
289
+ licensed,
290
+ qualified,
291
+ clock,
292
+ git,
293
+ }) {
294
+ const kind = request.role.kind;
295
+ if (!licensed) return { active: false, kind, reason: 'license_inactive' };
296
+ if (!qualified) return { active: false, kind, reason: 'host_unqualified' };
297
+ const now = (clock?.now ?? Date.now)();
298
+ const name = request.role.kind === 'worker' ? request.role.name : MANAGER_NAME;
299
+ try {
300
+ await sweepBus(root, clock);
301
+ const room = await resolveRoom({
302
+ cwd,
303
+ roomName: request.roomName,
304
+ ...(git === undefined ? {} : { git }),
305
+ });
306
+ const paths = await ensureRoom(root, room, clock);
307
+ /** @type {SessionRecord} */
308
+ const record = {
309
+ schemaVersion: 1,
310
+ sessionId: newSessionId(),
311
+ name,
312
+ role: kind,
313
+ host: host.name,
314
+ hostVersion: host.version,
315
+ launcherPid: process.pid,
316
+ childPid: null,
317
+ startedAt: now,
318
+ cwd,
319
+ locale,
320
+ state: kind === 'manager' ? 'idle' : 'starting',
321
+ stateSince: now,
322
+ turnOrigin: null,
323
+ queued: 0,
324
+ sandbox: 'unknown',
325
+ approvalPolicy: 'unknown',
326
+ approval: null,
327
+ heldApprovals: [],
328
+ };
329
+ await registerSession(paths, record, clock);
330
+ await audit(paths, { event: 'registered', sessionId: record.sessionId, kind }, clock);
331
+ return {
332
+ active: true,
333
+ kind,
334
+ name,
335
+ roomLabel: room.label,
336
+ paths,
337
+ sessionId: record.sessionId,
338
+ environmentValue: roleEnvironmentValue({
339
+ role: kind,
340
+ stateRoot: root,
341
+ roomId: room.id,
342
+ sessionId: record.sessionId,
343
+ name,
344
+ locale,
345
+ }),
346
+ };
347
+ } catch (error) {
348
+ if (error instanceof BusError && REFUSED_REGISTRATIONS.includes(error.code))
349
+ throw Object.assign(new Error(error.code), { exitCode: USAGE_EXIT_CODE });
350
+ return { active: false, kind, reason: 'bus_unavailable' };
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Remove the session when its launch ends. The role process does this itself
356
+ * when it exits cleanly; this covers the one that did not. Never throws.
357
+ * @param {ActiveRole | InactiveRole | null} prepared
358
+ * @param {import('./bus.mjs').BusClock} [clock]
359
+ */
360
+ export async function closeRole(prepared, clock) {
361
+ if (prepared === null || !prepared.active) return;
362
+ await removeSession(prepared.paths, prepared.sessionId, prepared.kind).catch(() => undefined);
363
+ await audit(prepared.paths, { event: 'closed', sessionId: prepared.sessionId }, clock);
364
+ }
365
+
366
+ /**
367
+ * The one line a launch prints about its role (FR1), in the stored locale.
368
+ * @param {ActiveRole | InactiveRole} prepared
369
+ * @param {BusLocale} locale
370
+ */
371
+ export function roleLaunchLine(prepared, locale) {
372
+ const portuguese = locale === 'pt-BR';
373
+ if (!prepared.active) {
374
+ const role = prepared.kind === 'manager' ? (portuguese ? 'gerente' : 'manager') : 'worker';
375
+ return portuguese
376
+ ? `aisac: a sessão inicia sem o papel de ${role} (${prepared.reason}).`
377
+ : `aisac: the session starts without the ${role} role (${prepared.reason}).`;
378
+ }
379
+ if (prepared.kind === 'worker')
380
+ return portuguese
381
+ ? `aisac: worker "${prepared.name}" na sala "${prepared.roomLabel}": as mensagens da sessão gerente rodam nesta sessão, com o sandbox e a política de aprovação dela. O texto das mensagens e das respostas passa pelos provedores das duas sessões.`
382
+ : `aisac: worker "${prepared.name}" in room "${prepared.roomLabel}": messages from the manager session run in this session, under its own sandbox and approval policy. The text of messages and replies crosses the providers of both sessions.`;
383
+ return portuguese
384
+ ? `aisac: gerente da sala "${prepared.roomLabel}": as ferramentas manager_* alcançam os workers Codex desta sala; enviar uma mensagem pede a sua permissão. O texto das mensagens e das respostas passa pelos provedores das duas sessões.`
385
+ : `aisac: manager of room "${prepared.roomLabel}": the manager_* tools reach the Codex workers of this room; sending a message asks for your permission. The text of messages and replies crosses the providers of both sessions.`;
386
+ }
387
+
388
+ /**
389
+ * What the Codex chain needs for an active worker role: the role itself and
390
+ * the module the adapter loads.
391
+ * @param {ActiveRole} prepared
392
+ * @param {string} packageRoot
393
+ * @returns {Record<string, string>}
394
+ */
395
+ export function workerEnvironment(prepared, packageRoot) {
396
+ return {
397
+ [WORKER_ROLE_ENV]: prepared.environmentValue,
398
+ [WORKER_MODULE_ENV]: join(packageRoot, 'manager', 'worker.mjs'),
399
+ };
400
+ }
401
+
402
+ /**
403
+ * The manager's entry of the session's `mcp.json` (FR6): a stdio server of the
404
+ * client, with the manager's identity in its environment and nowhere else.
405
+ * @param {ActiveRole} prepared
406
+ * @param {string} packageRoot
407
+ * @param {string} node
408
+ */
409
+ export function managerMcpEntry(prepared, packageRoot, node) {
410
+ return {
411
+ type: 'stdio',
412
+ command: node,
413
+ args: [join(packageRoot, 'manager', 'server.mjs')],
414
+ env: { [MANAGER_ROLE_ENV]: prepared.environmentValue },
415
+ };
416
+ }
417
+
418
+ /** The allow rules of the manager's pre-allowed tools, in Claude Code's form (FR8). */
419
+ export function managerAllowRules() {
420
+ return MANAGER_ALLOWED_TOOLS.map((tool) => `mcp__${MANAGER_SERVER_NAME}__${tool}`);
421
+ }
422
+
423
+ /** The variables a launch must never inherit from an outer session. */
424
+ export const ROLE_ENVIRONMENT_VARIABLES = Object.freeze([
425
+ WORKER_ROLE_ENV,
426
+ WORKER_MODULE_ENV,
427
+ MANAGER_ROLE_ENV,
428
+ ]);
429
+
430
+ /**
431
+ * @typedef {object} ManagerDoctorSection
432
+ * @property {'supported' | 'claude_not_found'} manager_role
433
+ * @property {'supported' | 'host_unqualified' | 'codex_not_found'} worker_role
434
+ * @property {string} minimum_codex the first Codex release that gets the worker role
435
+ * @property {string[]} measured_codex the Codex releases the role's host gate ran on
436
+ * @property {{ label: string, kind: string, manager: boolean, workers: number, pending: number }[]} rooms
437
+ */
438
+
439
+ /**
440
+ * The `manager` section of `aisac doctor` (FR11): the roles the installed
441
+ * hosts can take and the live rooms with their counts. It reads and never
442
+ * writes, and reports a room by its label, never by a path.
443
+ * @param {object} input
444
+ * @param {string} input.root the client's state root
445
+ * @param {boolean} input.claude Claude Code is installed
446
+ * @param {string | null | undefined} input.codexVersion the installed Codex, when there is one
447
+ * @param {boolean} input.codexAccepted this client runs that Codex (listed, or the same protocol)
448
+ * @param {import('./bus.mjs').BusClock} [input.clock]
449
+ * @returns {Promise<ManagerDoctorSection>}
450
+ */
451
+ export async function managerDoctorSection({ root, claude, codexVersion, codexAccepted, clock }) {
452
+ /** @type {ManagerDoctorSection['rooms']} */
453
+ const rooms = [];
454
+ for (const { descriptor, paths } of await listRooms(root)) {
455
+ const sessions = await listSessions(paths, { ...clock, sweep: false });
456
+ if (sessions.length === 0) continue;
457
+ const pending = await readdir(paths.pending).catch(() => []);
458
+ rooms.push({
459
+ label: descriptor.label,
460
+ kind: descriptor.kind,
461
+ manager: sessions.some((entry) => entry.role === 'manager'),
462
+ workers: sessions.filter((entry) => entry.role === 'worker').length,
463
+ pending: pending.filter((name) => MESSAGE_FILE_PATTERN.test(name)).length,
464
+ });
465
+ }
466
+ /** @type {ManagerDoctorSection['worker_role']} */
467
+ let workerRole = 'codex_not_found';
468
+ if (typeof codexVersion === 'string')
469
+ workerRole =
470
+ codexAccepted && supportsWorkerRole(codexVersion) ? 'supported' : 'host_unqualified';
471
+ return {
472
+ manager_role: claude ? 'supported' : 'claude_not_found',
473
+ worker_role: workerRole,
474
+ minimum_codex: MIN_WORKER_CODEX_VERSION,
475
+ measured_codex: [...MEASURED_WORKER_CODEX_VERSIONS],
476
+ rooms,
477
+ };
478
+ }
479
+
480
+ /**
481
+ * The text doctor's one line for the section.
482
+ * @param {ManagerDoctorSection | null} section
483
+ */
484
+ export function managerDoctorLine(section) {
485
+ if (section === null) return 'manager: unavailable';
486
+ const rooms =
487
+ section.rooms.length === 0
488
+ ? 'no live room'
489
+ : section.rooms
490
+ .map(
491
+ (room) =>
492
+ `${room.label} (${room.manager ? 'manager, ' : ''}${room.workers} worker${room.workers === 1 ? '' : 's'}, ${room.pending} pending)`,
493
+ )
494
+ .join('; ');
495
+ return `manager: manager role ${section.manager_role}; worker role ${section.worker_role} (Codex ${section.minimum_codex} or newer; measured with Codex ${section.measured_codex.join(', ')}); ${rooms}`;
496
+ }