@brunobracaioli/aibrain 0.4.0-beta.30 → 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/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
- /** @param {import('node:child_process').ChildProcess} child @param {string} directory */
525
- function waitForChild(child, directory) {
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
- void rm(directory, { recursive: true, force: true })
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 = { MCP_ALIAS, PLUGIN_NAME, PLUGIN_INLINE_NAME };
1451
+ export const launchInternals = {
1452
+ MCP_ALIAS,
1453
+ PLUGIN_NAME,
1454
+ PLUGIN_INLINE_NAME,
1455
+ waitForChild,
1456
+ withSessionMarker,
1457
+ };
@@ -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(`/proc/${pid}/stat`, 'latin1');
324
+ text = readFileSync(`${procRoot}/${pid}/stat`, 'latin1');
308
325
  } catch {
309
326
  return null;
310
327
  }
311
- // The command name (field 2) is in parentheses and may hold spaces or `)`.
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,
package/dist/mcp.mjs CHANGED
@@ -550,21 +550,47 @@ function responseError(response, fallback) {
550
550
  return fallback;
551
551
  }
552
552
 
553
- /** @param {JsonObject | null} result @returns {string | undefined} */
554
- function structuredErrorCode(result) {
555
- if (!result || result.isError !== true || !Array.isArray(result.content)) return undefined;
556
- const text = result.content.find((item) => isObject(item) && typeof item.text === 'string')?.text;
557
- const prefix =
558
- typeof text === 'string'
559
- ? /^(FEATURE_DISABLED|TOOL_UNAVAILABLE|PAID_PLAN_REQUIRED|INVALID_INPUT)(?::|$)/u.exec(
560
- text,
561
- )?.[1]
553
+ /** Server tool error codes the client acts on, mapped to its own codes. */
554
+ const CLIENT_ERROR_CODES = new Map([
555
+ ['FEATURE_DISABLED', 'mcp_feature_disabled'],
556
+ ['TOOL_UNAVAILABLE', 'mcp_tool_unavailable'],
557
+ ['PAID_PLAN_REQUIRED', 'mcp_paid_plan_required'],
558
+ ['INVALID_INPUT', 'mcp_invalid_input'],
559
+ ]);
560
+ /** A tool error text longer than this is not parsed as JSON. */
561
+ const MAX_ERROR_TEXT_JSON = 4_096;
562
+
563
+ /** @param {unknown} text @returns {string | undefined} */
564
+ function jsonErrorCode(text) {
565
+ if (typeof text !== 'string' || !text.startsWith('{') || text.length > MAX_ERROR_TEXT_JSON)
566
+ return undefined;
567
+ try {
568
+ const parsed = JSON.parse(text);
569
+ return isObject(parsed) && typeof parsed.error_code === 'string'
570
+ ? parsed.error_code
562
571
  : undefined;
563
- if (prefix === 'FEATURE_DISABLED') return 'mcp_feature_disabled';
564
- if (prefix === 'TOOL_UNAVAILABLE') return 'mcp_tool_unavailable';
565
- if (prefix === 'PAID_PLAN_REQUIRED') return 'mcp_paid_plan_required';
566
- if (prefix === 'INVALID_INPUT') return 'mcp_invalid_input';
567
- return undefined;
572
+ } catch {
573
+ return undefined;
574
+ }
575
+ }
576
+
577
+ /**
578
+ * The client code of a tool error, or undefined so the caller's fallback
579
+ * applies. The context tools put the server code in
580
+ * `structuredContent.error_code` and repeat that object as JSON text; older
581
+ * servers write `CODE: message` text. Only codes in CLIENT_ERROR_CODES map.
582
+ * @param {JsonObject | null} result @returns {string | undefined}
583
+ */
584
+ function structuredErrorCode(result) {
585
+ if (!result || result.isError !== true) return undefined;
586
+ const structured = isObject(result.structuredContent) ? result.structuredContent : null;
587
+ const content = Array.isArray(result.content) ? result.content : [];
588
+ const text = content.find((item) => isObject(item) && typeof item.text === 'string')?.text;
589
+ const serverCode =
590
+ (typeof structured?.error_code === 'string' ? structured.error_code : undefined) ??
591
+ jsonErrorCode(text) ??
592
+ (typeof text === 'string' ? /^([A-Z_]{1,64})(?::|$)/u.exec(text)?.[1] : undefined);
593
+ return serverCode === undefined ? undefined : CLIENT_ERROR_CODES.get(serverCode);
568
594
  }
569
595
 
570
596
  /** @param {string} endpoint @param {string} token @returns {Promise<{ok:true, providerBatches:0, providerModel:null}>} */
package/dist/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@brunobracaioli/aibrain",
3
- "version": "0.4.0-beta.30",
3
+ "version": "0.4.0-beta.32",
4
4
  "type": "module"
5
5
  }
package/dist/policy.mjs CHANGED
@@ -201,6 +201,22 @@ export function codexPolicyJson(policy) {
201
201
  return serialized;
202
202
  }
203
203
 
204
+ /**
205
+ * ASCII-only, any letter case: without the `u` flag a non-ASCII character never
206
+ * matches an ASCII letter, so look-alike characters are refused.
207
+ */
208
+ const DISCLOSURE_ACCEPT_PATTERN = /^accept$/i;
209
+
210
+ /**
211
+ * Whether a typed answer accepts the setup disclosure: the word ACCEPT in any
212
+ * letter case, with only whitespace around it. It stays one explicit word; a
213
+ * generic yes never accepts (spec aibrain-subscriber-beta, setup step 2).
214
+ * @param {string} answer
215
+ */
216
+ export function disclosureAnswerAccepted(answer) {
217
+ return DISCLOSURE_ACCEPT_PATTERN.test(answer.trim());
218
+ }
219
+
204
220
  /** @param {ContextPolicy} policy */
205
221
  export function publicPolicy(policy) {
206
222
  return {