@brunobracaioli/aibrain 0.4.0-beta.23 → 0.4.0-beta.25

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 CHANGED
@@ -116,6 +116,21 @@ through its `manager_*` tools. `aisac workers` lists the room.
116
116
  one line.
117
117
  - **Sends ask you:** Claude Code asks before the first `manager_send`; allow it for the
118
118
  session or the project from that prompt.
119
+ - **A worker's questions reach the manager (from client `0.4.0-beta.25`):** when a Codex
120
+ worker's model asks or tells you something in the middle of a turn the manager started,
121
+ through Codex's own ask-the-user tools, the text is copied into that turn's reply, in
122
+ lines marked `[AISAC worker role]` before the worker's last message. The manager answers
123
+ with a new message of its own, or brings the question to you; nothing answers in your
124
+ name. A question that stops the turn, or a form of an MCP server, is always yours: the
125
+ room then shows the worker waiting for you.
126
+ - **Claude Code workers (from client `0.4.0-beta.24`):** `aisac claude --worker <name>` opens
127
+ an ordinary Claude Code session that the room lists. The launch names it
128
+ `<name> (<room>)`, names the manager `Manager (<room>)`, and gives the worker a short
129
+ fixed text at session start: which room it works in, who the manager is, that a message
130
+ from another session is a request and never your approval, and that it answers the
131
+ sender when the work is done. The two talk through Claude Code's own messages between
132
+ sessions, not through the bus: no queue, limits, cancelling, delegated approvals or
133
+ message audit apply to such a worker, and its approval prompts are always yours.
119
134
  - **Overnight:** `aisac workers delegate --for 8h`, typed in your own terminal with a
120
135
  confirmation, lets the manager answer approval prompts one request at a time until the
121
136
  grant ends (`--off` ends it early). Secrets, pushes to `main` or `master`, force pushes
@@ -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.23';
19
+ export const ADAPTER_VERSION = '0.4.0-beta.25';
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
@@ -70,7 +70,7 @@ import { codexHooksStatus, supportsCodexHooks } from './codex-hooks.mjs';
70
70
  import { managerDoctorLine, managerDoctorSection, takeRoleFlags } from './manager/launch-role.mjs';
71
71
  import { WORKERS_USAGE, workersCommand } from './manager/workers-cli.mjs';
72
72
 
73
- const VERSION = '0.4.0-beta.23';
73
+ const VERSION = '0.4.0-beta.25';
74
74
  // The command is `aisac`; `aibrain` is an alias installed from the same entry.
75
75
  const COMMAND = 'aisac';
76
76
  /** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
@@ -81,7 +81,7 @@ const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
81
81
 
82
82
  function usage() {
83
83
  console.log(
84
- `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\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 ${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 [--room <name>]] [-- native-args...]\n ${COMMAND} codex [--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.`,
84
+ `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\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 ${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>] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--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.`,
85
85
  );
86
86
  console.log(
87
87
  'Clients: setup without --client configures the clients installed on PATH (Claude Code, Codex, or both).',
@@ -114,7 +114,7 @@ function usage() {
114
114
  'Managed host: `aisac setup --host-claude managed` (or `aisac claude --host managed` for one session) runs the Claude Code version the signed manifest pins, installed from the npm registry under the aisac state directory with scripts off; the installer never touches your own `claude`, your `~/.claude` (the managed copy shares your login and settings) or your shell profile. `system` (the default) keeps your binary; AISAC_HOST_MODE=system turns the managed host off for one launch; doctor reports it under `hosts`. After a failed install the launches of the next hour keep your binary without trying again; `aisac claude --host managed` tries at once.',
115
115
  );
116
116
  console.log(
117
- "Manager and workers (licensed accounts): `aisac claude --manager` coordinates the Codex sessions started with `aisac codex --worker <name>` in the same repository (or the same `--room <name>`): its manager_* tools send a message to a worker, which runs it as one turn under its own sandbox and approval policy, and read the reply; you can still type in any worker. `aisac workers` lists the room; `aisac workers delegate [<name>...] [--for 8h]`, typed by you on a terminal, lets the manager answer the workers' approval prompts for a limited time, except a fixed reserve that always stays with you; `aisac workers delegate --off` ends it and `aisac workers decisions` shows what was decided. Messages are local files under the aisac state directory, deleted when read; a message becomes part of the other session's conversation, so its text reaches that session's model provider like anything typed there.",
117
+ "Manager and workers (licensed accounts): `aisac claude --manager` coordinates the Codex sessions started with `aisac codex --worker <name>` in the same repository (or the same `--room <name>`): its manager_* tools send a message to a worker, which runs it as one turn under its own sandbox and approval policy, and read the reply; you can still type in any worker. `aisac claude --worker <name>` opens a Claude Code session that the room lists and names: it and the manager talk through Claude Code's own session messaging, so the queue, cancelling and delegated approvals do not apply to it. `aisac workers` lists the room; `aisac workers delegate [<name>...] [--for 8h]`, typed by you on a terminal, lets the manager answer the workers' approval prompts for a limited time, except a fixed reserve that always stays with you; `aisac workers delegate --off` ends it and `aisac workers decisions` shows what was decided. Messages are local files under the aisac state directory, deleted when read; a message becomes part of the other session's conversation, so its text reaches that session's model provider like anything typed there.",
118
118
  );
119
119
  }
120
120
 
@@ -18,6 +18,15 @@ const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/u;
18
18
  // Reasons are displayed, so only a plain identifier is accepted. New server
19
19
  // reasons stay readable by old clients without an allowlist update.
20
20
  const SAFE_REASON = /^[a-z][a-z0-9_]{0,63}$/u;
21
+ // Grant origins (SPEC 31): same plain-identifier rule, so a new origin does not
22
+ // reject the body; only the two known ones are kept and displayed.
23
+ const SAFE_SOURCE = /^[a-z][a-z_]{0,31}$/u;
24
+ const MAX_SOURCES = 4;
25
+ /** @type {ReadonlyMap<string, string>} */
26
+ const SOURCE_LABEL = new Map([
27
+ ['hotmart', 'Hotmart'],
28
+ ['mothership', 'Mothership'],
29
+ ]);
21
30
  /** @type {ReadonlyMap<number, string>} */
22
31
  const UNAVAILABLE_BY_STATUS = new Map([
23
32
  [401, 'unauthorized'],
@@ -32,13 +41,17 @@ const SERVER_ERROR_STATUS = 500;
32
41
  * state: 'active' | 'inactive' | 'unavailable',
33
42
  * reason: string,
34
43
  * validUntil: string | null,
35
- * purchaseUrl: string | null
44
+ * purchaseUrl: string | null,
45
+ * sources: string[]
36
46
  * }} EngineeringLicense
47
+ * `sources` lists the origins of the grants that decided the state, in the
48
+ * server's order, limited to `hotmart` and `mothership`; empty when the server
49
+ * sent none (an older server) or the state is unavailable.
37
50
  */
38
51
 
39
52
  /** @param {string} reason @returns {EngineeringLicense} */
40
53
  export function unavailableLicense(reason) {
41
- return { state: 'unavailable', reason, validUntil: null, purchaseUrl: null };
54
+ return { state: 'unavailable', reason, validUntil: null, purchaseUrl: null, sources: [] };
42
55
  }
43
56
 
44
57
  /** @param {string} endpoint */
@@ -70,6 +83,25 @@ function isValidUntil(value) {
70
83
  );
71
84
  }
72
85
 
86
+ /**
87
+ * The known origins of an optional `sources` field, or null when it is malformed.
88
+ * An absent field is an older server: no origins. Unknown but well-formed
89
+ * origins are dropped so a newer server stays readable.
90
+ * @param {unknown} value
91
+ * @returns {string[] | null}
92
+ */
93
+ function parseSources(value) {
94
+ if (value === undefined) return [];
95
+ if (!Array.isArray(value) || value.length > MAX_SOURCES) return null;
96
+ if (!value.every((entry) => typeof entry === 'string' && SAFE_SOURCE.test(entry))) return null;
97
+ return [...new Set(value.filter((entry) => SOURCE_LABEL.has(entry)))];
98
+ }
99
+
100
+ /** @param {string[]} sources */
101
+ function sourceNames(sources) {
102
+ return sources.map((source) => SOURCE_LABEL.get(source) ?? source).join(' + ');
103
+ }
104
+
73
105
  /**
74
106
  * Validate the 200 body of the license route (OpenAPI `EngineeringLicense`).
75
107
  * Unknown extra fields are ignored; anything malformed rejects the whole body.
@@ -89,11 +121,14 @@ export function parseLicenseBody(text) {
89
121
  if (state !== 'active' && state !== 'inactive') return null;
90
122
  if (typeof reason !== 'string' || !SAFE_REASON.test(reason)) return null;
91
123
  if (!isValidUntil(validUntil) || !isPurchaseUrl(purchaseUrl)) return null;
124
+ const sources = parseSources(body.sources);
125
+ if (sources === null) return null;
92
126
  return {
93
127
  state,
94
128
  reason,
95
129
  validUntil: /** @type {string | null} */ (validUntil),
96
130
  purchaseUrl: /** @type {string} */ (purchaseUrl),
131
+ sources,
97
132
  };
98
133
  }
99
134
 
@@ -185,10 +220,13 @@ export async function checkEngineeringLicense(endpoint, token, options = {}) {
185
220
  export function licenseLine(license) {
186
221
  if (license.state === 'active') {
187
222
  const until = license.validUntil === null ? '' : ` until ${license.validUntil.slice(0, 10)}`;
188
- return `AISAC Engineering: active${until}.`;
223
+ const via = license.sources.length === 0 ? '' : ` (via ${sourceNames(license.sources)})`;
224
+ return `AISAC Engineering: active${until}${via}.`;
225
+ }
226
+ if (license.state === 'inactive') {
227
+ const via = license.sources.length === 0 ? '' : `, via ${sourceNames(license.sources)}`;
228
+ return `AISAC Engineering: inactive (${license.reason}${via}) — ${license.purchaseUrl ?? ''}`.trimEnd();
189
229
  }
190
- if (license.state === 'inactive')
191
- return `AISAC Engineering: inactive (${license.reason}) — ${license.purchaseUrl ?? ''}`.trimEnd();
192
230
  if (license.reason === 'not_offered') return null;
193
231
  return `AISAC Engineering: unavailable (${license.reason}); memory and context are unaffected.`;
194
232
  }
package/dist/launch.mjs CHANGED
@@ -59,6 +59,7 @@ import {
59
59
  } from './manager/launch-role.mjs';
60
60
  import { MANAGER_ROLE_ENV } from './manager/bus.mjs';
61
61
  import { prepareManagerPlugin } from './manager/hooks.mjs';
62
+ import { prepareWorkerPlugin } from './manager/native-worker.mjs';
62
63
  import {
63
64
  CODEX_LAUNCH_ENVELOPE,
64
65
  CODEX_MONITOR_CWD,
@@ -501,6 +502,7 @@ export async function readSessionServers(root, client, environment) {
501
502
  * @property {typeof resolveHostExecutable} [resolveHost] Managed or system host resolution (ADR-0056 R4)
502
503
  * @property {typeof prepareRole} [prepareRole] Manager or worker role registration (ADR-0058)
503
504
  * @property {typeof prepareManagerPlugin} [prepareManagerPlugin] Manager hook nudges plugin writer (ADR-0058)
505
+ * @property {typeof prepareWorkerPlugin} [prepareWorkerPlugin] Claude Code worker start-text plugin writer (ADR-0060)
504
506
  */
505
507
 
506
508
  /**
@@ -524,6 +526,7 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
524
526
  const resolveHost = dependencies.resolveHost ?? resolveHostExecutable;
525
527
  const registerRole = dependencies.prepareRole ?? prepareRole;
526
528
  const writeManagerPlugin = dependencies.prepareManagerPlugin ?? prepareManagerPlugin;
529
+ const writeWorkerPlugin = dependencies.prepareWorkerPlugin ?? prepareWorkerPlugin;
527
530
  const validated = assertConfig(config);
528
531
  const launchArgs = await parseClaudeLaunchArgs(args, process.cwd());
529
532
  assertClaudeArgs(launchArgs.args);
@@ -733,13 +736,15 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
733
736
  : await readServers(root, 'claude', process.env).catch(() => null);
734
737
  for (const line of servers === null ? [] : mcpLaunchLines(servers, 'claude'))
735
738
  process.stderr.write(`${line}\n`);
736
- // The manager role (spec aisac-engineering-manager FR1, FR6-FR8) needs the same
737
- // confirmed license and never blocks the launch; a second manager of the room
738
- // stops it here, before any host starts.
739
+ // A role (spec aisac-engineering-manager FR1, FR6-FR8, FR14) needs the same
740
+ // confirmed license and never blocks the launch; a second manager of the room,
741
+ // a taken worker name or a full room stops it here, before any host starts.
739
742
  /** @type {Awaited<ReturnType<typeof prepareRole>> | null} */
740
743
  let role = null;
741
744
  /** @type {{ pluginRoot: string } | null} */
742
745
  let managerPlugin = null;
746
+ /** @type {{ pluginRoot: string } | null} */
747
+ let workerPlugin = null;
743
748
  if (launchOptions.role != null) {
744
749
  try {
745
750
  role = await registerRole({
@@ -756,7 +761,7 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
756
761
  throw error;
757
762
  }
758
763
  process.stderr.write(`${roleLaunchLine(role, locale)}\n`);
759
- if (role.active) {
764
+ if (role.active && role.kind === 'manager') {
760
765
  managerPlugin = await writeManagerPlugin({
761
766
  directory,
762
767
  packageRoot: validated.packageRoot,
@@ -768,7 +773,21 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
768
773
  requiredAllow.push(rule);
769
774
  }
770
775
  }
776
+ // A Claude Code worker gets its start text and nothing else: no tool, no
777
+ // allow rule, no role variable (FR14).
778
+ if (role.active && role.kind === 'worker')
779
+ workerPlugin = await writeWorkerPlugin({
780
+ directory,
781
+ packageRoot: validated.packageRoot,
782
+ name: role.name,
783
+ tag: role.roomTag,
784
+ locale,
785
+ }).catch(() => null);
771
786
  }
787
+ /** The manager's server and hooks exist for a manager session only. */
788
+ const manager = role !== null && role.active && role.kind === 'manager' ? role : null;
789
+ // The session's name in Claude Code's own session list (FR14).
790
+ const sessionName = role !== null && role.active ? role.peerName : null;
772
791
  /** Undo what this launch registered and wrote, when no host will run. */
773
792
  const abandon = async () => {
774
793
  await closeRole(role);
@@ -783,9 +802,15 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
783
802
  const mcp = {
784
803
  mcpServers: {
785
804
  ...(servers === null ? {} : claudeMcpEntries(servers.ready)),
786
- ...(role !== null && role.active
787
- ? { [MANAGER_SERVER_NAME]: managerMcpEntry(role, validated.packageRoot, process.execPath) }
788
- : {}),
805
+ ...(manager === null
806
+ ? {}
807
+ : {
808
+ [MANAGER_SERVER_NAME]: managerMcpEntry(
809
+ manager,
810
+ validated.packageRoot,
811
+ process.execPath,
812
+ ),
813
+ }),
789
814
  [MCP_ALIAS]: {
790
815
  type: 'http',
791
816
  url: validated.endpoint,
@@ -807,7 +832,7 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
807
832
  : childEnvironment(root);
808
833
  environment.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS = '1';
809
834
  // The manager's hooks and `aisac workers --wait` read the room from here (FR9).
810
- if (role !== null && role.active) environment[MANAGER_ROLE_ENV] = role.environmentValue;
835
+ if (manager !== null) environment[MANAGER_ROLE_ENV] = manager.environmentValue;
811
836
  /** @type {import('node:child_process').ChildProcess} */
812
837
  let child;
813
838
  try {
@@ -825,6 +850,8 @@ export async function launchClaude(config, root, args, dependencies = {}, launch
825
850
  ...(engineering.pluginRoot === null ? [] : ['--plugin-dir', engineering.pluginRoot]),
826
851
  ...(guardrails === null ? [] : ['--plugin-dir', guardrails.pluginRoot]),
827
852
  ...(managerPlugin === null ? [] : ['--plugin-dir', managerPlugin.pluginRoot]),
853
+ ...(workerPlugin === null ? [] : ['--plugin-dir', workerPlugin.pluginRoot]),
854
+ ...(sessionName === null ? [] : ['--name', sessionName]),
828
855
  ...launchArgs.args,
829
856
  ],
830
857
  { cwd: process.cwd(), env: environment, stdio: 'inherit' },
@@ -192,6 +192,7 @@ const MISSING_ERRORS = ['ENOENT', 'ENOTDIR'];
192
192
  * @property {string[]} heldApprovals ids of the approval requests the worker's adapter holds for the manager right now (FR13)
193
193
  * @property {string | null} [launcherStartTime] what identifies the launcher process (`processStartToken`), filled at registration; absent or null: pid only
194
194
  * @property {string | null} [childStartTime] what identifies the role process, filled by `writeSession` when the role process writes its own pid
195
+ * @property {'native'} [channel] a Claude Code worker, reached over the host's own session messaging and never over the bus (FR14); absent for every other session
195
196
  */
196
197
  /**
197
198
  * @typedef {object} RoomDescriptor
@@ -1036,8 +1037,14 @@ const SESSION_KEYS = [
1036
1037
  'approval',
1037
1038
  'heldApprovals',
1038
1039
  ];
1039
- /** Added after the first records were written: a record without them is still valid. */
1040
- const OPTIONAL_SESSION_KEYS = ['launcherStartTime', 'childStartTime'];
1040
+ /**
1041
+ * Added after the first records were written: a record without them is still valid. A
1042
+ * client that does not know one of them does not validate the record, so a session with
1043
+ * a channel of its own is invisible to an older client.
1044
+ */
1045
+ const OPTIONAL_SESSION_KEYS = ['launcherStartTime', 'childStartTime', 'channel'];
1046
+ /** The channel of a Claude Code worker (FR14). */
1047
+ export const NATIVE_CHANNEL = 'native';
1041
1048
  const SESSION_STATES = ['starting', 'idle', 'busy', 'waiting_approval'];
1042
1049
  const APPROVAL_KINDS = ['command', 'fileChange', 'permissions'];
1043
1050
  const UNKNOWN_VALUE = 'unknown';
@@ -1088,6 +1095,10 @@ export function isSessionRecord(value) {
1088
1095
  if (role !== 'manager' && role !== 'worker') return false;
1089
1096
  if (typeof name !== 'string' || !NAME_PATTERN.test(name)) return false;
1090
1097
  if ((role === 'manager') !== (name === MANAGER_NAME)) return false;
1098
+ // A worker on Claude Code is the native channel, and nothing else is (FR14).
1099
+ if (value.channel !== undefined && value.channel !== NATIVE_CHANNEL) return false;
1100
+ if ((role === 'worker' && value.host === 'claude') !== (value.channel === NATIVE_CHANNEL))
1101
+ return false;
1091
1102
  return (
1092
1103
  value.schemaVersion === BUS_SCHEMA_VERSION &&
1093
1104
  typeof value.sessionId === 'string' &&
@@ -1142,6 +1153,23 @@ function normalizeSessionRecord(record) {
1142
1153
  };
1143
1154
  }
1144
1155
 
1156
+ /**
1157
+ * A Claude Code worker: listed by the room, reached over Claude Code's own session
1158
+ * messaging, with no inbox the bus delivers to (FR14).
1159
+ * @param {Pick<SessionRecord, 'role' | 'channel'>} record
1160
+ */
1161
+ export function isNativeWorker(record) {
1162
+ return record.role === 'worker' && record.channel === NATIVE_CHANNEL;
1163
+ }
1164
+
1165
+ /**
1166
+ * A worker the bus delivers to: a Codex session with its adapter (FR2).
1167
+ * @param {Pick<SessionRecord, 'role' | 'channel'>} record
1168
+ */
1169
+ export function isBusWorker(record) {
1170
+ return record.role === 'worker' && record.channel !== NATIVE_CHANNEL;
1171
+ }
1172
+
1145
1173
  /**
1146
1174
  * A session's recipient key: its own id for a worker, `manager` for the manager.
1147
1175
  * @param {Pick<SessionRecord, 'role' | 'sessionId'>} record
@@ -1,8 +1,10 @@
1
1
  // The launcher's part of the manager feature (spec aisac-engineering-manager
2
- // D2, D11, D14, FR1, FR2, FR6, FR8): the `--manager`, `--worker` and `--room`
3
- // flags, the registration of the session, and what the launch hands to the
4
- // role process. A role lasts one launch, never blocks one, and reaches its
5
- // process only through the environment the launcher writes.
2
+ // D2, D11, D14, D17, FR1, FR2, FR6, FR8, FR14): the `--manager`, `--worker` and
3
+ // `--room` flags, the registration of the session, and what the launch hands to
4
+ // the role process. A role lasts one launch, never blocks one, and reaches its
5
+ // process only through the environment the launcher writes. A Claude Code
6
+ // worker has no role process: the launch gives it a name, a start text and a
7
+ // record (FR14).
6
8
 
7
9
  import { readdir } from 'node:fs/promises';
8
10
  import { join } from 'node:path';
@@ -11,6 +13,7 @@ import {
11
13
  MANAGER_NAME,
12
14
  MANAGER_ROLE_ENV,
13
15
  NAME_PATTERN,
16
+ NATIVE_CHANNEL,
14
17
  WORKER_MODULE_ENV,
15
18
  WORKER_ROLE_ENV,
16
19
  audit,
@@ -24,6 +27,7 @@ import {
24
27
  sweepBus,
25
28
  } from './bus.mjs';
26
29
  import { MESSAGE_FILE_PATTERN } from './messages.mjs';
30
+ import { hasNameFlag, managerPeerName, roomTag, workerPeerName } from './native-worker.mjs';
27
31
  import { resolveRoom } from './room.mjs';
28
32
 
29
33
  export const MANAGER_FLAG = '--manager';
@@ -143,6 +147,9 @@ const CODEX_VALUE_OPTIONS = new Set([
143
147
  * @property {RoomPaths} paths
144
148
  * @property {string} sessionId
145
149
  * @property {string} environmentValue the JSON the role process parses
150
+ * @property {boolean} native a Claude Code worker: no role process, the host's own messaging (FR14)
151
+ * @property {string} roomTag what a session name carries of the room's label (FR14)
152
+ * @property {string | null} peerName the session's name in Claude Code's session list; null for a Codex worker
146
153
  */
147
154
  /**
148
155
  * @typedef {object} InactiveRole
@@ -211,10 +218,13 @@ export function takeRoleFlags(args, host) {
211
218
  if (roomName !== null) usageError('room_flag_requires_role');
212
219
  return { request: null, args: rest };
213
220
  }
214
- // v1: the manager is a Claude Code session and a worker is a Codex session (FR1).
215
- if ((role.kind === 'manager') !== (host === 'claude')) usageError('role_unsupported_for_host');
216
- // A worker is the interactive terminal; checked before anything is registered.
217
- if (role.kind === 'worker') {
221
+ // The manager is a Claude Code session (FR1); a worker is a Codex session on the
222
+ // bus or, from MG8, a Claude Code session on the host's own messaging (FR14).
223
+ if (role.kind === 'manager' && host !== 'claude') usageError('role_unsupported_for_host');
224
+ // With a role on Claude Code the session's name is the launcher's (FR14).
225
+ if (host === 'claude' && hasNameFlag(rest)) usageError('role_name_reserved');
226
+ // A Codex worker is the interactive terminal; checked before anything is registered.
227
+ if (role.kind === 'worker' && host === 'codex') {
218
228
  const subcommand = codexSubcommand(rest);
219
229
  if (subcommand !== null && !WORKER_CODEX_SUBCOMMANDS.has(subcommand))
220
230
  usageError('role_unsupported_for_command');
@@ -296,6 +306,7 @@ export async function prepareRole({
296
306
  if (!qualified) return { active: false, kind, reason: 'host_unqualified' };
297
307
  const now = (clock?.now ?? Date.now)();
298
308
  const name = request.role.kind === 'worker' ? request.role.name : MANAGER_NAME;
309
+ const native = kind === 'worker' && host.name === 'claude';
299
310
  try {
300
311
  await sweepBus(root, clock);
301
312
  const room = await resolveRoom({
@@ -317,7 +328,9 @@ export async function prepareRole({
317
328
  startedAt: now,
318
329
  cwd,
319
330
  locale,
320
- state: kind === 'manager' ? 'idle' : 'starting',
331
+ // A Claude Code worker has no role process to report a state: the record is
332
+ // written once, and the room shows no state for it (FR14).
333
+ state: kind === 'manager' || native ? 'idle' : 'starting',
321
334
  stateSince: now,
322
335
  turnOrigin: null,
323
336
  queued: 0,
@@ -325,9 +338,15 @@ export async function prepareRole({
325
338
  approvalPolicy: 'unknown',
326
339
  approval: null,
327
340
  heldApprovals: [],
341
+ ...(native ? { channel: NATIVE_CHANNEL } : {}),
328
342
  };
329
343
  await registerSession(paths, record, clock);
330
344
  await audit(paths, { event: 'registered', sessionId: record.sessionId, kind }, clock);
345
+ const tag = roomTag(room.label);
346
+ /** @type {string | null} */
347
+ let peerName = null;
348
+ if (kind === 'manager') peerName = managerPeerName(tag);
349
+ else if (native) peerName = workerPeerName(name, tag);
331
350
  return {
332
351
  active: true,
333
352
  kind,
@@ -335,6 +354,9 @@ export async function prepareRole({
335
354
  roomLabel: room.label,
336
355
  paths,
337
356
  sessionId: record.sessionId,
357
+ native,
358
+ roomTag: tag,
359
+ peerName,
338
360
  environmentValue: roleEnvironmentValue({
339
361
  role: kind,
340
362
  stateRoot: root,
@@ -376,13 +398,17 @@ export function roleLaunchLine(prepared, locale) {
376
398
  ? `aisac: a sessão inicia sem o papel de ${role} (${prepared.reason}).`
377
399
  : `aisac: the session starts without the ${role} role (${prepared.reason}).`;
378
400
  }
401
+ if (prepared.kind === 'worker' && prepared.native)
402
+ return portuguese
403
+ ? `aisac: worker "${prepared.name}" na sala "${prepared.roomLabel}": esta sessão Claude Code se chama "${prepared.peerName}". As mensagens da sessão gerente chegam pelo canal de mensagens do próprio Claude Code e rodam com as permissões desta sessão. Fila, cancelamento e aprovações delegadas valem só para workers Codex. O texto das mensagens e das respostas passa pelos provedores das duas sessões.`
404
+ : `aisac: worker "${prepared.name}" in room "${prepared.roomLabel}": this Claude Code session is named "${prepared.peerName}". The manager session's messages arrive through Claude Code's own session messaging and run under this session's permissions. The queue, cancelling and delegated approvals are for Codex workers only. The text of messages and replies crosses the providers of both sessions.`;
379
405
  if (prepared.kind === 'worker')
380
406
  return portuguese
381
407
  ? `aisac: worker "${prepared.name}" na sala "${prepared.roomLabel}": as mensagens da sessão gerente rodam nesta sessão, com o sandbox e a política de aprovação dela. O texto das mensagens e das respostas passa pelos provedores das duas sessões.`
382
408
  : `aisac: worker "${prepared.name}" in room "${prepared.roomLabel}": messages from the manager session run in this session, under its own sandbox and approval policy. The text of messages and replies crosses the providers of both sessions.`;
383
409
  return portuguese
384
- ? `aisac: gerente da sala "${prepared.roomLabel}": as ferramentas manager_* alcançam os workers Codex desta sala; enviar uma mensagem pede a sua permissão. O texto das mensagens e das respostas passa pelos provedores das duas sessões.`
385
- : `aisac: manager of room "${prepared.roomLabel}": the manager_* tools reach the Codex workers of this room; sending a message asks for your permission. The text of messages and replies crosses the providers of both sessions.`;
410
+ ? `aisac: gerente da sala "${prepared.roomLabel}": esta sessão se chama "${prepared.peerName}". As ferramentas manager_* alcançam os workers Codex desta sala; enviar uma mensagem pede a sua permissão. Os workers Claude Code aparecem na lista e conversam pelo canal de mensagens do próprio Claude Code. O texto das mensagens e das respostas passa pelos provedores das duas sessões.`
411
+ : `aisac: manager of room "${prepared.roomLabel}": this session is named "${prepared.peerName}". The manager_* tools reach the Codex workers of this room; sending a message asks for your permission. Claude Code workers are on the list and talk through Claude Code's own session messaging. The text of messages and replies crosses the providers of both sessions.`;
386
412
  }
387
413
 
388
414
  /**
@@ -19,6 +19,7 @@ import {
19
19
  ROOM_ID_PATTERN,
20
20
  SESSION_ID_PATTERN,
21
21
  audit,
22
+ isBusWorker,
22
23
  isPendingRecord,
23
24
  isPlainRecord,
24
25
  isPrivateDirectory,
@@ -45,6 +46,12 @@ export const APPROVAL_DECISIONS = Object.freeze(
45
46
  );
46
47
  /** The fixed start of the text a worker receives (FR5). */
47
48
  export const MANAGER_LABEL_PREFIX = '[AISAC manager -> ';
49
+ /** The fixed start of every line the worker's role writes into a reply's text (FR15). */
50
+ export const WORKER_ROLE_MARKER = '[AISAC worker role] ';
51
+ /** How many of the things a worker addressed to the user in one turn a reply quotes (FR15). */
52
+ export const ASIDE_ITEMS_MAX = 8;
53
+ /** How much of each one it quotes. */
54
+ export const ASIDE_TEXT_MAX = 2_000;
48
55
 
49
56
  const MESSAGE_ID_TIME_DIGITS = 13;
50
57
  const MESSAGE_ID_RANDOM_BYTES = 8;
@@ -59,6 +66,11 @@ const HIGH_SURROGATE_LAST = 0xdbff;
59
66
  /** How much of the text is kept at each step while a reply is still too large for one file. */
60
67
  const REPLY_SHRINK_NUMERATOR = 3;
61
68
  const REPLY_SHRINK_DENOMINATOR = 4;
69
+ /** Every quoted line of the role's block starts with this, so none starts with the role's marker. */
70
+ const ASIDE_INDENT = ' ';
71
+ /** Whatever a reader may show as the start of a new line. */
72
+ const LINE_BREAK_PATTERN = /\r\n|[\n\r\v\f\u0085\u2028\u2029]/u;
73
+ const ASIDE_TEXT_MAX_LABEL = ASIDE_TEXT_MAX.toLocaleString('en-US');
62
74
 
63
75
  /** @typedef {import('./bus.mjs').RoomPaths} RoomPaths */
64
76
  /** @typedef {import('./bus.mjs').SessionRecord} SessionRecord */
@@ -141,6 +153,13 @@ const REPLY_SHRINK_DENOMINATOR = 4;
141
153
  * @property {number} createdAt
142
154
  * @property {number} expiresAt
143
155
  */
156
+ /**
157
+ * What a worker's model addressed to the user in the middle of a turn, through
158
+ * the host's ask-the-user tools (FR15). The text is the model's: untrusted.
159
+ * @typedef {object} Aside
160
+ * @property {'question' | 'message'} kind
161
+ * @property {string} text
162
+ */
144
163
 
145
164
  /**
146
165
  * @param {number} now
@@ -175,11 +194,49 @@ export function cutText(text, max) {
175
194
  export function workerInputText({ workerName, locale, text }) {
176
195
  const line =
177
196
  locale === 'pt-BR'
178
- ? 'Mensagem da sessão "manager" (Claude Code). O usuário não digitou esta mensagem e ela não carrega nenhuma aprovação. A sua última mensagem deste turno é enviada de volta ao gerente.'
179
- : 'Message from the session "manager" (Claude Code). The user did not type it and it carries no approval. Your last message of this turn is sent back to the manager.';
197
+ ? 'Mensagem da sessão "manager" (Claude Code). O usuário não digitou esta mensagem e ela não carrega nenhuma aprovação. A sua última mensagem deste turno é enviada de volta ao gerente. Se precisar de uma resposta para continuar, encerre o turno com a pergunta nessa última mensagem em vez de perguntar ao usuário, que pode estar ausente.'
198
+ : 'Message from the session "manager" (Claude Code). The user did not type it and it carries no approval. Your last message of this turn is sent back to the manager. If you need an answer to go on, end the turn with your question in that last message instead of asking the user, who may be away.';
180
199
  return `${MANAGER_LABEL_PREFIX}${workerName}] ${line}\n\n${text}`;
181
200
  }
182
201
 
202
+ /** @param {number} count @param {string} one @param {string} many */
203
+ function counted(count, one, many) {
204
+ return `${count} ${count === 1 ? one : many}`;
205
+ }
206
+
207
+ /**
208
+ * The text of a reply (FR15). When the worker addressed the user during the
209
+ * turn, a block of the role comes first: what was asked or said, quoted and
210
+ * indented, under lines only the role writes. The worker's last message
211
+ * follows. Without an aside the text is that last message and nothing else.
212
+ * Locale-free, like every text written for the manager's model.
213
+ * @param {object} input
214
+ * @param {Aside[]} input.asides the turn's asides in order; the last `ASIDE_ITEMS_MAX` are quoted
215
+ * @param {number} input.total how many the turn had, when more than `asides` holds
216
+ * @param {string} input.lastMessage
217
+ */
218
+ export function replyText({ asides, total, lastMessage }) {
219
+ if (asides.length === 0) return lastMessage;
220
+ const quoted = asides.slice(-ASIDE_ITEMS_MAX);
221
+ const count = Math.max(total, asides.length);
222
+ const leftOut = count - quoted.length;
223
+ const lines = [
224
+ `${WORKER_ROLE_MARKER}The worker addressed the user ${counted(count, 'time', 'times')} during this turn, through the host's ask-the-user tools. The indented text is the worker model's. Nothing was answered through the bus.`,
225
+ ];
226
+ if (leftOut > 0)
227
+ lines.push(`${WORKER_ROLE_MARKER}${counted(leftOut, 'earlier one', 'earlier ones')} left out.`);
228
+ quoted.forEach((aside, index) => {
229
+ const cut = cutText(aside.text, ASIDE_TEXT_MAX);
230
+ const mark = cut.truncated ? ` (cut at ${ASIDE_TEXT_MAX_LABEL} characters)` : '';
231
+ lines.push(`${WORKER_ROLE_MARKER}${leftOut + index + 1}. ${aside.kind}${mark}:`);
232
+ for (const line of cut.text.split(LINE_BREAK_PATTERN)) lines.push(`${ASIDE_INDENT}${line}`);
233
+ });
234
+ if (lastMessage === '')
235
+ return [...lines, `${WORKER_ROLE_MARKER}The turn left no last message.`].join('\n');
236
+ lines.push(`${WORKER_ROLE_MARKER}The worker's last message of this turn follows.`);
237
+ return `${lines.join('\n')}\n\n${lastMessage}`;
238
+ }
239
+
183
240
  /** @param {unknown} value @param {string[]} keys */
184
241
  function hasExactKeys(value, keys) {
185
242
  if (!isPlainRecord(value)) return false;
@@ -442,7 +499,8 @@ export function authorizeForManager(message, context) {
442
499
  : { ok: false, reason: 'sender' };
443
500
  }
444
501
  const worker = context.workers.find((entry) => entry.sessionId === message.sender.sessionId);
445
- return worker !== undefined && worker.role === 'worker' && worker.name === message.sender.name
502
+ // A Claude Code worker has no adapter: an approval request in its name is not its own (FR14).
503
+ return worker !== undefined && isBusWorker(worker) && worker.name === message.sender.name
446
504
  ? { ok: true }
447
505
  : { ok: false, reason: 'sender' };
448
506
  }