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

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
@@ -100,22 +100,32 @@ AISAC Creatives Studio, from client `0.4.0-beta.15`).
100
100
  - **Login:** the host does it (`/mcp` in Claude Code, `aisac mcp login <id>` for Codex)
101
101
  and keeps it in its own store. No token reaches `~/.aibrain` or AISAC.
102
102
 
103
- Manager and workers (licensed accounts, from client `0.4.0-beta.22`): `aisac claude --manager` and
104
- `aisac codex --worker <name>`, opened in the same repository (or with the same
105
- `--room <name>`), let one Claude Code session coordinate up to 16 Codex sessions on this
106
- machine. You talk only to the manager; it sends each worker a task and reads the reply
107
- through its `manager_*` tools. `aisac workers` lists the room.
103
+ Manager and workers (licensed accounts, from client `0.4.0-beta.22`): `aisac claude --manager`
104
+ or `aisac codex --manager` and `aisac codex --worker <name>`, opened in the same repository
105
+ (or with the same `--room <name>`), let one session on either host coordinate up to 16 Codex
106
+ workers on this machine. You talk only to the manager; it sends each worker a task and reads
107
+ the reply through its `manager_*` tools. `aisac workers` lists the room.
108
108
  - **Workers stay terminals:** you watch them, type in them and answer their approval
109
109
  prompts there. A manager message is labelled as not typed by you, carries no approval
110
110
  and never changes a worker's sandbox or approval policy. What you type into a turn the
111
111
  manager started goes back to it with the answer; turns you start yourself do not.
112
112
  - **Hosts:** the worker role needs Codex `0.166.0` or newer and, from client
113
- `0.4.0-beta.23`, is offered on every such Codex `aisac codex` runs; `aisac doctor` shows
114
- it on its `manager` line, with the releases the role was measured with. On an older
115
- Codex, or without an active license, the host starts without the role and says why in
116
- one line.
117
- - **Sends ask you:** Claude Code asks before the first `manager_send`; allow it for the
118
- session or the project from that prompt.
113
+ `0.4.0-beta.23`, is offered on every such Codex `aisac codex` runs. The Codex manager host
114
+ was measured on `0.166.0` and `0.167.1`; `aisac codex --manager` accepts interactive,
115
+ `resume` and `fork`. `aisac doctor` shows both role states and measurements. On an older
116
+ Codex, or without an active license, the host starts without the role and says why in one
117
+ line.
118
+ - **Codex manager sends:** `aisac workers allow-sends [--for 8h]` needs a typed confirmation
119
+ in your own terminal before a Codex manager can send or cancel. It expires after 10 minutes
120
+ to 24 hours, defaults to eight hours, and `aisac workers allow-sends --off` revokes it.
121
+ This grant covers new task sends and cancellations to Codex bus workers only. It does not
122
+ delegate worker approvals, change host permissions or let the manager speak for you.
123
+ - **Claude manager sends:** Claude Code asks before `manager_send` and `manager_cancel`; allow
124
+ them from that host prompt. `manager_decide` remains controlled by the worker's separate
125
+ terminal delegation.
126
+ - **Codex manager wake:** on an idle manager terminal, the adapter injects a fixed client
127
+ notice with counts and worker names only. It contains no reply text; call `manager_wait` to
128
+ read the news. Claude Code workers are listed as unreachable from a Codex manager.
119
129
  - **A worker's questions reach the manager (from client `0.4.0-beta.25`):** when a Codex
120
130
  worker's model asks or tells you something in the middle of a turn the manager started,
121
131
  through Codex's own ask-the-user tools, the text is copied into that turn's reply, in
@@ -130,7 +140,9 @@ through its `manager_*` tools. `aisac workers` lists the room.
130
140
  from another session is a request and never your approval, and that it answers the
131
141
  sender when the work is done. The two talk through Claude Code's own messages between
132
142
  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.
143
+ message audit apply to such a worker, and its approval prompts are always yours. A Claude
144
+ manager reaches this channel; a Codex manager reports `reachable: false` and does not try
145
+ to message it.
134
146
  - **Overnight:** `aisac workers delegate --for 8h`, typed in your own terminal with a
135
147
  confirmation, lets the manager answer approval prompts one request at a time until the
136
148
  grant ends (`--off` ends it early). Secrets, pushes to `main` or `master`, force pushes
@@ -169,6 +181,15 @@ equivalence with a tested native release. Unknown older patches, prereleases
169
181
  and other major/minor families remain rejected. No credentials, conversations,
170
182
  model requests or JEV calls are used by these compatibility probes.
171
183
 
184
+ This candidate supports a qualified private Codex installation as well as managed Claude
185
+ Code. Use `aisac setup --host-codex managed` or `aisac setup --host-claude managed` to keep
186
+ AISAC's executable choice independent of global CLI updates. `--host managed` selects it
187
+ for one launch. Downloads use the signed manifest's exact lock and are checked before
188
+ launch; your global executables remain unchanged. Explicit system mode stays authoritative,
189
+ and ambiguous legacy settings never authorize an automatic download. See
190
+ [managed hosts](../../docs/how-to/aibrain-subscriber-beta.md#managed-hosts) for consent,
191
+ environment overrides, cached/offline behavior and the shared-session-state limitation.
192
+
172
193
  Beta17 refreshes the Codex contract to 0.164.0, including its image-generation
173
194
  record formats. Native launch/resume qualification is separate from a new
174
195
  model/JEV compaction qualification. A later native release that changes the
@@ -66,6 +66,10 @@ const MAX_TRACKED_INITIALIZE_REQUESTS = 4;
66
66
  export const WORKER_ROLE_ENV = 'AISAC_WORKER_ROLE';
67
67
  export const WORKER_MODULE_ENV = 'AISAC_WORKER_MODULE';
68
68
  const WORKER_MODULE_SUFFIX = '/manager/worker.mjs';
69
+ export const MANAGER_ROLE_ENV = 'AISAC_MANAGER_ROLE';
70
+ export const MANAGER_ADAPTER_MODULE_ENV = 'AISAC_MANAGER_ADAPTER_MODULE';
71
+ export const MANAGER_CONFIG_ENV = 'AISAC_CODEX_MANAGER_CONFIG';
72
+ const MANAGER_ADAPTER_MODULE_SUFFIX = '/manager/adapter.mjs';
69
73
  // The one request the role may send, and the only fields it may carry: a turn
70
74
  // on a thread, with one text input and no override of sandbox, approval policy,
71
75
  // model or working directory.
@@ -86,6 +90,15 @@ const WORKER_HOLDABLE_METHODS = new Set([
86
90
  'item/commandExecution/requestApproval',
87
91
  'item/fileChange/requestApproval',
88
92
  ]);
93
+ const MANAGER_GATE_METHODS = new Set([
94
+ ...WORKER_HOLDABLE_METHODS,
95
+ 'item/permissions/requestApproval',
96
+ 'execCommandApproval',
97
+ 'applyPatchApproval',
98
+ 'item/tool/requestUserInput',
99
+ 'mcpServer/elicitation/request',
100
+ ]);
101
+ const MAX_MANAGER_GATE_REQUESTS = 128;
89
102
  // A role turn the app-server never reports stops counting as starting after this.
90
103
  const WORKER_TURN_START_DEADLINE_MS = 30_000;
91
104
  // How long the adapter waits for the role's stop() once the held lines are out.
@@ -319,10 +332,13 @@ function codexChildEnvironment() {
319
332
  const environment = { ...process.env };
320
333
  delete environment.JEV_API_KEY;
321
334
  delete environment.TYPESAFE_API_KEY;
322
- // The role belongs to this adapter alone: the app-server and the commands its
323
- // model runs never see it.
335
+ // Role metadata belongs to this adapter alone: the app-server and the commands
336
+ // its model runs never see either role's environment or adapter config.
324
337
  delete environment[WORKER_ROLE_ENV];
325
338
  delete environment[WORKER_MODULE_ENV];
339
+ delete environment[MANAGER_ROLE_ENV];
340
+ delete environment[MANAGER_ADAPTER_MODULE_ENV];
341
+ delete environment[MANAGER_CONFIG_ENV];
326
342
  return environment;
327
343
  }
328
344
  function isRecord(value) {
@@ -2917,6 +2933,7 @@ export function createCodexContextProxy({
2917
2933
  engineeringSkillsRoot = null,
2918
2934
  engineeringAckTimeoutMs = ENGINEERING_SKILLS_ACK_TIMEOUT_MS,
2919
2935
  createWorkerRole = null,
2936
+ createManagerRole = null,
2920
2937
  clientAtLineBoundary = () => true,
2921
2938
  }) {
2922
2939
  const contextPolicy = normalizeContextPolicy(policy);
@@ -2943,8 +2960,13 @@ export function createCodexContextProxy({
2943
2960
  // below exactly as it is without a role.
2944
2961
  let workerRole = null;
2945
2962
  let workerRoleStopped = false;
2963
+ let managerRole = null;
2964
+ let managerRoleStopped = false;
2946
2965
  // Held server requests by key: `{ text, id, threadId }`.
2947
2966
  const workerHeldRequests = new Map();
2967
+ // Server requests the manager's own terminal must answer before an idle wake.
2968
+ const managerGateRequests = new Map();
2969
+ let managerGateSaturated = false;
2948
2970
  // The terminal's current thread: the last one it started, resumed or forked that
2949
2971
  // is not ephemeral (spec FR4 step 1). Null when the adapter could not read it.
2950
2972
  let currentThreadId = null;
@@ -3048,7 +3070,8 @@ export function createCodexContextProxy({
3048
3070
  const owned = ownedRequests.get(id);
3049
3071
  ownedRequests.delete(id);
3050
3072
  // A role turn given up on (oversized answer, failed write) is not starting any more.
3051
- if (owned?.kind === 'worker') endWorkerTurnStart(threads.get(owned.threadId));
3073
+ if (owned?.kind === 'worker' || owned?.kind === 'manager')
3074
+ endWorkerTurnStart(threads.get(owned.threadId));
3052
3075
  const waiter = internalReads.get(id);
3053
3076
  if (waiter) {
3054
3077
  internalReads.delete(id);
@@ -4411,8 +4434,8 @@ export function createCodexContextProxy({
4411
4434
  releaseEngineering();
4412
4435
  return false;
4413
4436
  }
4414
- if (owned.kind === 'worker') {
4415
- // The role's own request: its answer goes to the role and nowhere else.
4437
+ if (owned.kind === 'worker' || owned.kind === 'manager') {
4438
+ // A role's own turn/start response goes to its adapter, never the TUI.
4416
4439
  const waiter = internalReads.get(message.id);
4417
4440
  internalReads.delete(message.id);
4418
4441
  if ('error' in message) {
@@ -4923,11 +4946,17 @@ export function createCodexContextProxy({
4923
4946
  let forwardLine = true;
4924
4947
  try {
4925
4948
  const message = JSON.parse(line.endsWith('\r') ? line.slice(0, -1) : line);
4949
+ if (managerRole !== null) trackManagerGateServerMessage(message);
4926
4950
  observeClientResponse(message);
4927
4951
  if (isEngineeringTrigger(message)) {
4928
4952
  holdForEngineering(`${line}\n`);
4929
4953
  return;
4930
4954
  }
4955
+ // Codex reports the extra-root change before answering our request. The
4956
+ // terminal has not started its thread yet and would submit a skills-list
4957
+ // operation against no active thread, so suppress only this request's
4958
+ // notification while its acknowledgement is outstanding.
4959
+ if (engineeringHeld !== null && message.method === 'skills/changed') return;
4931
4960
  forwardLine = handle(message);
4932
4961
  if (forwardLine && workerRole !== null)
4933
4962
  forwardLine = workerRoleObserves(message, `${line}\n`);
@@ -4948,6 +4977,41 @@ export function createCodexContextProxy({
4948
4977
  ? threadId
4949
4978
  : null;
4950
4979
  }
4980
+ /** Track server requests only for the idle wake gate; the manager role never sees or answers them. */
4981
+ function trackManagerGateServerMessage(message) {
4982
+ if (!isRecord(message) || typeof message.method !== 'string') return;
4983
+ if (message.method === 'serverRequest/resolved' && isRecord(message.params)) {
4984
+ const key = clientRequestKey(message.params.requestId);
4985
+ if (key !== null) managerGateRequests.delete(key);
4986
+ return;
4987
+ }
4988
+ if (message.method === 'thread/closed' || message.method === 'thread/deleted') {
4989
+ const threadId = messageThreadId(message);
4990
+ for (const [key, current] of [...managerGateRequests])
4991
+ if (current === threadId) managerGateRequests.delete(key);
4992
+ return;
4993
+ }
4994
+ if (!MANAGER_GATE_METHODS.has(message.method)) return;
4995
+ const key = serverRequestKey(message);
4996
+ const threadId = messageThreadId(message);
4997
+ if (key === null || threadId === null) return;
4998
+ if (managerGateRequests.size >= MAX_MANAGER_GATE_REQUESTS) {
4999
+ managerGateSaturated = true;
5000
+ return;
5001
+ }
5002
+ managerGateRequests.set(key, threadId);
5003
+ }
5004
+ /** A user answered one of the manager terminal's approval or input requests. */
5005
+ function resolveManagerGateClientResponse(message) {
5006
+ if (!isRecord(message) || Object.hasOwn(message, 'method')) return;
5007
+ if (!Object.hasOwn(message, 'result') && !Object.hasOwn(message, 'error')) return;
5008
+ const key = clientRequestKey(message.id);
5009
+ if (key === null) return;
5010
+ const threadId = managerGateRequests.get(key);
5011
+ if (threadId === undefined) return;
5012
+ managerGateRequests.delete(key);
5013
+ notifyManagerRoleIdle(threadId);
5014
+ }
4951
5015
  /**
4952
5016
  * A held request the app-server no longer waits for is dropped, never forwarded:
4953
5017
  * it was resolved (answered elsewhere, or dropped when the turn ended), or its
@@ -4992,13 +5056,25 @@ export function createCodexContextProxy({
4992
5056
  workerHeldRequests.set(key, { text, id: message.id, threadId });
4993
5057
  return false;
4994
5058
  }
4995
- function notifyWorkerRoleIdle(threadId) {
4996
- if (workerRole === null || stopped || workerRoleStopped || workerThreadBusy(threadId)) return;
5059
+ function notifyManagerRoleIdle(threadId) {
5060
+ if (managerRole === null || stopped || managerRoleStopped || managerThreadBusy(threadId))
5061
+ return;
4997
5062
  try {
4998
- workerRole.onAdapterIdle(threadId);
5063
+ managerRole.onAdapterIdle(threadId);
4999
5064
  } catch {
5000
- /* the role never affects the adapter's own lifecycle */
5065
+ /* the manager wake never affects the adapter's own lifecycle */
5066
+ }
5067
+ }
5068
+ function notifyWorkerRoleIdle(threadId) {
5069
+ if (stopped) return;
5070
+ if (workerRole !== null && !workerRoleStopped && !workerThreadBusy(threadId)) {
5071
+ try {
5072
+ workerRole.onAdapterIdle(threadId);
5073
+ } catch {
5074
+ /* the role never affects the adapter's own lifecycle */
5075
+ }
5001
5076
  }
5077
+ notifyManagerRoleIdle(threadId);
5002
5078
  }
5003
5079
  /** A start, resume or fork of the terminal awaits its answer: the thread may change. */
5004
5080
  function threadBindingPending(threadId) {
@@ -5013,7 +5089,8 @@ export function createCodexContextProxy({
5013
5089
  */
5014
5090
  function workerTurnUnanswered(threadId) {
5015
5091
  for (const owned of ownedRequests.values())
5016
- if (owned.kind === 'worker' && owned.threadId === threadId) return true;
5092
+ if ((owned.kind === 'worker' || owned.kind === 'manager') && owned.threadId === threadId)
5093
+ return true;
5017
5094
  return false;
5018
5095
  }
5019
5096
  /**
@@ -5032,6 +5109,11 @@ export function createCodexContextProxy({
5032
5109
  state.lifecycleChecks > 0
5033
5110
  );
5034
5111
  }
5112
+ function managerThreadBusy(threadId) {
5113
+ if (managerGateSaturated || workerThreadBusy(threadId)) return true;
5114
+ for (const current of managerGateRequests.values()) if (current === threadId) return true;
5115
+ return false;
5116
+ }
5035
5117
  /** A refusal of this adapter's own gate: nothing was written, so it is not the app-server's. */
5036
5118
  function workerGateRejection(reason) {
5037
5119
  return Object.assign(new Error(reason), { adapterGate: true });
@@ -5078,6 +5160,38 @@ export function createCodexContextProxy({
5078
5160
  state.workerTurnTimer = null;
5079
5161
  if (typeof cancel === 'function') cancel();
5080
5162
  }
5163
+ /** One text-only turn/start through the selected role's independently gated port. */
5164
+ function requestRoleTurn(kind, method, params) {
5165
+ const roleStopped = kind === 'worker' ? workerRoleStopped : managerRoleStopped;
5166
+ if (stopped || roleStopped) return Promise.reject(new Error('adapter stopped'));
5167
+ const turn = method === WORKER_ROLE_METHOD ? workerTurnFrom(params) : null;
5168
+ if (turn === null)
5169
+ return Promise.reject(
5170
+ new Error(kind === 'worker' ? 'worker request not allowed' : 'manager wake not allowed'),
5171
+ );
5172
+ if (turn.threadId !== currentThreadId)
5173
+ return Promise.reject(workerGateRejection('thread not current'));
5174
+ const state = threads.get(turn.threadId);
5175
+ const busy =
5176
+ kind === 'worker' ? workerThreadBusy(turn.threadId) : managerThreadBusy(turn.threadId);
5177
+ if (
5178
+ !state ||
5179
+ !WORKER_TURN_STATUSES.has(state.reportedStatus) ||
5180
+ state.workerTurnStarting ||
5181
+ busy
5182
+ )
5183
+ return Promise.reject(workerGateRejection('thread not idle'));
5184
+ if (!clientAtLineBoundary())
5185
+ return Promise.reject(workerGateRejection('client frame in flight'));
5186
+ const waiter = deferred();
5187
+ try {
5188
+ sendOwned(method, turn, kind, turn.threadId, waiter);
5189
+ } catch (error) {
5190
+ return Promise.reject(error);
5191
+ }
5192
+ beginWorkerTurnStart(state);
5193
+ return waiter.promise;
5194
+ }
5081
5195
  /** A deferred line still worth writing: an answer, or a request not given up on. */
5082
5196
  function isLiveWrite(entry) {
5083
5197
  return entry.ownedId === null || ownedRequests.has(entry.ownedId);
@@ -5112,32 +5226,7 @@ export function createCodexContextProxy({
5112
5226
  // What the worker role may do through this adapter, and nothing more.
5113
5227
  const workerPort = {
5114
5228
  request(method, params) {
5115
- if (stopped || workerRoleStopped) return Promise.reject(new Error('adapter stopped'));
5116
- const turn = method === WORKER_ROLE_METHOD ? workerTurnFrom(params) : null;
5117
- if (turn === null) return Promise.reject(new Error('worker request not allowed'));
5118
- // The role converses only on the terminal's current thread (spec FR4 step 1).
5119
- if (turn.threadId !== currentThreadId)
5120
- return Promise.reject(workerGateRejection('thread not current'));
5121
- // The app-server does not protect a busy thread, so the checks are repeated
5122
- // here, at the moment of the write.
5123
- const state = threads.get(turn.threadId);
5124
- if (
5125
- !state ||
5126
- !WORKER_TURN_STATUSES.has(state.reportedStatus) ||
5127
- state.workerTurnStarting ||
5128
- workerThreadBusy(turn.threadId)
5129
- )
5130
- return Promise.reject(workerGateRejection('thread not idle'));
5131
- if (!clientAtLineBoundary())
5132
- return Promise.reject(workerGateRejection('client frame in flight'));
5133
- const waiter = deferred();
5134
- try {
5135
- sendOwned(method, turn, 'worker', turn.threadId, waiter);
5136
- } catch (error) {
5137
- return Promise.reject(error);
5138
- }
5139
- beginWorkerTurnStart(state);
5140
- return waiter.promise;
5229
+ return requestRoleTurn('worker', method, params);
5141
5230
  },
5142
5231
  /** True when the answer was written, or waits only for the terminal's frame to end. */
5143
5232
  respond(requestId, result) {
@@ -5164,6 +5253,16 @@ export function createCodexContextProxy({
5164
5253
  threadBusy: workerThreadBusy,
5165
5254
  clientAtLineBoundary: () => clientAtLineBoundary(),
5166
5255
  };
5256
+ // The manager can start a content-free wake on its own idle terminal thread.
5257
+ // No approval response or worker inbox API exists on this separate port.
5258
+ const managerPort = {
5259
+ request(method, params) {
5260
+ return requestRoleTurn('manager', method, params);
5261
+ },
5262
+ threadBusy: managerThreadBusy,
5263
+ currentThreadId: () => currentThreadId,
5264
+ clientAtLineBoundary: () => clientAtLineBoundary(),
5265
+ };
5167
5266
  /** Everything the role still holds goes to the terminal, in the order it came. */
5168
5267
  function releaseWorkerHeld() {
5169
5268
  const held = [...workerHeldRequests.values()];
@@ -5195,6 +5294,25 @@ export function createCodexContextProxy({
5195
5294
  cancel();
5196
5295
  }
5197
5296
  }
5297
+ async function stopManagerRole() {
5298
+ if (managerRole === null || managerRoleStopped) return;
5299
+ managerRoleStopped = true;
5300
+ let stopping;
5301
+ try {
5302
+ stopping = Promise.resolve(managerRole.stop()).catch(() => undefined);
5303
+ } catch {
5304
+ return;
5305
+ }
5306
+ let cancel = () => undefined;
5307
+ const bound = new Promise((resolve) => {
5308
+ cancel = scheduleTimeout(resolve, WORKER_ROLE_STOP_TIMEOUT_MS);
5309
+ });
5310
+ try {
5311
+ await Promise.race([stopping, bound]);
5312
+ } finally {
5313
+ cancel();
5314
+ }
5315
+ }
5198
5316
  /** No timer of the adapter's own outlives it. */
5199
5317
  function cancelAdapterTimers() {
5200
5318
  for (const work of terminalWork.values()) work.cancel();
@@ -5233,7 +5351,7 @@ export function createCodexContextProxy({
5233
5351
  return;
5234
5352
  }
5235
5353
  cleanupRequest(id);
5236
- if (owned.kind === 'telemetry' || owned.kind === 'worker') return;
5354
+ if (owned.kind === 'telemetry' || owned.kind === 'worker' || owned.kind === 'manager') return;
5237
5355
  const failure = new Error('oversized internal response');
5238
5356
  failure.diagnosticReason = 'capture_size_exceeded';
5239
5357
  failure.responseBytes = responseBytes;
@@ -5315,6 +5433,14 @@ export function createCodexContextProxy({
5315
5433
  workerRole = null;
5316
5434
  }
5317
5435
  }
5436
+ if (workerRole === null && typeof createManagerRole === 'function') {
5437
+ try {
5438
+ managerRole = createManagerRole(managerPort) ?? null;
5439
+ if (managerRole !== null) void Promise.resolve(managerRole.start()).catch(() => undefined);
5440
+ } catch {
5441
+ managerRole = null;
5442
+ }
5443
+ }
5318
5444
  return {
5319
5445
  threads,
5320
5446
  observeClientRequest,
@@ -5322,6 +5448,7 @@ export function createCodexContextProxy({
5322
5448
  /** Every parsed terminal frame: the adapter's own bookkeeping, then the role's. */
5323
5449
  observeClientMessage(message) {
5324
5450
  observeClientRequest(message);
5451
+ if (managerRole !== null) resolveManagerGateClientResponse(message);
5325
5452
  if (workerRole === null || workerRoleStopped) return;
5326
5453
  try {
5327
5454
  workerRole.onClientMessage(message);
@@ -5336,6 +5463,7 @@ export function createCodexContextProxy({
5336
5463
  async stop() {
5337
5464
  releaseEngineering();
5338
5465
  await stopWorkerRole();
5466
+ await stopManagerRole();
5339
5467
  cancelAdapterTimers();
5340
5468
  if (stopped) {
5341
5469
  await Promise.all(
@@ -5390,6 +5518,15 @@ export function workerModulePathFrom(value) {
5390
5518
  return value.endsWith(WORKER_MODULE_SUFFIX) ? value : null;
5391
5519
  }
5392
5520
 
5521
+ /** The launcher's manager adapter module, or null unless it is a normalized package module path. */
5522
+ export function managerAdapterModulePathFrom(value) {
5523
+ if (typeof value !== 'string' || value.length === 0) return null;
5524
+ if (value.length > MAX_ENGINEERING_PATH_LENGTH || /[\u0000-\u001f\u007f]/u.test(value))
5525
+ return null;
5526
+ if (!value.startsWith('/') || resolve(value) !== value) return null;
5527
+ return value.endsWith(MANAGER_ADAPTER_MODULE_SUFFIX) ? value : null;
5528
+ }
5529
+
5393
5530
  /**
5394
5531
  * How this adapter gets its worker role (ADR-0058), or null: no role in the
5395
5532
  * environment, no module, or a module that does not load all leave the adapter
@@ -5413,6 +5550,58 @@ export async function workerRoleFactoryFrom(environment) {
5413
5550
  }
5414
5551
  }
5415
5552
 
5553
+ /** @param {string | undefined} value */
5554
+ function managerConfigIsValid(value) {
5555
+ if (typeof value !== 'string' || value.length === 0 || value.length > 128 * 1024) return false;
5556
+ try {
5557
+ const parsed = JSON.parse(value);
5558
+ return (
5559
+ isRecord(parsed) &&
5560
+ !Array.isArray(parsed) &&
5561
+ Object.keys(parsed).length === 2 &&
5562
+ Object.keys(parsed).every((key) =>
5563
+ ['schemaVersion', 'developerInstructions'].includes(key),
5564
+ ) &&
5565
+ parsed.schemaVersion === 1 &&
5566
+ typeof parsed.developerInstructions === 'string' &&
5567
+ Buffer.byteLength(parsed.developerInstructions, 'utf8') <= 128 * 1024
5568
+ );
5569
+ } catch {
5570
+ return false;
5571
+ }
5572
+ }
5573
+
5574
+ /**
5575
+ * How this adapter gets the manager's idle wake role, or null. Its environment
5576
+ * contains only the launch identity and absolute client module path.
5577
+ */
5578
+ export async function managerRoleFactoryFrom(environment) {
5579
+ if (
5580
+ typeof environment[MANAGER_ROLE_ENV] !== 'string' ||
5581
+ !managerConfigIsValid(environment[MANAGER_CONFIG_ENV])
5582
+ )
5583
+ return null;
5584
+ const modulePath = managerAdapterModulePathFrom(environment[MANAGER_ADAPTER_MODULE_ENV]);
5585
+ if (modulePath === null) return null;
5586
+ try {
5587
+ const module = await import(pathToFileURL(modulePath).href);
5588
+ if (typeof module.createManagerAdapterFromEnvironment !== 'function') return null;
5589
+ const role = { [MANAGER_ROLE_ENV]: environment[MANAGER_ROLE_ENV] };
5590
+ return (port) => module.createManagerAdapterFromEnvironment(role, port, { cwd: process.cwd() });
5591
+ } catch {
5592
+ return null;
5593
+ }
5594
+ }
5595
+
5596
+ /** Exactly one manager or worker role may belong to a launch. */
5597
+ export async function adapterRoleFactoriesFrom(environment) {
5598
+ const workerSet = typeof environment[WORKER_ROLE_ENV] === 'string';
5599
+ const managerSet = typeof environment[MANAGER_ROLE_ENV] === 'string';
5600
+ if (workerSet === managerSet) return { worker: null, manager: null };
5601
+ if (workerSet) return { worker: await workerRoleFactoryFrom(environment), manager: null };
5602
+ return { worker: null, manager: await managerRoleFactoryFrom(environment) };
5603
+ }
5604
+
5416
5605
  async function main() {
5417
5606
  if (process.argv.includes('--help')) {
5418
5607
  process.stderr.write(
@@ -5467,6 +5656,7 @@ async function main() {
5467
5656
  // True from the moment a terminal chunk arrives until the pipe below has
5468
5657
  // written it: nothing of the adapter's may be written in between.
5469
5658
  let clientChunkInFlight = false;
5659
+ const roleFactories = await adapterRoleFactoriesFrom(process.env);
5470
5660
  const proxy = createCodexContextProxy({
5471
5661
  child,
5472
5662
  threshold: numberEnv('CODEX_CONTEXT_COMPACT_AT', DEFAULT_THRESHOLD),
@@ -5474,7 +5664,8 @@ async function main() {
5474
5664
  policy,
5475
5665
  createDiagnosticSink: diagnosticFactory,
5476
5666
  engineeringSkillsRoot: engineeringSkillsRootFrom(process.env[ENGINEERING_SKILLS_ROOT_ENV]),
5477
- createWorkerRole: await workerRoleFactoryFrom(process.env),
5667
+ createWorkerRole: roleFactories.worker,
5668
+ createManagerRole: roleFactories.manager,
5478
5669
  clientAtLineBoundary: () =>
5479
5670
  !clientChunkInFlight && clientInputBuffer.length === 0 && !discardOversizedClientFrame,
5480
5671
  });
@@ -82,7 +82,14 @@ async function main() {
82
82
  // The worker role's variables (ADR-0058) are for the adapter the monitor runs;
83
83
  // the terminal, and every command its model runs, never carries them.
84
84
  const terminalEnv = { ...childEnv };
85
- for (const name of ['AISAC_WORKER_ROLE', 'AISAC_WORKER_MODULE', 'AISAC_MANAGER_ROLE'])
85
+ for (const name of [
86
+ 'AISAC_WORKER_ROLE',
87
+ 'AISAC_WORKER_MODULE',
88
+ 'AISAC_MANAGER_ROLE',
89
+ 'AISAC_MANAGER_ADAPTER_MODULE',
90
+ 'AISAC_CODEX_MANAGER_CONFIG',
91
+ 'AISAC_CODEX_NATIVE_CONFIG_ARGS',
92
+ ])
86
93
  delete terminalEnv[name];
87
94
  const bridgeRoot = await mkdtemp(join(tmpdir(), 'ai-brain-codex-terminal-'));
88
95
  await chmod(bridgeRoot, 0o700);
@@ -199,7 +206,7 @@ async function main() {
199
206
  }
200
207
  };
201
208
 
202
- const spawnMonitor = () => {
209
+ const spawnMonitor = ({ managerAuthority = true } = {}) => {
203
210
  const generation = {
204
211
  child: null,
205
212
  connection: null,
@@ -214,9 +221,20 @@ async function main() {
214
221
  queuedBytes: 0,
215
222
  retirementTimer: null,
216
223
  };
224
+ const monitorEnv = { ...childEnv };
225
+ if (!managerAuthority) {
226
+ // Resume-picker monitors are read-only auxiliary generations. They must
227
+ // never start a manager MCP server or wake adapter for the active room.
228
+ for (const name of [
229
+ 'AISAC_MANAGER_ROLE',
230
+ 'AISAC_MANAGER_ADAPTER_MODULE',
231
+ 'AISAC_CODEX_MANAGER_CONFIG',
232
+ ])
233
+ delete monitorEnv[name];
234
+ }
217
235
  const child = spawn(monitorCommand, [], {
218
236
  cwd: monitorCwd,
219
- env: childEnv,
237
+ env: monitorEnv,
220
238
  stdio: ['pipe', 'pipe', 'pipe'],
221
239
  detached: process.platform !== 'win32',
222
240
  });
@@ -779,11 +797,11 @@ async function main() {
779
797
  }
780
798
  if (connection.isCandidate && connection.generation === null) {
781
799
  handoffAttemptCount += 1;
782
- connection.generation = spawnMonitor();
800
+ connection.generation = spawnMonitor({ managerAuthority: true });
783
801
  connection.generation.connection = connection;
784
802
  }
785
803
  if (connection.isAuxiliary && connection.generation === null) {
786
- connection.generation = spawnMonitor();
804
+ connection.generation = spawnMonitor({ managerAuthority: false });
787
805
  connection.generation.connection = connection;
788
806
  }
789
807
  }
@@ -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.25';
19
+ export const ADAPTER_VERSION = '0.4.0-beta.26';
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']);