@brunobracaioli/aibrain 0.4.0-beta.31 → 0.4.0-beta.32
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/dist/assets/jev-paid-pilot-terminal.mjs +4 -0
- package/dist/claude-observation.mjs +1 -1
- package/dist/cli.mjs +23 -4
- package/dist/engineering-pack.mjs +221 -31
- package/dist/launch.mjs +67 -6
- package/dist/manager/bus.mjs +20 -9
- package/dist/manager/launch-role.mjs +2 -0
- package/dist/mcp.mjs +40 -14
- package/dist/package.json +1 -1
- package/dist/policy.mjs +16 -0
- package/dist/process-snapshot.mjs +778 -0
- package/dist/release-manifest.json +7 -7
- package/dist/resources-next.mjs +498 -0
- package/dist/resources.mjs +963 -0
- package/package.json +1 -1
|
@@ -534,6 +534,10 @@ async function main() {
|
|
|
534
534
|
};
|
|
535
535
|
process.once('SIGINT', shutdown);
|
|
536
536
|
process.once('SIGTERM', shutdown);
|
|
537
|
+
// Closing the terminal sends SIGHUP (the kernel to the foreground group, and the
|
|
538
|
+
// launcher forwards it). Without a handler Node exits at once, skipping cleanup and
|
|
539
|
+
// leaving the detached monitor group (monitor, compaction proxy, app-server) running.
|
|
540
|
+
process.once('SIGHUP', shutdown);
|
|
537
541
|
|
|
538
542
|
initialGeneration = spawnMonitor();
|
|
539
543
|
|
|
@@ -16,7 +16,7 @@ export const MAX_LOG_FILES = 3;
|
|
|
16
16
|
const LOCK_WAIT_MS = 250;
|
|
17
17
|
const LOCK_STALE_MS = 30_000;
|
|
18
18
|
const ADMISSION_MS = 60 * 60 * 1000;
|
|
19
|
-
export const ADAPTER_VERSION = '0.4.0-beta.
|
|
19
|
+
export const ADAPTER_VERSION = '0.4.0-beta.32';
|
|
20
20
|
const MAX_DIAGNOSTIC_COUNT = 10_000_000;
|
|
21
21
|
const MAX_DIAGNOSTIC_BYTES = 128 * 1024 * 1024;
|
|
22
22
|
const CHECKPOINT_BACKENDS = new Set(['native_store', 'private_file']);
|
package/dist/cli.mjs
CHANGED
|
@@ -34,7 +34,13 @@ import {
|
|
|
34
34
|
tokenFailureGuide,
|
|
35
35
|
tokenPromptGuide,
|
|
36
36
|
} from './token-guide.mjs';
|
|
37
|
-
import {
|
|
37
|
+
import {
|
|
38
|
+
codexPolicyJson,
|
|
39
|
+
disclosureAnswerAccepted,
|
|
40
|
+
makePolicy,
|
|
41
|
+
publicPolicy,
|
|
42
|
+
isProfile,
|
|
43
|
+
} from './policy.mjs';
|
|
38
44
|
import { readDiagnostics } from './claude-observation.mjs';
|
|
39
45
|
import { readCodexDiagnostics } from './codex-diagnostics.mjs';
|
|
40
46
|
import { checkEngineeringLicense, licenseLine, unavailableLicense } from './engineering.mjs';
|
|
@@ -87,6 +93,7 @@ import { anyFormatter } from './guardrails/format.mjs';
|
|
|
87
93
|
import { readCodexGuardrails } from './guardrails-plugin.mjs';
|
|
88
94
|
import { codexHooksStatus, supportsCodexHooks } from './codex-hooks.mjs';
|
|
89
95
|
import { managerDoctorLine, managerDoctorSection, takeRoleFlags } from './manager/launch-role.mjs';
|
|
96
|
+
import { resourcesDoctorLine, resourcesDoctorSection, runResources } from './resources.mjs';
|
|
90
97
|
import { WORKERS_USAGE, workersCommand } from './manager/workers-cli.mjs';
|
|
91
98
|
import {
|
|
92
99
|
describeClientNotConfigured,
|
|
@@ -97,7 +104,7 @@ import {
|
|
|
97
104
|
} from './launch-feedback.mjs';
|
|
98
105
|
import { parseCodexLaunchArgs } from './codex-permissions.mjs';
|
|
99
106
|
|
|
100
|
-
const VERSION = '0.4.0-beta.
|
|
107
|
+
const VERSION = '0.4.0-beta.32';
|
|
101
108
|
// The command is `aisac`; `aibrain` is an alias installed from the same entry.
|
|
102
109
|
const COMMAND = 'aisac';
|
|
103
110
|
/** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
|
|
@@ -108,7 +115,7 @@ const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
|
|
|
108
115
|
|
|
109
116
|
function usage() {
|
|
110
117
|
console.log(
|
|
111
|
-
`${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--paste-token | --token-file PATH]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n [--host-codex managed|system]\n ${COMMAND} setup --login\n ${COMMAND} doctor [--json]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--manager | --worker <name> [--bus]] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--host managed|system] [--manager | --worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
|
|
118
|
+
`${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--paste-token | --token-file PATH]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n [--host-codex managed|system]\n ${COMMAND} setup --login\n ${COMMAND} doctor [--json]\n ${COMMAND} resources [--json] [--sizes]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--manager | --worker <name> [--bus]] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--host managed|system] [--manager | --worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
|
|
112
119
|
);
|
|
113
120
|
console.log(
|
|
114
121
|
'`aisac setup` signs in through the browser at a terminal; use `--paste-token` for the manual prompt, `--token-file` for automation, or `aisac setup --login` to replace an existing login.',
|
|
@@ -612,7 +619,7 @@ async function disclosureAccepted(
|
|
|
612
619
|
const rl = createInterface({ input: stdin, output: stdout });
|
|
613
620
|
try {
|
|
614
621
|
const answer = await rl.question(`${disclosure} Type ACCEPT to continue: `);
|
|
615
|
-
return answer
|
|
622
|
+
return disclosureAnswerAccepted(answer);
|
|
616
623
|
} finally {
|
|
617
624
|
rl.close();
|
|
618
625
|
}
|
|
@@ -1401,6 +1408,8 @@ async function doctor(json) {
|
|
|
1401
1408
|
codexCompatibility?.status === 'qualified' ||
|
|
1402
1409
|
codexCompatibility?.status === 'protocol_match',
|
|
1403
1410
|
}).catch(() => null),
|
|
1411
|
+
// Machine resources (spec aisac-engineering-resources FR1): counts only, no worktree work.
|
|
1412
|
+
resources: await resourcesDoctorSection({ root: stateRoot() }).catch(() => null),
|
|
1404
1413
|
paidOrPilot: probe?.ok
|
|
1405
1414
|
? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
|
|
1406
1415
|
: config
|
|
@@ -1412,6 +1421,7 @@ async function doctor(json) {
|
|
|
1412
1421
|
console.log(result);
|
|
1413
1422
|
for (const line of releaseDoctorLines(result)) console.log(line);
|
|
1414
1423
|
console.log(managerDoctorLine(result.manager));
|
|
1424
|
+
console.log(resourcesDoctorLine(result.resources));
|
|
1415
1425
|
}
|
|
1416
1426
|
if (!platform.ok || !config || !probe?.ok || !nativeReady) process.exitCode = 1;
|
|
1417
1427
|
}
|
|
@@ -1564,6 +1574,15 @@ async function main(argv) {
|
|
|
1564
1574
|
validateOptions(rest, new Set(['--json']), new Set());
|
|
1565
1575
|
return doctor(rest.includes('--json'));
|
|
1566
1576
|
}
|
|
1577
|
+
if (command === 'resources') {
|
|
1578
|
+
const root = stateRoot();
|
|
1579
|
+
return runResources(rest, {
|
|
1580
|
+
root,
|
|
1581
|
+
cwd: process.cwd(),
|
|
1582
|
+
locale: resolvePackLocale(await readStoredLocale(root), process.env),
|
|
1583
|
+
write: (line) => console.log(line),
|
|
1584
|
+
});
|
|
1585
|
+
}
|
|
1567
1586
|
if (command === 'status') {
|
|
1568
1587
|
validateOptions(rest, new Set(['--json']), new Set());
|
|
1569
1588
|
return status(rest.includes('--json'));
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* launch or treat a failure as licensed.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import { createHash, createPublicKey, verify } from 'node:crypto';
|
|
17
|
+
import { createHash, createPublicKey, randomBytes, verify } from 'node:crypto';
|
|
18
18
|
import { constants } from 'node:fs';
|
|
19
19
|
import {
|
|
20
20
|
lstat,
|
|
@@ -37,6 +37,13 @@ import {
|
|
|
37
37
|
unavailableReasonFor,
|
|
38
38
|
} from './engineering.mjs';
|
|
39
39
|
import { atomicJson } from './state.mjs';
|
|
40
|
+
import {
|
|
41
|
+
createStartLookup,
|
|
42
|
+
currentProcessStart,
|
|
43
|
+
isLaunchRunning,
|
|
44
|
+
readDescendantSnapshot,
|
|
45
|
+
snapshotHasLiveMember,
|
|
46
|
+
} from './process-snapshot.mjs';
|
|
40
47
|
import {
|
|
41
48
|
AGENT_NAME,
|
|
42
49
|
CODEX_AGENTS_DIRECTORY,
|
|
@@ -876,26 +883,138 @@ export async function prepareEngineeringPack(input) {
|
|
|
876
883
|
* skip while one is live, so the version it is about to run is never removed.
|
|
877
884
|
*/
|
|
878
885
|
|
|
886
|
+
/**
|
|
887
|
+
* What `launch.json` records about one launch (spec
|
|
888
|
+
* aisac-engineering-resources FR2). A schema 1 record has `role: 'unknown'`
|
|
889
|
+
* and no session id.
|
|
890
|
+
* @typedef {object} LaunchRecord
|
|
891
|
+
* @property {1} schemaVersion kept at 1: the previous client skips any other value, and its garbage collection would then miss a launch in use after a rollback
|
|
892
|
+
* @property {number} launcherPid
|
|
893
|
+
* @property {number | null} childPid
|
|
894
|
+
* @property {LaunchHost | null} host
|
|
895
|
+
* @property {string | null} sessionId 128-bit random, hex
|
|
896
|
+
* @property {'solo' | 'manager' | 'worker' | 'unknown'} role
|
|
897
|
+
* @property {string | null} roomId
|
|
898
|
+
* @property {string | null} roomLabel the repository folder or room name, never a path
|
|
899
|
+
* @property {string | null} cwd
|
|
900
|
+
* @property {string | null} launcherStartTime pid start token, read as the bus reads liveness
|
|
901
|
+
* @property {string | null} childStartTime
|
|
902
|
+
* @property {string | null} startedAt
|
|
903
|
+
*/
|
|
904
|
+
const SESSION_ID_PATTERN = /^[0-9a-f]{32}$/u;
|
|
905
|
+
const ROOM_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
906
|
+
const LAUNCH_ROLES = Object.freeze(['solo', 'manager', 'worker']);
|
|
907
|
+
const LAUNCH_CWD_MAX = 1024;
|
|
908
|
+
const START_TIME_MAX = 80;
|
|
909
|
+
const ROOM_LABEL_MAX = 64;
|
|
910
|
+
|
|
911
|
+
/** @param {unknown} value @param {number} limit @returns {string | null} */
|
|
912
|
+
function boundedString(value, limit) {
|
|
913
|
+
return typeof value === 'string' && value.length > 0 && value.length <= limit ? value : null;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Parse a launch marker (schema 1; the extended fields are optional); null when it is not one. An extended
|
|
918
|
+
* field that is malformed reads as absent: the record still counts as a launch.
|
|
919
|
+
* @param {unknown} value
|
|
920
|
+
* @returns {LaunchRecord | null}
|
|
921
|
+
*/
|
|
922
|
+
export function parseLaunchRecord(value) {
|
|
923
|
+
if (!isRecord(value) || value.schemaVersion !== 1) return null;
|
|
924
|
+
if (!isPid(value.launcherPid)) return null;
|
|
925
|
+
if (value.childPid !== null && !isPid(value.childPid)) return null;
|
|
926
|
+
// The extended form is told by its session id; a record without one is a plain
|
|
927
|
+
// launch marker whose extra fields, if any, are not read.
|
|
928
|
+
const sessionId =
|
|
929
|
+
typeof value.sessionId === 'string' && SESSION_ID_PATTERN.test(value.sessionId)
|
|
930
|
+
? value.sessionId
|
|
931
|
+
: null;
|
|
932
|
+
const extended = sessionId !== null;
|
|
933
|
+
const role =
|
|
934
|
+
extended && LAUNCH_ROLES.includes(/** @type {string} */ (value.role))
|
|
935
|
+
? /** @type {'solo' | 'manager' | 'worker'} */ (value.role)
|
|
936
|
+
: 'unknown';
|
|
937
|
+
return {
|
|
938
|
+
schemaVersion: 1,
|
|
939
|
+
launcherPid: /** @type {number} */ (value.launcherPid),
|
|
940
|
+
childPid: /** @type {number | null} */ (value.childPid),
|
|
941
|
+
host: launchHostOf(value.host),
|
|
942
|
+
sessionId,
|
|
943
|
+
role,
|
|
944
|
+
roomId:
|
|
945
|
+
extended && typeof value.roomId === 'string' && ROOM_ID_PATTERN.test(value.roomId)
|
|
946
|
+
? value.roomId
|
|
947
|
+
: null,
|
|
948
|
+
roomLabel: extended ? boundedString(value.roomLabel, ROOM_LABEL_MAX) : null,
|
|
949
|
+
cwd: extended ? boundedString(value.cwd, LAUNCH_CWD_MAX) : null,
|
|
950
|
+
launcherStartTime: extended ? boundedString(value.launcherStartTime, START_TIME_MAX) : null,
|
|
951
|
+
childStartTime: extended ? boundedString(value.childStartTime, START_TIME_MAX) : null,
|
|
952
|
+
startedAt: boundedString(value.startedAt, 40),
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/** The working directory, or null when it was removed under the process. */
|
|
957
|
+
function currentDirectory() {
|
|
958
|
+
try {
|
|
959
|
+
return process.cwd();
|
|
960
|
+
} catch {
|
|
961
|
+
return null;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/** @type {string | null | undefined} */
|
|
966
|
+
let ownStartTime;
|
|
967
|
+
|
|
879
968
|
/**
|
|
880
969
|
* Record who owns a launch directory, so a later launch can sweep it once
|
|
881
|
-
* both processes are gone (spec FR4 step 7),
|
|
970
|
+
* both processes are gone (spec FR4 step 7), which host it runs, and the
|
|
971
|
+
* session identity: a random id, the role, the room, the working directory
|
|
972
|
+
* and the start times of the launcher and the host. Each write keeps the id,
|
|
973
|
+
* role, room and start of the previous one unless the caller names a new value.
|
|
882
974
|
* @param {string} directory
|
|
883
|
-
* @param {{ launcherPid: number, childPid: number | null, host?: LaunchHost }} owners
|
|
975
|
+
* @param {{ launcherPid: number, childPid: number | null, host?: LaunchHost, role?: 'solo' | 'manager' | 'worker', roomId?: string | null, roomLabel?: string | null, cwd?: string }} owners
|
|
976
|
+
* @returns {Promise<LaunchRecord>} what was written
|
|
884
977
|
*/
|
|
885
978
|
export async function writeLaunchMarker(directory, owners) {
|
|
886
979
|
const path = join(directory, LAUNCH_MARKER_FILE);
|
|
887
980
|
const temp = `${path}.tmp-${process.pid}-${Date.now()}`;
|
|
981
|
+
const previous = parseLaunchRecord(await readSmallStateJson(path));
|
|
982
|
+
if (owners.launcherPid === process.pid && ownStartTime === undefined)
|
|
983
|
+
ownStartTime = currentProcessStart(process.pid);
|
|
984
|
+
const cwd = boundedString(owners.cwd ?? previous?.cwd ?? currentDirectory(), LAUNCH_CWD_MAX);
|
|
985
|
+
const written = {
|
|
986
|
+
schemaVersion: 1,
|
|
987
|
+
launcherPid: owners.launcherPid,
|
|
988
|
+
childPid: owners.childPid,
|
|
989
|
+
...(owners.host === undefined && previous?.host == null
|
|
990
|
+
? {}
|
|
991
|
+
: { host: owners.host ?? previous?.host }),
|
|
992
|
+
sessionId: previous?.sessionId ?? randomBytes(16).toString('hex'),
|
|
993
|
+
role:
|
|
994
|
+
owners.role ?? (previous === null || previous.role === 'unknown' ? 'solo' : previous.role),
|
|
995
|
+
roomId: owners.roomId === undefined ? (previous?.roomId ?? null) : owners.roomId,
|
|
996
|
+
roomLabel:
|
|
997
|
+
owners.roomLabel === undefined
|
|
998
|
+
? (previous?.roomLabel ?? null)
|
|
999
|
+
: boundedString(owners.roomLabel, ROOM_LABEL_MAX),
|
|
1000
|
+
cwd,
|
|
1001
|
+
launcherStartTime:
|
|
1002
|
+
owners.launcherPid === process.pid
|
|
1003
|
+
? (ownStartTime ?? null)
|
|
1004
|
+
: currentProcessStart(owners.launcherPid),
|
|
1005
|
+
childStartTime: owners.childPid === null ? null : currentProcessStart(owners.childPid),
|
|
1006
|
+
startedAt: previous?.startedAt ?? new Date().toISOString(),
|
|
1007
|
+
};
|
|
888
1008
|
try {
|
|
889
|
-
await writeFile(
|
|
890
|
-
temp,
|
|
891
|
-
`${JSON.stringify({ schemaVersion: 1, ...owners, startedAt: new Date().toISOString() })}\n`,
|
|
892
|
-
{ mode: 0o600, flag: 'wx' },
|
|
893
|
-
);
|
|
1009
|
+
await writeFile(temp, `${JSON.stringify(written)}\n`, { mode: 0o600, flag: 'wx' });
|
|
894
1010
|
await rename(temp, path);
|
|
895
1011
|
} catch (error) {
|
|
896
1012
|
await unlink(temp).catch(() => undefined);
|
|
897
1013
|
throw error;
|
|
898
1014
|
}
|
|
1015
|
+
const record = parseLaunchRecord(written);
|
|
1016
|
+
if (record === null) throw new Error('launch_marker_invalid');
|
|
1017
|
+
return record;
|
|
899
1018
|
}
|
|
900
1019
|
|
|
901
1020
|
/** @param {number} pid */
|
|
@@ -913,14 +1032,37 @@ function isPid(value) {
|
|
|
913
1032
|
return Number.isSafeInteger(value) && /** @type {number} */ (value) > 0;
|
|
914
1033
|
}
|
|
915
1034
|
|
|
1035
|
+
/**
|
|
1036
|
+
* Which of a launch's two processes still run (`isLaunchRunning`: pid, and the
|
|
1037
|
+
* start time where the record has one).
|
|
1038
|
+
* @param {LaunchRecord} record
|
|
1039
|
+
* @param {(pid: number) => boolean} alive
|
|
1040
|
+
* @param {import('./process-snapshot.mjs').StartLookup} startOf
|
|
1041
|
+
*/
|
|
1042
|
+
async function launchRunning(record, alive, startOf) {
|
|
1043
|
+
const launcher = await isLaunchRunning(
|
|
1044
|
+
record.launcherPid,
|
|
1045
|
+
record.launcherStartTime,
|
|
1046
|
+
alive,
|
|
1047
|
+
startOf,
|
|
1048
|
+
);
|
|
1049
|
+
const child = await isLaunchRunning(record.childPid, record.childStartTime, alive, startOf);
|
|
1050
|
+
return { launcher, child, any: launcher || child };
|
|
1051
|
+
}
|
|
1052
|
+
|
|
916
1053
|
/**
|
|
917
1054
|
* Remove launch directories left by crashed launches: only directories with
|
|
918
1055
|
* a marker whose launcher and child are both gone. Never throws.
|
|
919
1056
|
* @param {string} root
|
|
920
1057
|
* @param {(pid: number) => boolean} [alive]
|
|
1058
|
+
* @param {import('./process-snapshot.mjs').StartLookup} [startOf] the start token of a live pid
|
|
921
1059
|
* @returns {Promise<number>} directories removed
|
|
922
1060
|
*/
|
|
923
|
-
export async function sweepStaleLaunches(
|
|
1061
|
+
export async function sweepStaleLaunches(
|
|
1062
|
+
root,
|
|
1063
|
+
alive = processAlive,
|
|
1064
|
+
startOf = createStartLookup(),
|
|
1065
|
+
) {
|
|
924
1066
|
const runtime = join(root, 'runtime');
|
|
925
1067
|
let entries;
|
|
926
1068
|
try {
|
|
@@ -932,12 +1074,12 @@ export async function sweepStaleLaunches(root, alive = processAlive) {
|
|
|
932
1074
|
for (const entry of entries) {
|
|
933
1075
|
if (!entry.isDirectory() || !LAUNCH_DIRECTORY.test(entry.name)) continue;
|
|
934
1076
|
const directory = join(runtime, entry.name);
|
|
935
|
-
const
|
|
936
|
-
if (
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
if (
|
|
1077
|
+
const record = parseLaunchRecord(await readSmallStateJson(join(directory, LAUNCH_MARKER_FILE)));
|
|
1078
|
+
if (record === null) continue;
|
|
1079
|
+
if ((await launchRunning(record, alive, startOf)).any) continue;
|
|
1080
|
+
// A process the launch's snapshot lists is still running: keep the record, so
|
|
1081
|
+
// a later cleanup can attribute it (FR2).
|
|
1082
|
+
if (await snapshotHasLiveMember(directory, alive, startOf)) continue;
|
|
941
1083
|
try {
|
|
942
1084
|
await rm(directory, { recursive: true, force: true });
|
|
943
1085
|
removed += 1;
|
|
@@ -957,7 +1099,8 @@ export async function sweepStaleLaunches(root, alive = processAlive) {
|
|
|
957
1099
|
* @returns {Promise<number>}
|
|
958
1100
|
*/
|
|
959
1101
|
export async function liveLaunchCount(root, alive = processAlive) {
|
|
960
|
-
|
|
1102
|
+
const startOf = createStartLookup();
|
|
1103
|
+
await sweepStaleLaunches(root, alive, startOf);
|
|
961
1104
|
const runtime = join(root, 'runtime');
|
|
962
1105
|
let entries;
|
|
963
1106
|
try {
|
|
@@ -968,11 +1111,11 @@ export async function liveLaunchCount(root, alive = processAlive) {
|
|
|
968
1111
|
let live = 0;
|
|
969
1112
|
for (const entry of entries) {
|
|
970
1113
|
if (!entry.isDirectory() || !LAUNCH_DIRECTORY.test(entry.name)) continue;
|
|
971
|
-
const
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
if (
|
|
975
|
-
|
|
1114
|
+
const record = parseLaunchRecord(
|
|
1115
|
+
await readSmallStateJson(join(runtime, entry.name, LAUNCH_MARKER_FILE)),
|
|
1116
|
+
);
|
|
1117
|
+
if (record === null) continue;
|
|
1118
|
+
if ((await launchRunning(record, alive, startOf)).any) live += 1;
|
|
976
1119
|
}
|
|
977
1120
|
return live;
|
|
978
1121
|
}
|
|
@@ -995,7 +1138,8 @@ function launchHostOf(value) {
|
|
|
995
1138
|
* @returns {Promise<LaunchHost[]>}
|
|
996
1139
|
*/
|
|
997
1140
|
export async function liveLaunchHosts(root, alive = processAlive) {
|
|
998
|
-
|
|
1141
|
+
const startOf = createStartLookup();
|
|
1142
|
+
await sweepStaleLaunches(root, alive, startOf);
|
|
999
1143
|
const runtime = join(root, 'runtime');
|
|
1000
1144
|
let entries;
|
|
1001
1145
|
try {
|
|
@@ -1007,16 +1151,62 @@ export async function liveLaunchHosts(root, alive = processAlive) {
|
|
|
1007
1151
|
const hosts = [];
|
|
1008
1152
|
for (const entry of entries) {
|
|
1009
1153
|
if (!entry.isDirectory() || !LAUNCH_DIRECTORY.test(entry.name)) continue;
|
|
1010
|
-
const
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
if (
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
)
|
|
1017
|
-
continue;
|
|
1018
|
-
const host = launchHostOf(marker.host);
|
|
1154
|
+
const record = parseLaunchRecord(
|
|
1155
|
+
await readSmallStateJson(join(runtime, entry.name, LAUNCH_MARKER_FILE)),
|
|
1156
|
+
);
|
|
1157
|
+
if (record === null) continue;
|
|
1158
|
+
if (!(await launchRunning(record, alive, startOf)).any) continue;
|
|
1159
|
+
const host = record.host;
|
|
1019
1160
|
if (host !== null) hosts.push(host);
|
|
1020
1161
|
}
|
|
1021
1162
|
return hosts;
|
|
1022
1163
|
}
|
|
1164
|
+
|
|
1165
|
+
/**
|
|
1166
|
+
* One launch directory as `aisac resources` reads it (FR1, FR2).
|
|
1167
|
+
* @typedef {object} LaunchEntry
|
|
1168
|
+
* @property {string} name the directory name, `claude-` or `codex-` and six characters
|
|
1169
|
+
* @property {string} directory
|
|
1170
|
+
* @property {LaunchRecord} record
|
|
1171
|
+
* @property {boolean} live the launcher or the host still runs (pid and start time)
|
|
1172
|
+
* @property {boolean} launcherRunning
|
|
1173
|
+
* @property {boolean} childRunning
|
|
1174
|
+
* @property {import('./process-snapshot.mjs').SnapshotMember[]} members the snapshot's members
|
|
1175
|
+
*/
|
|
1176
|
+
|
|
1177
|
+
/**
|
|
1178
|
+
* Every launch directory with a readable marker, live or not, and its snapshot.
|
|
1179
|
+
* Read-only: nothing is swept. Never throws.
|
|
1180
|
+
* @param {string} root
|
|
1181
|
+
* @param {(pid: number) => boolean} [alive]
|
|
1182
|
+
* @param {import('./process-snapshot.mjs').StartLookup} [startOf]
|
|
1183
|
+
* @returns {Promise<LaunchEntry[]>}
|
|
1184
|
+
*/
|
|
1185
|
+
export async function listLaunches(root, alive = processAlive, startOf = createStartLookup()) {
|
|
1186
|
+
const runtime = join(root, 'runtime');
|
|
1187
|
+
let entries;
|
|
1188
|
+
try {
|
|
1189
|
+
entries = await readdir(runtime, { withFileTypes: true });
|
|
1190
|
+
} catch {
|
|
1191
|
+
return [];
|
|
1192
|
+
}
|
|
1193
|
+
/** @type {LaunchEntry[]} */
|
|
1194
|
+
const launches = [];
|
|
1195
|
+
for (const entry of entries) {
|
|
1196
|
+
if (!entry.isDirectory() || !LAUNCH_DIRECTORY.test(entry.name)) continue;
|
|
1197
|
+
const directory = join(runtime, entry.name);
|
|
1198
|
+
const record = parseLaunchRecord(await readSmallStateJson(join(directory, LAUNCH_MARKER_FILE)));
|
|
1199
|
+
if (record === null) continue;
|
|
1200
|
+
const running = await launchRunning(record, alive, startOf);
|
|
1201
|
+
launches.push({
|
|
1202
|
+
name: entry.name,
|
|
1203
|
+
directory,
|
|
1204
|
+
record,
|
|
1205
|
+
live: running.any,
|
|
1206
|
+
launcherRunning: running.launcher,
|
|
1207
|
+
childRunning: running.child,
|
|
1208
|
+
members: await readDescendantSnapshot(directory),
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
return launches;
|
|
1212
|
+
}
|
package/dist/launch.mjs
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
telemetryConfigBinding,
|
|
24
24
|
} from './state.mjs';
|
|
25
25
|
import { codexPolicyJson, makePolicy } from './policy.mjs';
|
|
26
|
+
import { retireLaunchDirectory, startDescendantSnapshots } from './process-snapshot.mjs';
|
|
26
27
|
import {
|
|
27
28
|
liveLaunchHosts,
|
|
28
29
|
prepareEngineeringPack,
|
|
@@ -107,6 +108,8 @@ import {
|
|
|
107
108
|
launchFeedbackLocale,
|
|
108
109
|
} from './launch-feedback.mjs';
|
|
109
110
|
|
|
111
|
+
/** The variable that carries the session id into the host (resources spec FR2). */
|
|
112
|
+
const SESSION_ID_ENV = 'AISAC_SESSION_ID';
|
|
110
113
|
const MCP_ALIAS = 'aibrain_context';
|
|
111
114
|
const PLUGIN_NAME = 'ai-brain-context-compaction';
|
|
112
115
|
const PLUGIN_INLINE_NAME = `${PLUGIN_NAME}@inline`;
|
|
@@ -521,12 +524,51 @@ async function recordChild(directory, childPid, host) {
|
|
|
521
524
|
);
|
|
522
525
|
}
|
|
523
526
|
|
|
524
|
-
/**
|
|
525
|
-
|
|
527
|
+
/**
|
|
528
|
+
* Add the role and room of an active manager or worker to the launch marker
|
|
529
|
+
* (resources spec FR2). The launcher knows them at launch time; nothing is read
|
|
530
|
+
* from the bus. A role that did not start leaves the launch `solo`.
|
|
531
|
+
* @param {string} directory
|
|
532
|
+
* @param {Awaited<ReturnType<typeof prepareRole>>} role
|
|
533
|
+
*/
|
|
534
|
+
async function recordRole(directory, role) {
|
|
535
|
+
if (!role.active) return;
|
|
536
|
+
await writeLaunchMarker(directory, {
|
|
537
|
+
launcherPid: process.pid,
|
|
538
|
+
childPid: null,
|
|
539
|
+
role: role.kind,
|
|
540
|
+
roomId: role.roomId,
|
|
541
|
+
roomLabel: role.roomLabel,
|
|
542
|
+
}).catch(() => undefined);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Put the session marker into a host's environment (resources spec FR2).
|
|
547
|
+
* @param {NodeJS.ProcessEnv} environment @param {string | null} sessionId
|
|
548
|
+
*/
|
|
549
|
+
function withSessionMarker(environment, sessionId) {
|
|
550
|
+
if (sessionId !== null) environment[SESSION_ID_ENV] = sessionId;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* @param {import('node:child_process').ChildProcess} child @param {string} directory
|
|
555
|
+
* @param {import('./process-snapshot.mjs').SnapshotterDependencies} [snapshotDeps]
|
|
556
|
+
*/
|
|
557
|
+
function waitForChild(child, directory, snapshotDeps = {}) {
|
|
558
|
+
// The descendant snapshot (resources spec FR2): the first walk about 3 s after the
|
|
559
|
+
// start, then every 30 s on an unref'ed timer, one when a terminating signal is
|
|
560
|
+
// forwarded, and one when the host exits. Nothing scans at launch.
|
|
561
|
+
const snapshots =
|
|
562
|
+
child.pid === undefined
|
|
563
|
+
? null
|
|
564
|
+
: startDescendantSnapshots({ directory, rootPid: child.pid, deps: snapshotDeps });
|
|
526
565
|
return new Promise((resolvePromise) => {
|
|
527
566
|
let settled = false;
|
|
528
567
|
/** @param {NodeJS.Signals} signal */
|
|
529
568
|
const forwardSignal = (signal) => {
|
|
569
|
+
// The walk starts as the signal is forwarded, so the members are on record
|
|
570
|
+
// before the host takes them down; it is not awaited.
|
|
571
|
+
if (signal !== 'SIGINT') void snapshots?.tick();
|
|
530
572
|
if (child.exitCode === null) child.kill(signal);
|
|
531
573
|
};
|
|
532
574
|
const signalHandlers = {
|
|
@@ -544,8 +586,16 @@ function waitForChild(child, directory) {
|
|
|
544
586
|
process.removeListener('SIGINT', signalHandlers.SIGINT);
|
|
545
587
|
process.removeListener('SIGTERM', signalHandlers.SIGTERM);
|
|
546
588
|
process.removeListener('SIGHUP', signalHandlers.SIGHUP);
|
|
547
|
-
|
|
589
|
+
// The directory goes with the host, unless a process the snapshot lists still
|
|
590
|
+
// runs: then only the two records stay, for attribution (FR2).
|
|
591
|
+
void (snapshots?.stop() ?? Promise.resolve())
|
|
548
592
|
.catch(() => undefined)
|
|
593
|
+
.then(() =>
|
|
594
|
+
retireLaunchDirectory(directory, {
|
|
595
|
+
...(snapshotDeps.alive === undefined ? {} : { alive: snapshotDeps.alive }),
|
|
596
|
+
...(snapshotDeps.startOf === undefined ? {} : { startOf: snapshotDeps.startOf }),
|
|
597
|
+
}),
|
|
598
|
+
)
|
|
549
599
|
.finally(() => resolvePromise(code));
|
|
550
600
|
};
|
|
551
601
|
child.once('error', () => finish(1));
|
|
@@ -720,7 +770,7 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
|
|
|
720
770
|
const currentVersion = compatibility.version ?? nativeVersion(pinnedExecutable);
|
|
721
771
|
/** @type {import('./engineering-pack.mjs').LaunchHost} */
|
|
722
772
|
const launchHost = { name: 'claude', mode: host.mode, version: compatibility.version ?? null };
|
|
723
|
-
await writeLaunchMarker(directory, {
|
|
773
|
+
const launchRecord = await writeLaunchMarker(directory, {
|
|
724
774
|
launcherPid: process.pid,
|
|
725
775
|
childPid: null,
|
|
726
776
|
host: launchHost,
|
|
@@ -888,6 +938,7 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
|
|
|
888
938
|
throw error;
|
|
889
939
|
}
|
|
890
940
|
notices.add({ plain: roleLaunchLine(role, locale) });
|
|
941
|
+
await recordRole(directory, role);
|
|
891
942
|
if (role.active && role.kind === 'manager') {
|
|
892
943
|
managerPlugin = await writeManagerPlugin({
|
|
893
944
|
directory,
|
|
@@ -971,6 +1022,8 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
|
|
|
971
1022
|
? managedHostEnvironment(childEnvironment(root))
|
|
972
1023
|
: childEnvironment(root);
|
|
973
1024
|
environment.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS = '1';
|
|
1025
|
+
// The session marker (resources spec FR2): the id `launch.json` records.
|
|
1026
|
+
withSessionMarker(environment, launchRecord.sessionId);
|
|
974
1027
|
// The manager's hooks and `aisac workers --wait` read the room from here (FR9).
|
|
975
1028
|
if (manager !== null) environment[MANAGER_ROLE_ENV] = manager.environmentValue;
|
|
976
1029
|
notices.draw();
|
|
@@ -1163,7 +1216,7 @@ export async function launchCodex(config, root, args, dependencies = {}, launchO
|
|
|
1163
1216
|
});
|
|
1164
1217
|
/** @type {import('./engineering-pack.mjs').LaunchHost} */
|
|
1165
1218
|
const launchHost = { name: 'codex', mode: host.mode, version: compatibility.version };
|
|
1166
|
-
await writeLaunchMarker(directory, {
|
|
1219
|
+
const launchRecord = await writeLaunchMarker(directory, {
|
|
1167
1220
|
launcherPid: process.pid,
|
|
1168
1221
|
childPid: null,
|
|
1169
1222
|
host: launchHost,
|
|
@@ -1292,6 +1345,7 @@ export async function launchCodex(config, root, args, dependencies = {}, launchO
|
|
|
1292
1345
|
throw error;
|
|
1293
1346
|
}
|
|
1294
1347
|
notices.add({ plain: roleLaunchLine(role, roleLocale) });
|
|
1348
|
+
await recordRole(directory, role);
|
|
1295
1349
|
if (role.active && role.kind === 'worker')
|
|
1296
1350
|
Object.assign(environment, workerEnvironment(role, packageRoot));
|
|
1297
1351
|
if (role.active && role.kind === 'manager') {
|
|
@@ -1317,6 +1371,7 @@ export async function launchCodex(config, root, args, dependencies = {}, launchO
|
|
|
1317
1371
|
}
|
|
1318
1372
|
}
|
|
1319
1373
|
}
|
|
1374
|
+
withSessionMarker(environment, launchRecord.sessionId);
|
|
1320
1375
|
environment.AI_BRAIN_MCP_SERVER = MCP_ALIAS;
|
|
1321
1376
|
environment.CODEX_BIN = executable;
|
|
1322
1377
|
environment.CODEX_MONITOR_COMMAND = monitor;
|
|
@@ -1393,4 +1448,10 @@ export async function launchCodex(config, root, args, dependencies = {}, launchO
|
|
|
1393
1448
|
return finished;
|
|
1394
1449
|
}
|
|
1395
1450
|
|
|
1396
|
-
export const launchInternals = {
|
|
1451
|
+
export const launchInternals = {
|
|
1452
|
+
MCP_ALIAS,
|
|
1453
|
+
PLUGIN_NAME,
|
|
1454
|
+
PLUGIN_INLINE_NAME,
|
|
1455
|
+
waitForChild,
|
|
1456
|
+
withSessionMarker,
|
|
1457
|
+
};
|
package/dist/manager/bus.mjs
CHANGED
|
@@ -291,6 +291,22 @@ function bootId() {
|
|
|
291
291
|
return cachedBootId;
|
|
292
292
|
}
|
|
293
293
|
|
|
294
|
+
/**
|
|
295
|
+
* The start-time token of one `/proc/<pid>/stat` text: the boot id and field 22
|
|
296
|
+
* (clock ticks since boot). Null when the text is not a stat line.
|
|
297
|
+
* @param {string} text
|
|
298
|
+
* @returns {string | null}
|
|
299
|
+
*/
|
|
300
|
+
export function startTokenFromStat(text) {
|
|
301
|
+
// The command name (field 2) is in parentheses and may hold spaces or `)`.
|
|
302
|
+
const close = text.lastIndexOf(')');
|
|
303
|
+
if (close === -1) return null;
|
|
304
|
+
const start = text.slice(close + 2).split(' ')[PROC_STAT_START_TIME_INDEX];
|
|
305
|
+
if (start === undefined || !DIGITS.test(start)) return null;
|
|
306
|
+
const boot = bootId();
|
|
307
|
+
return boot === null ? start : `${boot}:${start}`;
|
|
308
|
+
}
|
|
309
|
+
|
|
294
310
|
/**
|
|
295
311
|
* What identifies one process over its whole life, so that a pid reused by a
|
|
296
312
|
* later process is not taken for it: on Linux the boot id and the start time
|
|
@@ -298,23 +314,18 @@ function bootId() {
|
|
|
298
314
|
* `/proc` (macOS), or the process is gone, null: liveness is then the pid
|
|
299
315
|
* alone, with `EPERM` as "not ours" (`processAlive`).
|
|
300
316
|
* @param {number} pid
|
|
317
|
+
* @param {string} [procRoot] the `/proc` directory; a fixture in tests
|
|
301
318
|
* @returns {string | null}
|
|
302
319
|
*/
|
|
303
|
-
export function processStartToken(pid) {
|
|
320
|
+
export function processStartToken(pid, procRoot = '/proc') {
|
|
304
321
|
if (!isPid(pid)) return null;
|
|
305
322
|
let text;
|
|
306
323
|
try {
|
|
307
|
-
text = readFileSync(
|
|
324
|
+
text = readFileSync(`${procRoot}/${pid}/stat`, 'latin1');
|
|
308
325
|
} catch {
|
|
309
326
|
return null;
|
|
310
327
|
}
|
|
311
|
-
|
|
312
|
-
const close = text.lastIndexOf(')');
|
|
313
|
-
if (close === -1) return null;
|
|
314
|
-
const start = text.slice(close + 2).split(' ')[PROC_STAT_START_TIME_INDEX];
|
|
315
|
-
if (start === undefined || !DIGITS.test(start)) return null;
|
|
316
|
-
const boot = bootId();
|
|
317
|
-
return boot === null ? start : `${boot}:${start}`;
|
|
328
|
+
return startTokenFromStat(text);
|
|
318
329
|
}
|
|
319
330
|
|
|
320
331
|
/** @param {number} milliseconds @returns {Promise<void>} */
|
|
@@ -175,6 +175,7 @@ const CODEX_VALUE_OPTIONS = new Set([
|
|
|
175
175
|
* @property {'claude' | 'codex'} host
|
|
176
176
|
* @property {string} name
|
|
177
177
|
* @property {string} roomLabel
|
|
178
|
+
* @property {string} roomId the room's id, recorded in the launch marker (resources spec FR2)
|
|
178
179
|
* @property {RoomPaths} paths
|
|
179
180
|
* @property {string} sessionId
|
|
180
181
|
* @property {string} environmentValue the JSON the role process parses
|
|
@@ -452,6 +453,7 @@ export async function prepareRole({
|
|
|
452
453
|
host: host.name,
|
|
453
454
|
name,
|
|
454
455
|
roomLabel: room.label,
|
|
456
|
+
roomId: room.id,
|
|
455
457
|
paths,
|
|
456
458
|
sessionId: record.sessionId,
|
|
457
459
|
native,
|