@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,918 @@
|
|
|
1
|
+
// The manager session's hook nudges and its wake (spec aisac-engineering-manager
|
|
2
|
+
// D9, D12, FR7, FR9; ADR-0058): a per-launch Claude Code plugin whose hooks
|
|
3
|
+
// tell the manager's model, in one content-free line, that something waits for
|
|
4
|
+
// it. Every line is `statusLine(status)`: counts and worker names, never
|
|
5
|
+
// message, reply or command text. A hook never breaks the session: anything
|
|
6
|
+
// unexpected is exit 0 with no output.
|
|
7
|
+
//
|
|
8
|
+
// Claude Code runs `node <package>/manager/hooks.mjs <event>` with the hook's
|
|
9
|
+
// JSON on stdin and the manager's role in AISAC_MANAGER_ROLE, which the
|
|
10
|
+
// launcher exported into the Claude Code process.
|
|
11
|
+
// - UserPromptSubmit: the line as context when there is news; records the
|
|
12
|
+
// turn's baseline.
|
|
13
|
+
// - Stop: continues the turn once with the line when a reply or a held
|
|
14
|
+
// approval request is new since the baseline.
|
|
15
|
+
// - PostToolUse and PostToolUseFailure: the line once per approval request
|
|
16
|
+
// held for the manager.
|
|
17
|
+
// - wake: an `asyncRewake` hook started at each Stop. It waits for news the
|
|
18
|
+
// model has not been told about, then exits 2 with the line on stderr,
|
|
19
|
+
// which wakes an idle session; at its timeout it exits 0 silently.
|
|
20
|
+
//
|
|
21
|
+
// The state of one manager session lives in `<room>/manager/hooks/<session>/`,
|
|
22
|
+
// one file per writer so that no hook rewrites another's fields: `prompt.json`
|
|
23
|
+
// (UserPromptSubmit), `stop.json` (Stop), `wake.json` (the wake), the wake's
|
|
24
|
+
// lock, and `announced/<approval id>`, an empty file created exclusively, so
|
|
25
|
+
// that of hooks running at once exactly one announces a request.
|
|
26
|
+
|
|
27
|
+
import { randomBytes } from 'node:crypto';
|
|
28
|
+
import { realpathSync } from 'node:fs';
|
|
29
|
+
import { access, mkdir, readdir, rm, unlink, writeFile } from 'node:fs/promises';
|
|
30
|
+
import { isAbsolute, join } from 'node:path';
|
|
31
|
+
import { fileURLToPath } from 'node:url';
|
|
32
|
+
import {
|
|
33
|
+
BUS_SCHEMA_VERSION,
|
|
34
|
+
BusError,
|
|
35
|
+
LIMITS,
|
|
36
|
+
MANAGER_RECIPIENT,
|
|
37
|
+
MANAGER_ROLE_ENV,
|
|
38
|
+
MESSAGE_ID_PATTERN,
|
|
39
|
+
ensurePrivateDirectory,
|
|
40
|
+
isPlainRecord,
|
|
41
|
+
listSessions,
|
|
42
|
+
liveManager,
|
|
43
|
+
mailboxDirectory,
|
|
44
|
+
parseRoleEnvironment,
|
|
45
|
+
processAlive,
|
|
46
|
+
readJsonFile,
|
|
47
|
+
roomPaths,
|
|
48
|
+
writePrivateFile,
|
|
49
|
+
} from './bus.mjs';
|
|
50
|
+
import { listMailbox } from './messages.mjs';
|
|
51
|
+
import { hasNews, roomStatus, statusKey, statusLine } from './status.mjs';
|
|
52
|
+
import { createDirectoryWatch } from './watch.mjs';
|
|
53
|
+
|
|
54
|
+
export const MANAGER_PLUGIN_NAME = 'aisac-manager';
|
|
55
|
+
/** The runner's mode for the wake hook (FR9). */
|
|
56
|
+
export const WAKE_MODE = 'wake';
|
|
57
|
+
/** An `asyncRewake` hook that exits with this code wakes Claude, even an idle session. */
|
|
58
|
+
export const WAKE_EXIT_CODE = 2;
|
|
59
|
+
/** Seconds Claude Code gives each nudge before it cancels it. */
|
|
60
|
+
export const NUDGE_TIMEOUT_SECONDS = 5;
|
|
61
|
+
/** Lets the synchronous Stop hook record its continuation before the wake reads the state. */
|
|
62
|
+
export const WAKE_SETTLE_MS = 1_500;
|
|
63
|
+
|
|
64
|
+
const MANAGER_EVENTS = /** @type {const} */ ([
|
|
65
|
+
'UserPromptSubmit',
|
|
66
|
+
'Stop',
|
|
67
|
+
'PostToolUse',
|
|
68
|
+
'PostToolUseFailure',
|
|
69
|
+
]);
|
|
70
|
+
const PLUGIN_VERSION = '1.0.0';
|
|
71
|
+
const PLUGIN_DIRECTORY = 'manager-plugin';
|
|
72
|
+
const HOOKS_SCRIPT = join('manager', 'hooks.mjs');
|
|
73
|
+
const PRIVATE_DIRECTORY_MODE = 0o700;
|
|
74
|
+
const PRIVATE_FILE_MODE = 0o600;
|
|
75
|
+
const DEFAULT_WAKE = 'hook';
|
|
76
|
+
// The wake exits on its own first; Claude Code enforces `timeout` on an asyncRewake hook.
|
|
77
|
+
const WAKE_TIMEOUT_MARGIN_SECONDS = 60;
|
|
78
|
+
const STATE_DIRECTORY = 'hooks';
|
|
79
|
+
const PROMPT_FILE = 'prompt.json';
|
|
80
|
+
const STOP_FILE = 'stop.json';
|
|
81
|
+
const WAKE_FILE = 'wake.json';
|
|
82
|
+
const LOCK_FILE = 'wake.lock';
|
|
83
|
+
const ANNOUNCED_DIRECTORY = 'announced';
|
|
84
|
+
const KIBIBYTE = 1024;
|
|
85
|
+
const KEY_CHARS_MAX = 32 * KIBIBYTE;
|
|
86
|
+
const RECORD_BYTES_MAX = 2 * KEY_CHARS_MAX;
|
|
87
|
+
const LOCK_BYTES_MAX = KIBIBYTE;
|
|
88
|
+
// Every request a room can hold at once: sixteen workers holding up to 32 each.
|
|
89
|
+
const HELD_PER_WORKER_MAX = 32;
|
|
90
|
+
const HELD_MAX = LIMITS.workersPerRoom * HELD_PER_WORKER_MAX;
|
|
91
|
+
const TURN_MAX = Number.MAX_SAFE_INTEGER;
|
|
92
|
+
/** Claude Code caps a hook's context string at 10,000 characters. */
|
|
93
|
+
const HOOK_TEXT_MAX = 10_000;
|
|
94
|
+
// A Stop payload carries the turn's last answer, which can be long.
|
|
95
|
+
const INPUT_BYTES_MAX = 4 * 1024 * KIBIBYTE;
|
|
96
|
+
const STDIN_DEADLINE_MS = 5_000;
|
|
97
|
+
/** The wake's fallback poll, for file systems where the directory watch says nothing. */
|
|
98
|
+
const WAKE_POLL_MS = 5_000;
|
|
99
|
+
const MILLISECONDS_PER_SECOND = 1_000;
|
|
100
|
+
const LOCK_TOKEN_BYTES = 8;
|
|
101
|
+
const LOCK_TOKEN_PATTERN = /^[0-9a-f]{16}$/u;
|
|
102
|
+
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/u;
|
|
103
|
+
// Claude Code substitutes `${...}` placeholders in a hook's command and args.
|
|
104
|
+
const PLACEHOLDER = '${';
|
|
105
|
+
const TIMEOUT_ARGUMENT = '--timeout';
|
|
106
|
+
const ALREADY_EXISTS = 'EEXIST';
|
|
107
|
+
const MISSING = 'ENOENT';
|
|
108
|
+
/** The parts of `statusKey`, in its order, and the news each one is. */
|
|
109
|
+
const KEY_PARTS = /** @type {const} */ (['reply', 'user', 'held']);
|
|
110
|
+
const STOP_NEWS = /** @type {const} */ (['reply', 'held']);
|
|
111
|
+
const PROMPT_KEYS = ['schemaVersion', 'turn', 'baseline'];
|
|
112
|
+
const LOCK_KEYS = ['schemaVersion', 'pid', 'token', 'startedAt'];
|
|
113
|
+
|
|
114
|
+
/** @typedef {import('./bus.mjs').RoomPaths} RoomPaths */
|
|
115
|
+
/** @typedef {import('./bus.mjs').BusClock} BusClock */
|
|
116
|
+
/** @typedef {import('./bus.mjs').RoleEnvironment} RoleEnvironment */
|
|
117
|
+
/** @typedef {import('./status.mjs').RoomStatus} RoomStatus */
|
|
118
|
+
/** @typedef {import('./watch.mjs').DirectoryWatch} DirectoryWatch */
|
|
119
|
+
/** @typedef {(typeof KEY_PARTS)[number]} NewsKind */
|
|
120
|
+
/** @typedef {(typeof MANAGER_EVENTS)[number]} ManagerEvent */
|
|
121
|
+
/** @typedef {{ stdout: string, stderr: string, exitCode: number }} HookResult */
|
|
122
|
+
/**
|
|
123
|
+
* Runs a task after a delay; the returned function cancels it. The task may
|
|
124
|
+
* return a promise, which tests await.
|
|
125
|
+
* @typedef {(milliseconds: number, task: () => unknown) => () => void} Schedule
|
|
126
|
+
*/
|
|
127
|
+
/**
|
|
128
|
+
* @typedef {object} ManagerContext
|
|
129
|
+
* @property {RoleEnvironment} role
|
|
130
|
+
* @property {RoomPaths} paths
|
|
131
|
+
* @property {string} directory this manager session's hook state
|
|
132
|
+
*/
|
|
133
|
+
/** @typedef {{ turn: number, baseline: string | null }} PromptRecord */
|
|
134
|
+
/**
|
|
135
|
+
* @typedef {object} HookOptions
|
|
136
|
+
* @property {string | undefined} event a hook event of MANAGER_EVENTS, or `wake`
|
|
137
|
+
* @property {unknown} input the hook's JSON from stdin, parsed
|
|
138
|
+
* @property {NodeJS.ProcessEnv} env
|
|
139
|
+
* @property {BusClock} [clock]
|
|
140
|
+
* @property {DirectoryWatch} [watch] the wake's directory watch
|
|
141
|
+
* @property {Schedule} [schedule] the wake's timers
|
|
142
|
+
* @property {number} [timeoutSeconds] the wake's timeout
|
|
143
|
+
*/
|
|
144
|
+
|
|
145
|
+
/** @returns {HookResult} */
|
|
146
|
+
function quiet() {
|
|
147
|
+
return { stdout: '', stderr: '', exitCode: 0 };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** @param {string} text */
|
|
151
|
+
function hookText(text) {
|
|
152
|
+
return text.length > HOOK_TEXT_MAX ? text.slice(0, HOOK_TEXT_MAX) : text;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Context for the model next to the prompt, the tool result or the turn's end.
|
|
157
|
+
* @param {ManagerEvent} event
|
|
158
|
+
* @param {string} line
|
|
159
|
+
* @returns {HookResult}
|
|
160
|
+
*/
|
|
161
|
+
function contextResult(event, line) {
|
|
162
|
+
const output = {
|
|
163
|
+
hookSpecificOutput: { hookEventName: event, additionalContext: hookText(line) },
|
|
164
|
+
};
|
|
165
|
+
return { stdout: JSON.stringify(output), stderr: '', exitCode: 0 };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** @param {unknown} error */
|
|
169
|
+
function errorCode(error) {
|
|
170
|
+
return error instanceof Error && 'code' in error ? error.code : undefined;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** @param {NodeJS.ProcessEnv} env @returns {ManagerContext | null} */
|
|
174
|
+
function managerContext(env) {
|
|
175
|
+
const role = parseRoleEnvironment(env[MANAGER_ROLE_ENV], 'manager');
|
|
176
|
+
if (role === null) return null;
|
|
177
|
+
const paths = roomPaths(role.stateRoot, role.roomId);
|
|
178
|
+
return { role, paths, directory: join(paths.manager, STATE_DIRECTORY, role.sessionId) };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** @param {ManagerContext} context */
|
|
182
|
+
async function ensureStateDirectory(context) {
|
|
183
|
+
await ensurePrivateDirectory(context.directory);
|
|
184
|
+
await ensurePrivateDirectory(join(context.directory, ANNOUNCED_DIRECTORY));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** @param {unknown} value @param {string[]} keys */
|
|
188
|
+
function hasExactKeys(value, keys) {
|
|
189
|
+
if (!isPlainRecord(value)) return false;
|
|
190
|
+
const own = Object.keys(value);
|
|
191
|
+
return own.length === keys.length && own.every((key) => keys.includes(key));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* The news a status key names, one token per reply, waiting worker and held
|
|
196
|
+
* request. Anything that is not a key of `statusKey`'s shape names nothing.
|
|
197
|
+
* @param {string | null} key
|
|
198
|
+
* @returns {Set<string>}
|
|
199
|
+
*/
|
|
200
|
+
export function keyTokens(key) {
|
|
201
|
+
/** @type {Set<string>} */
|
|
202
|
+
const tokens = new Set();
|
|
203
|
+
if (key === null) return tokens;
|
|
204
|
+
/** @type {unknown} */
|
|
205
|
+
let parsed;
|
|
206
|
+
try {
|
|
207
|
+
parsed = JSON.parse(key);
|
|
208
|
+
} catch {
|
|
209
|
+
return tokens;
|
|
210
|
+
}
|
|
211
|
+
if (!Array.isArray(parsed) || parsed.length !== KEY_PARTS.length) return tokens;
|
|
212
|
+
KEY_PARTS.forEach((kind, index) => {
|
|
213
|
+
const part = /** @type {unknown} */ (parsed[index]);
|
|
214
|
+
if (!Array.isArray(part)) return;
|
|
215
|
+
for (const item of part) if (typeof item === 'string') tokens.add(`${kind}:${item}`);
|
|
216
|
+
});
|
|
217
|
+
return tokens;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** @param {unknown} value @returns {value is string | null} */
|
|
221
|
+
function isStoredKey(value) {
|
|
222
|
+
return value === null || (typeof value === 'string' && value.length <= KEY_CHARS_MAX);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** @param {string} key */
|
|
226
|
+
function boundedKey(key) {
|
|
227
|
+
return key.length <= KEY_CHARS_MAX ? key : null;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* One record of this session's state, of the current schema; null when it is
|
|
232
|
+
* missing, corrupt or too large.
|
|
233
|
+
* @param {ManagerContext} context
|
|
234
|
+
* @param {string} name
|
|
235
|
+
*/
|
|
236
|
+
async function readRecord(context, name) {
|
|
237
|
+
const file = await readJsonFile(join(context.directory, name), RECORD_BYTES_MAX);
|
|
238
|
+
if (!file.ok || !isPlainRecord(file.value)) return null;
|
|
239
|
+
return file.value.schemaVersion === BUS_SCHEMA_VERSION ? file.value : null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The prompt hook's record: the turn count and the turn's baseline. Only
|
|
244
|
+
* UserPromptSubmit writes it; anything unexpected reads as turn 0.
|
|
245
|
+
* @param {ManagerContext} context
|
|
246
|
+
* @returns {Promise<PromptRecord>}
|
|
247
|
+
*/
|
|
248
|
+
async function readPrompt(context) {
|
|
249
|
+
/** @type {PromptRecord} */
|
|
250
|
+
const empty = { turn: 0, baseline: null };
|
|
251
|
+
const record = await readRecord(context, PROMPT_FILE);
|
|
252
|
+
if (record === null || !hasExactKeys(record, PROMPT_KEYS)) return empty;
|
|
253
|
+
const { turn, baseline } = record;
|
|
254
|
+
if (typeof turn !== 'number' || !Number.isSafeInteger(turn) || turn < 0) return empty;
|
|
255
|
+
return isStoredKey(baseline) ? { turn, baseline } : empty;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The status key of a single-key record (`stop.json`, `wake.json`), or null.
|
|
260
|
+
* @param {ManagerContext} context
|
|
261
|
+
* @param {string} name
|
|
262
|
+
* @param {string} field
|
|
263
|
+
*/
|
|
264
|
+
async function readKey(context, name, field) {
|
|
265
|
+
const record = await readRecord(context, name);
|
|
266
|
+
if (record === null || !hasExactKeys(record, ['schemaVersion', field])) return null;
|
|
267
|
+
const key = record[field];
|
|
268
|
+
return isStoredKey(key) ? key : null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Write one record of this session's state by rename. Each record has one
|
|
273
|
+
* writer, so a write never rolls back another hook's fields.
|
|
274
|
+
* @param {ManagerContext} context
|
|
275
|
+
* @param {string} name
|
|
276
|
+
* @param {Record<string, unknown>} fields
|
|
277
|
+
*/
|
|
278
|
+
async function writeRecord(context, name, fields) {
|
|
279
|
+
const record = { schemaVersion: BUS_SCHEMA_VERSION, ...fields };
|
|
280
|
+
await writePrivateFile(
|
|
281
|
+
context.paths,
|
|
282
|
+
join(context.directory, name),
|
|
283
|
+
`${JSON.stringify(record)}\n`,
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* What the model was told: the turn's baseline, the key the Stop nudge last
|
|
289
|
+
* continued a turn on, and the key the wake last reported.
|
|
290
|
+
* @param {ManagerContext} context
|
|
291
|
+
*/
|
|
292
|
+
async function toldKeys(context) {
|
|
293
|
+
const [prompt, blocked, woke] = await Promise.all([
|
|
294
|
+
readPrompt(context),
|
|
295
|
+
readKey(context, STOP_FILE, 'blocked'),
|
|
296
|
+
readKey(context, WAKE_FILE, 'woke'),
|
|
297
|
+
]);
|
|
298
|
+
return [prompt.baseline, blocked, woke];
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* The news of a status that none of the reference keys names.
|
|
303
|
+
* @param {RoomStatus} status
|
|
304
|
+
* @param {(string | null)[]} references
|
|
305
|
+
* @param {readonly NewsKind[]} kinds
|
|
306
|
+
*/
|
|
307
|
+
function freshNews(status, references, kinds) {
|
|
308
|
+
const seen = new Set(references.flatMap((key) => [...keyTokens(key)]));
|
|
309
|
+
return [...keyTokens(statusKey(status))].filter(
|
|
310
|
+
(token) => !seen.has(token) && kinds.some((kind) => token.startsWith(`${kind}:`)),
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The held approval ids of a status, in id order and bounded. @param {RoomStatus} status */
|
|
315
|
+
function heldIds(status) {
|
|
316
|
+
const ids = new Set(status.held.map((entry) => entry.approvalId));
|
|
317
|
+
return [...ids]
|
|
318
|
+
.filter((id) => MESSAGE_ID_PATTERN.test(id))
|
|
319
|
+
.sort()
|
|
320
|
+
.slice(0, HELD_MAX);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* The approval ids announced so far. Taken before the room is read, so that
|
|
325
|
+
* the sweep only removes what existed then.
|
|
326
|
+
* @param {ManagerContext} context
|
|
327
|
+
* @returns {Promise<Set<string>>}
|
|
328
|
+
*/
|
|
329
|
+
async function listAnnounced(context) {
|
|
330
|
+
try {
|
|
331
|
+
return new Set(await readdir(join(context.directory, ANNOUNCED_DIRECTORY)));
|
|
332
|
+
} catch (error) {
|
|
333
|
+
if (errorCode(error) === MISSING) return new Set();
|
|
334
|
+
throw error;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Claim the announcement of one request by creating its file exclusively:
|
|
340
|
+
* true for the one hook that created it, false when it exists, null when the
|
|
341
|
+
* file system failed.
|
|
342
|
+
* @param {ManagerContext} context
|
|
343
|
+
* @param {string} id
|
|
344
|
+
* @returns {Promise<boolean | null>}
|
|
345
|
+
*/
|
|
346
|
+
async function claim(context, id) {
|
|
347
|
+
const path = join(context.directory, ANNOUNCED_DIRECTORY, id);
|
|
348
|
+
try {
|
|
349
|
+
await writeFile(path, '', { mode: PRIVATE_FILE_MODE, flag: 'wx' });
|
|
350
|
+
return true;
|
|
351
|
+
} catch (error) {
|
|
352
|
+
return errorCode(error) === ALREADY_EXISTS ? false : null;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Claim, in id order, every held request that was not announced before. With
|
|
358
|
+
* `exclusive`, a claim another hook won ends it with 0: that hook is telling
|
|
359
|
+
* the model now, and its line covers what this one would say.
|
|
360
|
+
* @param {ManagerContext} context
|
|
361
|
+
* @param {Set<string>} before
|
|
362
|
+
* @param {string[]} held
|
|
363
|
+
* @param {boolean} exclusive
|
|
364
|
+
* @returns {Promise<number>} the claims this hook won
|
|
365
|
+
*/
|
|
366
|
+
async function claimHeld(context, before, held, exclusive) {
|
|
367
|
+
let claimed = 0;
|
|
368
|
+
for (const id of held) {
|
|
369
|
+
if (before.has(id)) continue;
|
|
370
|
+
const won = await claim(context, id);
|
|
371
|
+
if (won === null) break;
|
|
372
|
+
if (!won && exclusive) return 0;
|
|
373
|
+
if (won) claimed += 1;
|
|
374
|
+
}
|
|
375
|
+
return claimed;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Remove the announcements of requests no longer held. Approval ids are never
|
|
380
|
+
* reused, so a request that is gone never needs its file again.
|
|
381
|
+
* @param {ManagerContext} context
|
|
382
|
+
* @param {Set<string>} before
|
|
383
|
+
* @param {string[]} held
|
|
384
|
+
*/
|
|
385
|
+
async function sweepAnnounced(context, before, held) {
|
|
386
|
+
const current = new Set(held);
|
|
387
|
+
for (const name of before) {
|
|
388
|
+
if (current.has(name)) continue;
|
|
389
|
+
await unlink(join(context.directory, ANNOUNCED_DIRECTORY, name)).catch(() => undefined);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* After a hook told the model about the held requests: claim them all, so
|
|
395
|
+
* that the tool hooks do not repeat them, and sweep. A failure here only
|
|
396
|
+
* risks a repeated line, so it never fails the hook.
|
|
397
|
+
* @param {ManagerContext} context
|
|
398
|
+
* @param {Set<string>} before
|
|
399
|
+
* @param {string[]} held
|
|
400
|
+
* @param {boolean} told
|
|
401
|
+
*/
|
|
402
|
+
async function markTold(context, before, held, told) {
|
|
403
|
+
try {
|
|
404
|
+
if (told) await claimHeld(context, before, held, false);
|
|
405
|
+
await sweepAnnounced(context, before, held);
|
|
406
|
+
} catch {
|
|
407
|
+
// Fail open: the worst case is the same line once more at a tool call.
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Remove the hook state of earlier manager sessions of the room, while this
|
|
413
|
+
* session is its live manager.
|
|
414
|
+
* @param {ManagerContext} context
|
|
415
|
+
* @param {BusClock | undefined} clock
|
|
416
|
+
*/
|
|
417
|
+
async function sweepEarlierSessions(context, clock) {
|
|
418
|
+
const manager = await liveManager(context.paths, clock);
|
|
419
|
+
if (manager?.sessionId !== context.role.sessionId) return;
|
|
420
|
+
const root = join(context.paths.manager, STATE_DIRECTORY);
|
|
421
|
+
for (const name of await readdir(root)) {
|
|
422
|
+
if (name === context.role.sessionId) continue;
|
|
423
|
+
await rm(join(root, name), { recursive: true, force: true });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* FR7: the line when there is news, and the turn's baseline.
|
|
429
|
+
* @param {ManagerContext} context
|
|
430
|
+
* @param {BusClock | undefined} clock
|
|
431
|
+
*/
|
|
432
|
+
async function onUserPromptSubmit(context, clock) {
|
|
433
|
+
const before = await listAnnounced(context);
|
|
434
|
+
const status = await roomStatus(context.paths, context.role.roomId, clock);
|
|
435
|
+
const { turn } = await readPrompt(context);
|
|
436
|
+
await ensureStateDirectory(context);
|
|
437
|
+
await writeRecord(context, PROMPT_FILE, {
|
|
438
|
+
turn: turn >= TURN_MAX ? 0 : turn + 1,
|
|
439
|
+
baseline: boundedKey(statusKey(status)),
|
|
440
|
+
});
|
|
441
|
+
const line = hasNews(status) ? statusLine(status) : null;
|
|
442
|
+
await markTold(context, before, heldIds(status), line !== null);
|
|
443
|
+
await sweepEarlierSessions(context, clock).catch(() => undefined);
|
|
444
|
+
return line === null ? quiet() : contextResult('UserPromptSubmit', line);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* FR7: continue the turn once when a reply or a held request is new since the
|
|
449
|
+
* baseline, the last continuation and the last wake. Never on a continuation.
|
|
450
|
+
* @param {ManagerContext} context
|
|
451
|
+
* @param {Record<string, unknown>} input
|
|
452
|
+
* @param {BusClock | undefined} clock
|
|
453
|
+
*/
|
|
454
|
+
async function onStop(context, input, clock) {
|
|
455
|
+
if (input.stop_hook_active === true) return quiet();
|
|
456
|
+
const before = await listAnnounced(context);
|
|
457
|
+
const status = await roomStatus(context.paths, context.role.roomId, clock);
|
|
458
|
+
if (freshNews(status, await toldKeys(context), STOP_NEWS).length === 0) return quiet();
|
|
459
|
+
const line = statusLine(status);
|
|
460
|
+
if (line === null) return quiet();
|
|
461
|
+
await ensureStateDirectory(context);
|
|
462
|
+
await writeRecord(context, STOP_FILE, { blocked: boundedKey(statusKey(status)) });
|
|
463
|
+
await markTold(context, before, heldIds(status), true);
|
|
464
|
+
return contextResult('Stop', line);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* FR7 (MG6): the line once per approval request held for the manager, after a
|
|
469
|
+
* tool call that succeeded or failed. It runs after every tool call, so it
|
|
470
|
+
* stops at the cheapest read that rules a held request out: an empty manager
|
|
471
|
+
* inbox, then the workers' records, which list the ids their adapter holds.
|
|
472
|
+
* The exclusive claim makes "once" hold across tool calls that run at once. A
|
|
473
|
+
* subagent's tool call is skipped, so that the main conversation is told.
|
|
474
|
+
* @param {'PostToolUse' | 'PostToolUseFailure'} event
|
|
475
|
+
* @param {ManagerContext} context
|
|
476
|
+
* @param {Record<string, unknown>} input
|
|
477
|
+
* @param {BusClock | undefined} clock
|
|
478
|
+
*/
|
|
479
|
+
async function onToolResult(event, context, input, clock) {
|
|
480
|
+
if (typeof input.agent_id === 'string' && input.agent_id.length > 0) return quiet();
|
|
481
|
+
const inbox = await listMailbox(context.paths, 'inbox', MANAGER_RECIPIENT);
|
|
482
|
+
if (inbox.names.length === 0) return quiet();
|
|
483
|
+
const before = await listAnnounced(context);
|
|
484
|
+
const sessions = await listSessions(context.paths, { ...clock, sweep: false });
|
|
485
|
+
const recorded = sessions.flatMap((entry) =>
|
|
486
|
+
entry.role === 'worker' ? entry.heldApprovals : [],
|
|
487
|
+
);
|
|
488
|
+
if (recorded.every((id) => before.has(id))) return quiet();
|
|
489
|
+
const status = await roomStatus(context.paths, context.role.roomId, clock);
|
|
490
|
+
const held = heldIds(status);
|
|
491
|
+
if (held.every((id) => before.has(id))) return quiet();
|
|
492
|
+
const line = statusLine(status);
|
|
493
|
+
if (line === null) return quiet();
|
|
494
|
+
await ensureStateDirectory(context);
|
|
495
|
+
const claimed = await claimHeld(context, before, held, true);
|
|
496
|
+
await sweepAnnounced(context, before, held).catch(() => undefined);
|
|
497
|
+
return claimed === 0 ? quiet() : contextResult(event, line);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* @typedef {object} WakeLock
|
|
502
|
+
* @property {1} schemaVersion
|
|
503
|
+
* @property {number} pid
|
|
504
|
+
* @property {string} token
|
|
505
|
+
* @property {number} startedAt
|
|
506
|
+
*/
|
|
507
|
+
|
|
508
|
+
/** @param {ManagerContext} context */
|
|
509
|
+
function lockPath(context) {
|
|
510
|
+
return join(context.directory, LOCK_FILE);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** @param {ManagerContext} context @returns {Promise<WakeLock | null>} */
|
|
514
|
+
async function readLock(context) {
|
|
515
|
+
const file = await readJsonFile(lockPath(context), LOCK_BYTES_MAX);
|
|
516
|
+
if (!file.ok || !hasExactKeys(file.value, LOCK_KEYS)) return null;
|
|
517
|
+
const lock = /** @type {Record<string, unknown>} */ (file.value);
|
|
518
|
+
if (lock.schemaVersion !== BUS_SCHEMA_VERSION) return null;
|
|
519
|
+
if (typeof lock.token !== 'string' || !LOCK_TOKEN_PATTERN.test(lock.token)) return null;
|
|
520
|
+
if (typeof lock.pid !== 'number' || typeof lock.startedAt !== 'number') return null;
|
|
521
|
+
return /** @type {WakeLock} */ (/** @type {unknown} */ (lock));
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Take the wake lock: the newest waiter of the session holds it, and an older
|
|
526
|
+
* one that sees another live holder's token exits.
|
|
527
|
+
* @param {ManagerContext} context
|
|
528
|
+
* @param {string} token
|
|
529
|
+
* @param {number} now
|
|
530
|
+
*/
|
|
531
|
+
async function writeLock(context, token, now) {
|
|
532
|
+
/** @type {WakeLock} */
|
|
533
|
+
const lock = { schemaVersion: BUS_SCHEMA_VERSION, pid: process.pid, token, startedAt: now };
|
|
534
|
+
await writePrivateFile(context.paths, lockPath(context), `${JSON.stringify(lock)}\n`);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** Remove the lock when this waiter still holds it. @param {ManagerContext} context @param {string} token */
|
|
538
|
+
async function releaseLock(context, token) {
|
|
539
|
+
const lock = await readLock(context);
|
|
540
|
+
if (lock?.token === token) await unlink(lockPath(context)).catch(() => undefined);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* @typedef {object} Waiter
|
|
545
|
+
* @property {ManagerContext} context
|
|
546
|
+
* @property {string} token
|
|
547
|
+
* @property {number} turn the prompt count when the waiter started
|
|
548
|
+
* @property {BusClock | undefined} clock
|
|
549
|
+
*/
|
|
550
|
+
/**
|
|
551
|
+
* What a wake that fires told the model: the status key, and the held
|
|
552
|
+
* requests with the announcements listed before the room was read.
|
|
553
|
+
* @typedef {{ key: string, before: Set<string>, held: string[] }} WakeReport
|
|
554
|
+
*/
|
|
555
|
+
/** @typedef {{ kind: 'wait' } | { kind: 'stop' } | { kind: 'news', line: string, report: WakeReport }} LookOutcome */
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Whether a newer waiter holds the lock. A lock whose process is gone is
|
|
559
|
+
* stale: this waiter takes it back and goes on, so the session is not left
|
|
560
|
+
* without one. A missing lock is not a replacement.
|
|
561
|
+
* @param {Waiter} waiter
|
|
562
|
+
*/
|
|
563
|
+
async function replaced(waiter) {
|
|
564
|
+
const { context, clock } = waiter;
|
|
565
|
+
const lock = await readLock(context);
|
|
566
|
+
if (lock === null || lock.token === waiter.token) return false;
|
|
567
|
+
if ((clock?.alive ?? processAlive)(lock.pid)) return true;
|
|
568
|
+
await writeLock(context, waiter.token, (clock?.now ?? Date.now)());
|
|
569
|
+
return false;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* One look at the room for a waiter: `stop` when a newer waiter took the lock,
|
|
574
|
+
* when its manager is gone or when a new prompt started a turn (that turn's
|
|
575
|
+
* Stop starts the next waiter); `news` when there is news nobody told the
|
|
576
|
+
* model. Writes nothing but a stale lock taken back.
|
|
577
|
+
* @param {Waiter} waiter
|
|
578
|
+
* @returns {Promise<LookOutcome>}
|
|
579
|
+
*/
|
|
580
|
+
async function lookOnce(waiter) {
|
|
581
|
+
const { context, clock } = waiter;
|
|
582
|
+
if (await replaced(waiter)) return { kind: 'stop' };
|
|
583
|
+
const manager = await liveManager(context.paths, clock);
|
|
584
|
+
if (manager?.sessionId !== context.role.sessionId) return { kind: 'stop' };
|
|
585
|
+
if ((await readPrompt(context)).turn !== waiter.turn) return { kind: 'stop' };
|
|
586
|
+
const before = await listAnnounced(context);
|
|
587
|
+
const status = await roomStatus(context.paths, context.role.roomId, clock);
|
|
588
|
+
if (freshNews(status, await toldKeys(context), KEY_PARTS).length === 0) return { kind: 'wait' };
|
|
589
|
+
const line = statusLine(status);
|
|
590
|
+
if (line === null) return { kind: 'wait' };
|
|
591
|
+
return { kind: 'news', line, report: { key: statusKey(status), before, held: heldIds(status) } };
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Record what the wake told the model, in its own record only.
|
|
596
|
+
* @param {ManagerContext} context
|
|
597
|
+
* @param {WakeReport} report
|
|
598
|
+
*/
|
|
599
|
+
async function recordWake(context, report) {
|
|
600
|
+
await writeRecord(context, WAKE_FILE, { woke: boundedKey(report.key) });
|
|
601
|
+
await markTold(context, report.before, report.held, true);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** @param {string} line @returns {HookResult} */
|
|
605
|
+
function wakeResult(line) {
|
|
606
|
+
return { stdout: '', stderr: `${hookText(line)}\n`, exitCode: WAKE_EXIT_CODE };
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** @param {number | undefined} seconds */
|
|
610
|
+
function wakeTimeoutMs(seconds) {
|
|
611
|
+
const valid =
|
|
612
|
+
seconds !== undefined &&
|
|
613
|
+
Number.isSafeInteger(seconds) &&
|
|
614
|
+
seconds > 0 &&
|
|
615
|
+
seconds <= LIMITS.wakeTimeoutMaxSeconds;
|
|
616
|
+
return (valid ? seconds : LIMITS.wakeTimeoutDefaultSeconds) * MILLISECONDS_PER_SECOND;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Wait for news: a look after the settle delay and after every change of the
|
|
621
|
+
* manager inbox, the sessions or this session's hook state (where the prompt
|
|
622
|
+
* record and the lock live), until news, a stop or the timeout. The first
|
|
623
|
+
* ending claims the result before any write, so the timeout and a late look
|
|
624
|
+
* never both act.
|
|
625
|
+
* @param {Waiter} waiter
|
|
626
|
+
* @param {{ watch: DirectoryWatch, schedule: Schedule, timeoutMs: number }} drive
|
|
627
|
+
* @returns {Promise<HookResult>}
|
|
628
|
+
*/
|
|
629
|
+
function waitForNews(waiter, drive) {
|
|
630
|
+
const { paths, directory } = waiter.context;
|
|
631
|
+
return new Promise((resolve) => {
|
|
632
|
+
/** @type {(() => void)[]} */
|
|
633
|
+
const cancels = [];
|
|
634
|
+
const flags = { done: false, settled: false, looking: false, again: false };
|
|
635
|
+
/** @param {HookResult} result @param {WakeReport | null} report */
|
|
636
|
+
const end = async (result, report) => {
|
|
637
|
+
if (flags.done) return;
|
|
638
|
+
flags.done = true;
|
|
639
|
+
for (const cancel of cancels) cancel();
|
|
640
|
+
if (report !== null) await recordWake(waiter.context, report).catch(() => undefined);
|
|
641
|
+
await releaseLock(waiter.context, waiter.token).catch(() => undefined);
|
|
642
|
+
resolve(result);
|
|
643
|
+
};
|
|
644
|
+
const look = async () => {
|
|
645
|
+
if (flags.done || !flags.settled) return;
|
|
646
|
+
if (flags.looking) {
|
|
647
|
+
flags.again = true;
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
flags.looking = true;
|
|
651
|
+
try {
|
|
652
|
+
do {
|
|
653
|
+
flags.again = false;
|
|
654
|
+
const outcome = await lookOnce(waiter);
|
|
655
|
+
if (outcome.kind === 'stop') return await end(quiet(), null);
|
|
656
|
+
if (outcome.kind === 'news') return await end(wakeResult(outcome.line), outcome.report);
|
|
657
|
+
} while (flags.again && !flags.done);
|
|
658
|
+
} catch {
|
|
659
|
+
await end(quiet(), null);
|
|
660
|
+
} finally {
|
|
661
|
+
flags.looking = false;
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
cancels.push(drive.schedule(drive.timeoutMs, () => end(quiet(), null)));
|
|
665
|
+
cancels.push(
|
|
666
|
+
drive.schedule(WAKE_SETTLE_MS, () => {
|
|
667
|
+
flags.settled = true;
|
|
668
|
+
return look();
|
|
669
|
+
}),
|
|
670
|
+
);
|
|
671
|
+
cancels.push(
|
|
672
|
+
drive.watch(
|
|
673
|
+
[mailboxDirectory(paths, 'inbox', MANAGER_RECIPIENT), paths.sessions, directory],
|
|
674
|
+
() => look(),
|
|
675
|
+
),
|
|
676
|
+
);
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** @type {Schedule} */
|
|
681
|
+
function realSchedule(milliseconds, task) {
|
|
682
|
+
const timer = setTimeout(task, milliseconds);
|
|
683
|
+
return () => clearTimeout(timer);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* FR9 (MG5): block until news the model was not told about, then exit 2 with
|
|
688
|
+
* the line on stderr; exit 0 silently at the timeout. Started by Claude Code at
|
|
689
|
+
* each Stop; the newest waiter replaces the one before it.
|
|
690
|
+
* @param {ManagerContext} context
|
|
691
|
+
* @param {HookOptions} options
|
|
692
|
+
*/
|
|
693
|
+
async function onWake(context, options) {
|
|
694
|
+
const token = randomBytes(LOCK_TOKEN_BYTES).toString('hex');
|
|
695
|
+
await ensureStateDirectory(context);
|
|
696
|
+
const { turn } = await readPrompt(context);
|
|
697
|
+
await writeLock(context, token, (options.clock?.now ?? Date.now)());
|
|
698
|
+
return waitForNews(
|
|
699
|
+
{ context, token, turn, clock: options.clock },
|
|
700
|
+
{
|
|
701
|
+
watch: options.watch ?? createDirectoryWatch({ pollMs: WAKE_POLL_MS }),
|
|
702
|
+
schedule: options.schedule ?? realSchedule,
|
|
703
|
+
timeoutMs: wakeTimeoutMs(options.timeoutSeconds),
|
|
704
|
+
},
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** @param {unknown} event @returns {event is ManagerEvent | typeof WAKE_MODE} */
|
|
709
|
+
function isKnownEvent(event) {
|
|
710
|
+
return event === WAKE_MODE || MANAGER_EVENTS.some((name) => name === event);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Run one hook. Never throws: no role, an unknown event, unreadable input or
|
|
715
|
+
* any internal error is exit 0 with no output.
|
|
716
|
+
* @param {HookOptions} options
|
|
717
|
+
* @returns {Promise<HookResult>}
|
|
718
|
+
*/
|
|
719
|
+
export async function runManagerHook(options) {
|
|
720
|
+
try {
|
|
721
|
+
const { event, input } = options;
|
|
722
|
+
if (!isKnownEvent(event) || !isPlainRecord(input)) return quiet();
|
|
723
|
+
const context = managerContext(options.env);
|
|
724
|
+
if (context === null) return quiet();
|
|
725
|
+
if (event === WAKE_MODE) return await onWake(context, options);
|
|
726
|
+
// A payload for another event than the one this command was declared on is not ours.
|
|
727
|
+
if (input.hook_event_name !== undefined && input.hook_event_name !== event) return quiet();
|
|
728
|
+
if (event === 'UserPromptSubmit') return await onUserPromptSubmit(context, options.clock);
|
|
729
|
+
if (event === 'Stop') return await onStop(context, input, options.clock);
|
|
730
|
+
return await onToolResult(event, context, input, options.clock);
|
|
731
|
+
} catch {
|
|
732
|
+
return quiet();
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** @param {string} path */
|
|
737
|
+
function safeAbsolute(path) {
|
|
738
|
+
return isAbsolute(path) && !CONTROL_CHARACTERS.test(path) && !path.includes(PLACEHOLDER);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* One exec-form command hook: the absolute Node executable and the runner,
|
|
743
|
+
* with no shell, so a path with spaces or quotes stays one argument.
|
|
744
|
+
* @param {{ node: string, script: string }} paths
|
|
745
|
+
* @param {string[]} args
|
|
746
|
+
*/
|
|
747
|
+
function commandHook(paths, args) {
|
|
748
|
+
return { type: 'command', command: paths.node, args: [paths.script, ...args] };
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* The plugin's hooks.json: the four nudges with short timeouts, and with
|
|
753
|
+
* `wake: 'hook'` the wake as an asyncRewake Stop hook.
|
|
754
|
+
* @param {{ node: string, script: string, wake: 'hook' | 'off', wakeTimeoutSeconds: number }} input
|
|
755
|
+
*/
|
|
756
|
+
function managerHooks(input) {
|
|
757
|
+
/** @param {ManagerEvent} event */
|
|
758
|
+
const nudge = (event) => ({ ...commandHook(input, [event]), timeout: NUDGE_TIMEOUT_SECONDS });
|
|
759
|
+
const wake = {
|
|
760
|
+
...commandHook(input, [WAKE_MODE, TIMEOUT_ARGUMENT, String(input.wakeTimeoutSeconds)]),
|
|
761
|
+
asyncRewake: true,
|
|
762
|
+
timeout: input.wakeTimeoutSeconds + WAKE_TIMEOUT_MARGIN_SECONDS,
|
|
763
|
+
};
|
|
764
|
+
return {
|
|
765
|
+
description:
|
|
766
|
+
'AISAC manager nudges for this session: counts and worker names, never message text.',
|
|
767
|
+
hooks: {
|
|
768
|
+
UserPromptSubmit: [{ hooks: [nudge('UserPromptSubmit')] }],
|
|
769
|
+
PostToolUse: [{ hooks: [nudge('PostToolUse')] }],
|
|
770
|
+
PostToolUseFailure: [{ hooks: [nudge('PostToolUseFailure')] }],
|
|
771
|
+
Stop: [{ hooks: input.wake === 'hook' ? [nudge('Stop'), wake] : [nudge('Stop')] }],
|
|
772
|
+
},
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/** @param {number | undefined} seconds */
|
|
777
|
+
function pluginWakeSeconds(seconds) {
|
|
778
|
+
return wakeTimeoutMs(seconds) / MILLISECONDS_PER_SECOND;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* The plugin's manifest and hooks file, private, in new directories. The
|
|
783
|
+
* manifest names no `hooks` path: Claude Code loads `hooks/hooks.json` by
|
|
784
|
+
* itself and merges a declared path into it.
|
|
785
|
+
* @param {string} pluginRoot
|
|
786
|
+
* @param {ReturnType<typeof managerHooks>} hooks
|
|
787
|
+
*/
|
|
788
|
+
async function writePluginFiles(pluginRoot, hooks) {
|
|
789
|
+
const manifest = {
|
|
790
|
+
name: MANAGER_PLUGIN_NAME,
|
|
791
|
+
version: PLUGIN_VERSION,
|
|
792
|
+
description: 'AISAC manager hook nudges, loaded for this session only.',
|
|
793
|
+
author: { name: 'AISAC' },
|
|
794
|
+
};
|
|
795
|
+
await mkdir(join(pluginRoot, '.claude-plugin'), {
|
|
796
|
+
recursive: true,
|
|
797
|
+
mode: PRIVATE_DIRECTORY_MODE,
|
|
798
|
+
});
|
|
799
|
+
await mkdir(join(pluginRoot, 'hooks'), { mode: PRIVATE_DIRECTORY_MODE });
|
|
800
|
+
const options = { mode: PRIVATE_FILE_MODE, flag: 'wx' };
|
|
801
|
+
await writeFile(
|
|
802
|
+
join(pluginRoot, '.claude-plugin', 'plugin.json'),
|
|
803
|
+
`${JSON.stringify(manifest, null, 2)}\n`,
|
|
804
|
+
options,
|
|
805
|
+
);
|
|
806
|
+
await writeFile(
|
|
807
|
+
join(pluginRoot, 'hooks', 'hooks.json'),
|
|
808
|
+
`${JSON.stringify(hooks, null, 2)}\n`,
|
|
809
|
+
options,
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Write the manager's per-launch plugin into the launch's private directory,
|
|
815
|
+
* which the launcher removes when the session ends. Throws `bus_unavailable`
|
|
816
|
+
* when a path is unsafe for a hook command or the runner is missing; the
|
|
817
|
+
* launcher then starts the session without the nudges.
|
|
818
|
+
* @param {{ directory: string, packageRoot: string, node?: string, wake?: 'hook' | 'off', wakeTimeoutSeconds?: number }} input
|
|
819
|
+
* @returns {Promise<{ pluginRoot: string }>}
|
|
820
|
+
*/
|
|
821
|
+
export async function prepareManagerPlugin(input) {
|
|
822
|
+
const node = input.node ?? process.execPath;
|
|
823
|
+
const script = join(input.packageRoot, HOOKS_SCRIPT);
|
|
824
|
+
const pluginRoot = join(input.directory, PLUGIN_DIRECTORY);
|
|
825
|
+
if (![node, script, pluginRoot].every(safeAbsolute))
|
|
826
|
+
throw new BusError('bus_unavailable', 'plugin_path_unsafe');
|
|
827
|
+
await access(script).catch(() => {
|
|
828
|
+
throw new BusError('bus_unavailable', 'manager_hooks_missing');
|
|
829
|
+
});
|
|
830
|
+
const hooks = managerHooks({
|
|
831
|
+
node,
|
|
832
|
+
script,
|
|
833
|
+
wake: input.wake ?? DEFAULT_WAKE,
|
|
834
|
+
wakeTimeoutSeconds: pluginWakeSeconds(input.wakeTimeoutSeconds ?? LIMITS.wakeTimeoutMaxSeconds),
|
|
835
|
+
});
|
|
836
|
+
await writePluginFiles(pluginRoot, hooks);
|
|
837
|
+
return { pluginRoot };
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* Standard input up to the size limit, or null when it is larger or does not
|
|
842
|
+
* end before the deadline.
|
|
843
|
+
* @returns {Promise<string | null>}
|
|
844
|
+
*/
|
|
845
|
+
function readStandardInput() {
|
|
846
|
+
return new Promise((resolve) => {
|
|
847
|
+
/** @type {Buffer[]} */
|
|
848
|
+
const chunks = [];
|
|
849
|
+
let size = 0;
|
|
850
|
+
const finish = (/** @type {string | null} */ text) => {
|
|
851
|
+
clearTimeout(deadline);
|
|
852
|
+
process.stdin.removeAllListeners();
|
|
853
|
+
process.stdin.destroy();
|
|
854
|
+
resolve(text);
|
|
855
|
+
};
|
|
856
|
+
const deadline = setTimeout(() => finish(null), STDIN_DEADLINE_MS);
|
|
857
|
+
process.stdin.on('data', (/** @type {Buffer} */ chunk) => {
|
|
858
|
+
size += chunk.length;
|
|
859
|
+
if (size > INPUT_BYTES_MAX) finish(null);
|
|
860
|
+
else chunks.push(chunk);
|
|
861
|
+
});
|
|
862
|
+
process.stdin.on('end', () => finish(Buffer.concat(chunks).toString('utf8')));
|
|
863
|
+
process.stdin.on('error', () => finish(null));
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** @param {string[]} args @returns {number | undefined} */
|
|
868
|
+
function timeoutArgument(args) {
|
|
869
|
+
if (args.length !== 2 || args[0] !== TIMEOUT_ARGUMENT) return undefined;
|
|
870
|
+
const seconds = Number(args[1]);
|
|
871
|
+
return Number.isSafeInteger(seconds) ? seconds : undefined;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/** @param {string} text @param {NodeJS.WriteStream} stream */
|
|
875
|
+
function writeAll(text, stream) {
|
|
876
|
+
return new Promise((resolve) => {
|
|
877
|
+
if (text.length === 0) resolve(undefined);
|
|
878
|
+
else stream.write(text, () => resolve(undefined));
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
async function main() {
|
|
883
|
+
const [event, ...rest] = process.argv.slice(2);
|
|
884
|
+
const raw = await readStandardInput();
|
|
885
|
+
/** @type {unknown} */
|
|
886
|
+
let input = null;
|
|
887
|
+
try {
|
|
888
|
+
input = raw === null ? null : JSON.parse(raw);
|
|
889
|
+
} catch {
|
|
890
|
+
input = null;
|
|
891
|
+
}
|
|
892
|
+
const timeoutSeconds = timeoutArgument(rest);
|
|
893
|
+
const result = await runManagerHook({
|
|
894
|
+
event,
|
|
895
|
+
input,
|
|
896
|
+
env: process.env,
|
|
897
|
+
...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),
|
|
898
|
+
});
|
|
899
|
+
await writeAll(result.stdout, process.stdout);
|
|
900
|
+
await writeAll(result.stderr, process.stderr);
|
|
901
|
+
process.exitCode = result.exitCode;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/** Run directly (not imported), also through a symlinked or space-holding path. */
|
|
905
|
+
function invokedDirectly() {
|
|
906
|
+
const entry = process.argv[1];
|
|
907
|
+
if (entry === undefined) return false;
|
|
908
|
+
try {
|
|
909
|
+
return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
|
|
910
|
+
} catch {
|
|
911
|
+
return false;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
if (invokedDirectly())
|
|
916
|
+
main().catch(() => {
|
|
917
|
+
process.exitCode = 0;
|
|
918
|
+
});
|