@brunobracaioli/aibrain 0.4.0-beta.3 → 0.4.0-beta.31

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.
Files changed (70) hide show
  1. package/README.md +199 -13
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +939 -13
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +34 -5
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +1106 -46
  11. package/dist/codex-compatibility.mjs +67 -5
  12. package/dist/codex-hooks.mjs +411 -0
  13. package/dist/codex-permissions.mjs +242 -51
  14. package/dist/codex-protocol-fingerprint.json +12 -13
  15. package/dist/device-login.mjs +511 -0
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +191 -14
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/engineering.mjs +43 -5
  23. package/dist/extensions-catalog.mjs +393 -0
  24. package/dist/extensions-cli.mjs +524 -0
  25. package/dist/extensions-preferences.mjs +151 -0
  26. package/dist/guardrails/continuity.mjs +239 -0
  27. package/dist/guardrails/format.mjs +111 -0
  28. package/dist/guardrails/guards.mjs +1560 -0
  29. package/dist/guardrails/patch.mjs +33 -0
  30. package/dist/guardrails/run.mjs +286 -0
  31. package/dist/guardrails/shell-words.mjs +206 -0
  32. package/dist/guardrails-plugin.mjs +216 -0
  33. package/dist/launch-banner-art.json +40 -0
  34. package/dist/launch-banner.mjs +533 -0
  35. package/dist/launch-feedback.mjs +346 -0
  36. package/dist/launch.mjs +744 -64
  37. package/dist/managed-host.mjs +1276 -0
  38. package/dist/manager/adapter.mjs +304 -0
  39. package/dist/manager/bus.mjs +2222 -0
  40. package/dist/manager/claude-bus-worker.mjs +1355 -0
  41. package/dist/manager/delegation.mjs +354 -0
  42. package/dist/manager/hooks.mjs +918 -0
  43. package/dist/manager/launch-role.mjs +733 -0
  44. package/dist/manager/mcp-stdio.mjs +463 -0
  45. package/dist/manager/messages.mjs +861 -0
  46. package/dist/manager/native-worker.mjs +338 -0
  47. package/dist/manager/reserve.mjs +2170 -0
  48. package/dist/manager/room.mjs +106 -0
  49. package/dist/manager/send-grant.mjs +147 -0
  50. package/dist/manager/server.mjs +2010 -0
  51. package/dist/manager/status.mjs +119 -0
  52. package/dist/manager/wake-state.mjs +93 -0
  53. package/dist/manager/watch.mjs +87 -0
  54. package/dist/manager/worker.mjs +2977 -0
  55. package/dist/manager/workers-cli.mjs +1880 -0
  56. package/dist/mcp-servers.mjs +192 -0
  57. package/dist/mcp.mjs +10 -2
  58. package/dist/monitor.mjs +179 -2
  59. package/dist/package.json +1 -1
  60. package/dist/platform.mjs +78 -29
  61. package/dist/release-manifest-public-keys.json +10 -0
  62. package/dist/release-manifest.json +334 -0
  63. package/dist/release-manifest.mjs +817 -0
  64. package/dist/release-settings.mjs +335 -0
  65. package/dist/self-update.mjs +1047 -0
  66. package/dist/setup-login-state.mjs +19 -0
  67. package/dist/state.mjs +25 -1
  68. package/dist/token-guide.mjs +201 -0
  69. package/dist/update-actions.mjs +442 -0
  70. package/package.json +2 -2
@@ -60,6 +60,62 @@ const ENGINEERING_SKILLS_ROOT_ENV = 'AISAC_ENGINEERING_SKILLS_ROOT';
60
60
  const ENGINEERING_SKILLS_ACK_TIMEOUT_MS = 2_000;
61
61
  const MAX_ENGINEERING_PATH_LENGTH = 4_096;
62
62
  const MAX_TRACKED_INITIALIZE_REQUESTS = 4;
63
+ // The worker role (ADR-0058): a launch started with `aisac codex --worker` gives
64
+ // this adapter a role and the module that runs it. Without both, nothing below
65
+ // that mentions the role runs. The names match clients/aibrain/src/manager/bus.mjs.
66
+ export const WORKER_ROLE_ENV = 'AISAC_WORKER_ROLE';
67
+ export const WORKER_MODULE_ENV = 'AISAC_WORKER_MODULE';
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';
73
+ // The one request the role may send, and the only fields it may carry: a turn
74
+ // on a thread, with one text input and no override of sandbox, approval policy,
75
+ // model or working directory.
76
+ const WORKER_ROLE_METHOD = 'turn/start';
77
+ const WORKER_TURN_KEYS = new Set(['threadId', 'clientUserMessageId', 'input']);
78
+ const WORKER_INPUT_KEYS = new Set(['type', 'text']);
79
+ // The statuses on which a thread takes a turn of the role. A failed turn leaves
80
+ // the thread in `systemError` and no `idle` follows; a new turn works there
81
+ // (measured on Codex 0.166.0), and without it one provider error would stop
82
+ // every later delivery until a person typed in the terminal.
83
+ const WORKER_TURN_STATUSES = new Set(['idle', 'systemError']);
84
+ // The only answers the role may give to a request it holds.
85
+ const WORKER_ROLE_DECISIONS = new Set(['accept', 'decline']);
86
+ const MAX_WORKER_HELD_REQUESTS = 32;
87
+ // The only server requests the role may hold and answer: the two approvals whose
88
+ // decisions are accept and decline. Every other request goes to the terminal.
89
+ const WORKER_HOLDABLE_METHODS = new Set([
90
+ 'item/commandExecution/requestApproval',
91
+ 'item/fileChange/requestApproval',
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;
102
+ // A role turn the app-server never reports stops counting as starting after this.
103
+ const WORKER_TURN_START_DEADLINE_MS = 30_000;
104
+ // How long the adapter waits for the role's stop() once the held lines are out.
105
+ const WORKER_ROLE_STOP_TIMEOUT_MS = 5_000;
106
+ // Requests of the terminal that start work on a thread. From the write until the
107
+ // answer and the thread's next status event the thread still reads idle, so the
108
+ // adapter starts no compaction there and the role no turn (codex-manager-gate.md).
109
+ const TERMINAL_WORK_METHODS = new Set([
110
+ 'turn/start',
111
+ 'turn/steer',
112
+ 'thread/compact/start',
113
+ 'review/start',
114
+ 'thread/shellCommand',
115
+ ]);
116
+ const MAX_TERMINAL_WORK = 128;
117
+ // A terminal work request whose answer or status event is lost stops counting after this.
118
+ const TERMINAL_WORK_DEADLINE_MS = 30_000;
63
119
  const MAX_RECOVERY_ITEMS = 128;
64
120
  const MAX_RECOVERY_SOURCE_INDEX = 65_536;
65
121
  const MAX_NOTE_BYTES = 128 * 1024;
@@ -276,6 +332,13 @@ function codexChildEnvironment() {
276
332
  const environment = { ...process.env };
277
333
  delete environment.JEV_API_KEY;
278
334
  delete environment.TYPESAFE_API_KEY;
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.
337
+ delete environment[WORKER_ROLE_ENV];
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];
279
342
  return environment;
280
343
  }
281
344
  function isRecord(value) {
@@ -398,6 +461,19 @@ function clientRequestKey(value) {
398
461
  return null;
399
462
  }
400
463
 
464
+ // The head of an answer line: `{"id":<id>,"result"` or `"error"`, optionally after
465
+ // `"jsonrpc":"2.0"`. A string id with escapes is not read.
466
+ const LEADING_RESPONSE_ID =
467
+ /^\s*\{\s*(?:"jsonrpc"\s*:\s*"2\.0"\s*,\s*)?"id"\s*:\s*(?:(0|[1-9][0-9]{0,15})|"([^"\\\u0000-\u001f]{1,128})")\s*,\s*"(?:result|error)"\s*:/u;
468
+ const LEADING_RESPONSE_SCAN_CHARS = 512;
469
+
470
+ /** The request key of an answer line too large to parse, from its first bytes; null otherwise. */
471
+ function leadingResponseKey(text) {
472
+ const match = LEADING_RESPONSE_ID.exec(text.slice(0, LEADING_RESPONSE_SCAN_CHARS));
473
+ if (!match) return null;
474
+ return match[1] === undefined ? clientRequestKey(match[2]) : clientRequestKey(Number(match[1]));
475
+ }
476
+
401
477
  /**
402
478
  * Closed private diagnostic contract consumed by the client sink. It contains
403
479
  * stage/reason enums, pseudonymous session identity, operation/correlation
@@ -1007,6 +1083,128 @@ async function processIdentity(pid) {
1007
1083
  }
1008
1084
  }
1009
1085
 
1086
+ // macOS has flock(2) but no util-linux helper and no /proc (ADR-0049, spec
1087
+ // codex-macos). The guard helper and the owner identity use fixed system paths:
1088
+ // never PATH lookups, never a shell.
1089
+ const DARWIN_CAPTURE_TOOLS = Object.freeze({
1090
+ perl: '/usr/bin/perl',
1091
+ sysctl: '/usr/sbin/sysctl',
1092
+ ps: '/bin/ps',
1093
+ });
1094
+ const DARWIN_FLOCK_ARGS = Object.freeze([
1095
+ '-MFcntl=:flock',
1096
+ '-e',
1097
+ 'open(my $f, "+<&=", 3) or exit 2; exit(flock($f, LOCK_EX | LOCK_NB) ? 0 : 1)',
1098
+ ]);
1099
+ const DARWIN_TOOL_ENV = Object.freeze({ LC_ALL: 'C', TZ: 'UTC', PATH: '/usr/bin:/bin:/usr/sbin' });
1100
+ const DARWIN_TOOL_TIMEOUT_MS = 2_000;
1101
+ const DARWIN_TOOL_MAX_OUTPUT_BYTES = 4096;
1102
+ const DARWIN_START_TIME = /^[\x20-\x7e]{1,64}$/u;
1103
+ const BOOT_SESSION = /^[a-f0-9-]{36}$/iu;
1104
+ const PS_NO_MATCHING_PROCESS = 1;
1105
+
1106
+ /** Platform and tool paths of the capture lock; replaced only by tests. */
1107
+ let captureLockHost = { platform: process.platform, tools: DARWIN_CAPTURE_TOOLS };
1108
+
1109
+ export function __testSetCaptureLockHost(host) {
1110
+ const previous = captureLockHost;
1111
+ captureLockHost = host;
1112
+ return previous;
1113
+ }
1114
+
1115
+ function guardHelperCommand() {
1116
+ return captureLockHost.platform === 'darwin'
1117
+ ? [captureLockHost.tools.perl, [...DARWIN_FLOCK_ARGS]]
1118
+ : ['flock', ['-x', '-n', '3']];
1119
+ }
1120
+
1121
+ /** @returns {Promise<{ code: number | null, stdout: string }>} */
1122
+ function runDarwinTool(command, args) {
1123
+ return new Promise((resolvePromise) => {
1124
+ const child = spawn(command, args, {
1125
+ env: DARWIN_TOOL_ENV,
1126
+ stdio: ['ignore', 'pipe', 'ignore'],
1127
+ });
1128
+ let stdout = '';
1129
+ let settled = false;
1130
+ const finish = (code) => {
1131
+ if (settled) return;
1132
+ settled = true;
1133
+ clearTimeout(timer);
1134
+ resolvePromise({ code, stdout });
1135
+ };
1136
+ const timer = setTimeout(() => {
1137
+ child.kill('SIGKILL');
1138
+ finish(null);
1139
+ }, DARWIN_TOOL_TIMEOUT_MS);
1140
+ child.stdout.setEncoding('utf8');
1141
+ child.stdout.on('data', (chunk) => {
1142
+ stdout += chunk;
1143
+ if (Buffer.byteLength(stdout) > DARWIN_TOOL_MAX_OUTPUT_BYTES) {
1144
+ child.kill('SIGKILL');
1145
+ finish(null);
1146
+ }
1147
+ });
1148
+ child.once('error', () => finish(null));
1149
+ child.once('close', (code) => finish(code));
1150
+ });
1151
+ }
1152
+
1153
+ async function darwinBootSession() {
1154
+ const result = await runDarwinTool(captureLockHost.tools.sysctl, ['-n', 'kern.bootsessionuuid']);
1155
+ const value = result.stdout.trim();
1156
+ return result.code === 0 && BOOT_SESSION.test(value) ? value.toUpperCase() : null;
1157
+ }
1158
+
1159
+ async function darwinProcessIdentity(pid) {
1160
+ if (!Number.isSafeInteger(pid) || pid <= 0) return { status: 'invalid' };
1161
+ const bootSession = await darwinBootSession();
1162
+ if (bootSession === null) return { status: 'unverifiable' };
1163
+ const result = await runDarwinTool(captureLockHost.tools.ps, [
1164
+ '-o',
1165
+ 'lstart=',
1166
+ '-p',
1167
+ String(pid),
1168
+ ]);
1169
+ const startTime = result.stdout.trim();
1170
+ // BSD ps exits 1 with no output when no process matches the pid.
1171
+ if (result.code === PS_NO_MATCHING_PROCESS && startTime === '') return { status: 'dead' };
1172
+ if (result.code !== 0 || !DARWIN_START_TIME.test(startTime)) return { status: 'unverifiable' };
1173
+ return { status: 'live', startTime, bootSession };
1174
+ }
1175
+
1176
+ async function darwinSentinelOwner(value) {
1177
+ if (
1178
+ !isRecord(value) ||
1179
+ !hasOnlyKeys(value, [
1180
+ 'schema',
1181
+ 'backend',
1182
+ 'platform',
1183
+ 'pid',
1184
+ 'startTime',
1185
+ 'bootSession',
1186
+ 'nonce',
1187
+ ]) ||
1188
+ value.schema !== 1 ||
1189
+ value.backend !== 'flock' ||
1190
+ value.platform !== 'darwin' ||
1191
+ !isSafeBoundedInteger(value.pid, 1, 4_000_000_000) ||
1192
+ typeof value.startTime !== 'string' ||
1193
+ !DARWIN_START_TIME.test(value.startTime) ||
1194
+ typeof value.bootSession !== 'string' ||
1195
+ !BOOT_SESSION.test(value.bootSession) ||
1196
+ typeof value.nonce !== 'string' ||
1197
+ !isUuid(value.nonce)
1198
+ )
1199
+ return { status: 'unverifiable' };
1200
+ const observer = await darwinBootSession();
1201
+ if (observer === null) return { status: 'unverifiable' };
1202
+ if (observer !== value.bootSession.toUpperCase()) return { status: 'dead' };
1203
+ const current = await darwinProcessIdentity(value.pid);
1204
+ if (current.status !== 'live') return { status: current.status };
1205
+ return current.startTime === value.startTime ? { status: 'live' } : { status: 'dead' };
1206
+ }
1207
+
1010
1208
  async function captureSentinelOwner(lockPath, fsOps) {
1011
1209
  let info;
1012
1210
  try {
@@ -1025,6 +1223,7 @@ async function captureSentinelOwner(lockPath, fsOps) {
1025
1223
  } catch {
1026
1224
  return { status: 'unverifiable' };
1027
1225
  }
1226
+ if (captureLockHost.platform === 'darwin') return darwinSentinelOwner(value);
1028
1227
  if (
1029
1228
  !isRecord(value) ||
1030
1229
  !hasOnlyKeys(value, [
@@ -1060,10 +1259,23 @@ async function captureSentinelOwner(lockPath, fsOps) {
1060
1259
  return current.startTime === value.startTime ? { status: 'live' } : { status: 'dead' };
1061
1260
  }
1062
1261
 
1063
- async function ensureCaptureSentinel(lockPath, task) {
1262
+ async function ownSentinelRecord() {
1263
+ if (captureLockHost.platform === 'darwin') {
1264
+ const identity = await darwinProcessIdentity(process.pid);
1265
+ if (identity.status !== 'live') throw captureLockError('capture_lock_owner_unverifiable');
1266
+ return {
1267
+ schema: 1,
1268
+ backend: 'flock',
1269
+ platform: 'darwin',
1270
+ pid: process.pid,
1271
+ startTime: identity.startTime,
1272
+ bootSession: identity.bootSession,
1273
+ nonce: randomUUID(),
1274
+ };
1275
+ }
1064
1276
  const identity = await processIdentity(process.pid);
1065
1277
  if (identity.status !== 'live') throw captureLockError('capture_lock_owner_unverifiable');
1066
- const metadata = `${JSON.stringify({
1278
+ return {
1067
1279
  schema: 1,
1068
1280
  backend: 'flock',
1069
1281
  pid: process.pid,
@@ -1071,7 +1283,11 @@ async function ensureCaptureSentinel(lockPath, task) {
1071
1283
  bootId: identity.bootId,
1072
1284
  pidNamespace: identity.pidNamespace,
1073
1285
  nonce: randomUUID(),
1074
- })}\n`;
1286
+ };
1287
+ }
1288
+
1289
+ async function ensureCaptureSentinel(lockPath, task) {
1290
+ const metadata = `${JSON.stringify(await ownSentinelRecord())}\n`;
1075
1291
  while (true) {
1076
1292
  const temporary = `${lockPath}.${process.pid}.${randomUUID()}.tmp`;
1077
1293
  let contention = false;
@@ -1149,7 +1365,8 @@ async function withAdvisoryCaptureLock(directory, task) {
1149
1365
  while (true) {
1150
1366
  let helper;
1151
1367
  try {
1152
- helper = spawn('flock', ['-x', '-n', '3'], {
1368
+ const [command, args] = guardHelperCommand();
1369
+ helper = spawn(command, args, {
1153
1370
  stdio: ['ignore', 'ignore', 'ignore', guardHandle.fd],
1154
1371
  });
1155
1372
  const acquired = await new Promise((resolvePromise, rejectPromise) => {
@@ -2715,6 +2932,9 @@ export function createCodexContextProxy({
2715
2932
  clientVersion = process.env.CODEX_CLIENT_VERSION ?? '0.161.0',
2716
2933
  engineeringSkillsRoot = null,
2717
2934
  engineeringAckTimeoutMs = ENGINEERING_SKILLS_ACK_TIMEOUT_MS,
2935
+ createWorkerRole = null,
2936
+ createManagerRole = null,
2937
+ clientAtLineBoundary = () => true,
2718
2938
  }) {
2719
2939
  const contextPolicy = normalizeContextPolicy(policy);
2720
2940
  const effectiveThreshold = contextPolicy?.compactAtPercent ?? threshold;
@@ -2736,6 +2956,27 @@ export function createCodexContextProxy({
2736
2956
  : 'off';
2737
2957
  const initializeRequestKeys = new Set();
2738
2958
  let engineeringHeld = null;
2959
+ // The worker role, when the launch gave one (ADR-0058); null keeps every path
2960
+ // below exactly as it is without a role.
2961
+ let workerRole = null;
2962
+ let workerRoleStopped = false;
2963
+ let managerRole = null;
2964
+ let managerRoleStopped = false;
2965
+ // Held server requests by key: `{ text, id, threadId }`.
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;
2970
+ // The terminal's current thread: the last one it started, resumed or forked that
2971
+ // is not ephemeral (spec FR4 step 1). Null when the adapter could not read it.
2972
+ let currentThreadId = null;
2973
+ // Terminal work requests in flight by request key: `{ threadId, answered, cancel }`.
2974
+ // Past the bound nothing more is counted and every thread reads busy until it drains.
2975
+ const terminalWork = new Map();
2976
+ let terminalWorkSaturated = false;
2977
+ // Lines of this adapter's that wait for the terminal to finish the frame it is
2978
+ // writing to the app-server: `{ value, ownedId }`, `ownedId` null for an answer.
2979
+ const deferredWrites = [];
2739
2980
  function emitDiagnostic(event) {
2740
2981
  try {
2741
2982
  const phase = typeof event?.phase === 'string' ? event.phase : '';
@@ -2826,7 +3067,11 @@ export function createCodexContextProxy({
2826
3067
  }
2827
3068
  function cleanupRequest(id) {
2828
3069
  if (!id) return;
3070
+ const owned = ownedRequests.get(id);
2829
3071
  ownedRequests.delete(id);
3072
+ // A role turn given up on (oversized answer, failed write) is not starting any more.
3073
+ if (owned?.kind === 'worker' || owned?.kind === 'manager')
3074
+ endWorkerTurnStart(threads.get(owned.threadId));
2830
3075
  const waiter = internalReads.get(id);
2831
3076
  if (waiter) {
2832
3077
  internalReads.delete(id);
@@ -2913,6 +3158,17 @@ export function createCodexContextProxy({
2913
3158
  resumePending: false,
2914
3159
  resumeRetryRequested: false,
2915
3160
  resumeRequests: new Set(),
3161
+ // The worker role wrote a turn/start the app-server has not reported yet:
3162
+ // the thread still reads idle, and no lifecycle of this adapter may start.
3163
+ workerTurnStarting: false,
3164
+ // Cancels the deadline of that start; null when no role turn is starting.
3165
+ workerTurnTimer: null,
3166
+ // Compaction checks in flight, including the ones still loading state.
3167
+ lifecycleChecks: 0,
3168
+ // What the app-server last said the thread's status is, including the
3169
+ // answer to thread/start, which no status event follows. Only the worker
3170
+ // role's gate reads it: `idle` above keeps deciding compaction.
3171
+ reportedStatus: null,
2916
3172
  };
2917
3173
  threads.set(threadId, created);
2918
3174
  return created;
@@ -2934,7 +3190,7 @@ export function createCodexContextProxy({
2934
3190
  ownedRequests.set(id, { kind, threadId });
2935
3191
  if (waiter) internalReads.set(id, waiter);
2936
3192
  try {
2937
- writeJsonLine(child.stdin, { id, method, params });
3193
+ writeAtClientBoundary({ id, method, params }, id);
2938
3194
  } catch (error) {
2939
3195
  cleanupRequest(id);
2940
3196
  throw error;
@@ -3123,7 +3379,14 @@ export function createCodexContextProxy({
3123
3379
  reporter.failed({ operationId, reason: 'native_error' });
3124
3380
  }
3125
3381
  function assertCurrent(threadId, state, pending, revision) {
3126
- if (pending.canceled || state.pending !== pending || !state.idle || state.revision !== revision)
3382
+ if (
3383
+ pending.canceled ||
3384
+ state.pending !== pending ||
3385
+ !state.idle ||
3386
+ state.revision !== revision ||
3387
+ // The terminal started work the app-server has not reported yet.
3388
+ terminalWorkInFlight(threadId)
3389
+ )
3127
3390
  throw new Error('Codex state changed during compaction');
3128
3391
  }
3129
3392
  async function readThreadCapture(
@@ -3569,13 +3832,31 @@ export function createCodexContextProxy({
3569
3832
  if (state.recoveryAttach === attachment) state.recoveryAttach = null;
3570
3833
  }
3571
3834
  }
3835
+ /**
3836
+ * Every lifecycle of this adapter on a thread starts here. The count makes a
3837
+ * check that is still loading state visible to the worker role, which must
3838
+ * not start a turn in that window, and the role hears when the last one ends.
3839
+ */
3572
3840
  async function requestCompaction(threadId, state) {
3841
+ state.lifecycleChecks += 1;
3842
+ try {
3843
+ await compactWhenDue(threadId, state);
3844
+ } finally {
3845
+ state.lifecycleChecks -= 1;
3846
+ notifyWorkerRoleIdle(threadId);
3847
+ }
3848
+ }
3849
+ async function compactWhenDue(threadId, state) {
3573
3850
  if (!state.owned) return;
3574
3851
  if (state.resumePending) {
3575
3852
  state.resumeRetryRequested = true;
3576
3853
  return;
3577
3854
  }
3855
+ // A turn of the worker role, or work of the terminal, is starting: its end
3856
+ // brings the next idle event.
3857
+ if (state.workerTurnStarting || terminalWorkInFlight(threadId)) return;
3578
3858
  if (recoveryEnabled && recoveryDisclosed) await loadRecoveryState(threadId, state);
3859
+ if (state.workerTurnStarting || terminalWorkInFlight(threadId)) return;
3579
3860
  if (
3580
3861
  state.recovery &&
3581
3862
  ['pending_attachment', 'recovery_uncertain'].includes(state.recovery.status)
@@ -4153,6 +4434,16 @@ export function createCodexContextProxy({
4153
4434
  releaseEngineering();
4154
4435
  return false;
4155
4436
  }
4437
+ if (owned.kind === 'worker' || owned.kind === 'manager') {
4438
+ // A role's own turn/start response goes to its adapter, never the TUI.
4439
+ const waiter = internalReads.get(message.id);
4440
+ internalReads.delete(message.id);
4441
+ if ('error' in message) {
4442
+ endWorkerTurnStart(threads.get(owned.threadId));
4443
+ waiter?.reject(rpcFailure(owned.kind, message.error));
4444
+ } else waiter?.resolve(message.result);
4445
+ return false;
4446
+ }
4156
4447
  if (
4157
4448
  owned.kind === 'read' ||
4158
4449
  owned.kind === 'page' ||
@@ -4203,11 +4494,17 @@ export function createCodexContextProxy({
4203
4494
  typeof message.params.threadId === 'string' &&
4204
4495
  isRecord(message.params.status)
4205
4496
  ) {
4497
+ // The status event that follows the answer to a work request of the terminal.
4498
+ settleAnsweredTerminalWork(message.params.threadId);
4206
4499
  const state = threads.get(message.params.threadId);
4207
4500
  if (!state) return true;
4208
4501
  state.status =
4209
4502
  typeof message.params.status.type === 'string' ? message.params.status.type : 'unknown';
4210
4503
  state.idle = state.status === 'idle';
4504
+ state.reportedStatus = state.status;
4505
+ // A busy thread means the app-server took the role's turn/start; an idle may
4506
+ // have been emitted before it read it.
4507
+ if (!state.idle) endWorkerTurnStart(state);
4211
4508
  if (!state.idle) invalidateAttachment(state);
4212
4509
  if (!state.owned) return true;
4213
4510
  if (!state.telemetryConnected) {
@@ -4272,6 +4569,7 @@ export function createCodexContextProxy({
4272
4569
  ) {
4273
4570
  const state = threads.get(message.params.threadId);
4274
4571
  const turnId = message.params.turn.id;
4572
+ endWorkerTurnStart(state);
4275
4573
  if (
4276
4574
  state?.recoveryAttach &&
4277
4575
  typeof turnId === 'string' &&
@@ -4365,6 +4663,9 @@ export function createCodexContextProxy({
4365
4663
  typeof message.params.threadId === 'string'
4366
4664
  ) {
4367
4665
  fail(message.params.threadId, 'thread closed');
4666
+ endWorkerTurnStart(threads.get(message.params.threadId));
4667
+ settleTerminalWorkOf(message.params.threadId);
4668
+ if (currentThreadId === message.params.threadId) currentThreadId = null;
4368
4669
  ownedThreadIds.delete(message.params.threadId);
4369
4670
  threads.delete(message.params.threadId);
4370
4671
  }
@@ -4394,6 +4695,10 @@ export function createCodexContextProxy({
4394
4695
  initializeRequestKeys.add(requestKey);
4395
4696
  return;
4396
4697
  }
4698
+ if (TERMINAL_WORK_METHODS.has(message.method)) {
4699
+ observeTerminalWork(requestKey, message.params);
4700
+ return;
4701
+ }
4397
4702
  if (['thread/start', 'thread/resume', 'thread/fork'].includes(message.method)) {
4398
4703
  const threadId =
4399
4704
  isRecord(message.params) && typeof message.params.threadId === 'string'
@@ -4404,7 +4709,9 @@ export function createCodexContextProxy({
4404
4709
  clientRequestBindings.size >= MAX_CLIENT_REQUEST_BINDINGS
4405
4710
  )
4406
4711
  return;
4407
- clientRequestBindings.set(requestKey, { method: message.method, threadId });
4712
+ // The terminal's task-title threads ask for `ephemeral` (spec S5).
4713
+ const ephemeral = isRecord(message.params) && message.params.ephemeral === true;
4714
+ clientRequestBindings.set(requestKey, { method: message.method, threadId, ephemeral });
4408
4715
  if (message.method === 'thread/resume') {
4409
4716
  if (threadId === null || threadId.length === 0 || threadId.length > 256) {
4410
4717
  clientRequestBindings.delete(requestKey);
@@ -4418,10 +4725,21 @@ export function createCodexContextProxy({
4418
4725
  }
4419
4726
  }
4420
4727
 
4728
+ /** The status a thread/start, resume or fork answer reports for its thread. */
4729
+ function noteReportedStatus(state, thread) {
4730
+ const type = isRecord(thread) && isRecord(thread.status) ? thread.status.type : null;
4731
+ if (state && typeof type === 'string') state.reportedStatus = type;
4732
+ }
4733
+ /** Whether a start, resume or fork answer names a thread the terminal converses on. */
4734
+ function isConversationThread(binding, thread) {
4735
+ return !binding.ephemeral && !(isRecord(thread) && thread.ephemeral === true);
4736
+ }
4421
4737
  function observeClientResponse(message) {
4422
4738
  if (!isRecord(message) || message.id === undefined) return;
4423
4739
  const requestKey = clientRequestKey(message.id);
4424
4740
  if (requestKey === null) return;
4741
+ // An answer, not a server request that reuses the id.
4742
+ if (message.method === undefined) answerTerminalWork(requestKey, message.error === undefined);
4425
4743
  const binding = clientRequestBindings.get(requestKey);
4426
4744
  if (binding) {
4427
4745
  clientRequestBindings.delete(requestKey);
@@ -4436,22 +4754,119 @@ export function createCodexContextProxy({
4436
4754
  typeof responseThreadId === 'string' &&
4437
4755
  responseThreadId === binding.threadId
4438
4756
  ) {
4757
+ if (isConversationThread(binding, message.result.thread))
4758
+ currentThreadId = binding.threadId;
4439
4759
  const claimed = claimOwnedThread(binding.threadId);
4760
+ noteReportedStatus(claimed, message.result.thread);
4440
4761
  if (claimed && !state.resumePending && claimed.idle)
4441
4762
  void requestCompaction(binding.threadId, claimed);
4442
4763
  } else if (!state.owned && state.resumeRequests.size === 0 && state.pending === null) {
4443
4764
  threads.delete(binding.threadId);
4444
4765
  }
4766
+ // Only now: the answer's status is recorded and its compaction check counted.
4767
+ notifyWorkerRoleIdle(binding.threadId);
4445
4768
  } else if (message.error === undefined) {
4446
4769
  const selectedId = message.result?.thread?.id;
4447
4770
  if (typeof selectedId === 'string' && selectedId.length > 0 && selectedId.length <= 256) {
4771
+ if (isConversationThread(binding, message.result.thread)) currentThreadId = selectedId;
4448
4772
  const selected = claimOwnedThread(selectedId);
4449
4773
  if (!selected) return;
4774
+ noteReportedStatus(selected, message.result.thread);
4450
4775
  if (selected.idle) void requestCompaction(selectedId, selected);
4451
4776
  }
4452
4777
  }
4453
4778
  }
4454
4779
  }
4780
+ /**
4781
+ * An answer over the line limit cannot be parsed, but its leading id still
4782
+ * settles the terminal request it answers: a lost resume binding would leave
4783
+ * the thread busy for good. The status stays unknown until the next event.
4784
+ */
4785
+ function settleOversizedAnswer(text) {
4786
+ const requestKey = leadingResponseKey(text);
4787
+ if (requestKey === null) return;
4788
+ answerTerminalWork(requestKey, true);
4789
+ const binding = clientRequestBindings.get(requestKey);
4790
+ if (!binding) return;
4791
+ clientRequestBindings.delete(requestKey);
4792
+ if (binding.method === 'thread/resume' && binding.threadId !== null) {
4793
+ const state = threads.get(binding.threadId);
4794
+ if (state) {
4795
+ state.resumeRequests.delete(requestKey);
4796
+ state.resumePending = state.resumeRequests.size > 0;
4797
+ state.resumeRetryRequested = false;
4798
+ state.reportedStatus = null;
4799
+ }
4800
+ if (!binding.ephemeral) currentThreadId = binding.threadId;
4801
+ } else if (!binding.ephemeral) {
4802
+ // The terminal moved to a thread whose id the adapter could not read.
4803
+ currentThreadId = null;
4804
+ }
4805
+ }
4806
+
4807
+ /** Count a work request of the terminal on its thread (spec FR4 step 1). */
4808
+ function observeTerminalWork(requestKey, params) {
4809
+ const threadId =
4810
+ isRecord(params) && typeof params.threadId === 'string' ? params.threadId : null;
4811
+ if (threadId === null || threadId.length === 0 || threadId.length > 256) return;
4812
+ if (terminalWork.has(requestKey)) return;
4813
+ if (terminalWork.size >= MAX_TERMINAL_WORK) terminalWorkSaturated = true;
4814
+ else {
4815
+ const cancel = scheduleTimeout(
4816
+ () => terminalWorkEnded(requestKey),
4817
+ TERMINAL_WORK_DEADLINE_MS,
4818
+ );
4819
+ terminalWork.set(requestKey, { threadId, answered: false, cancel });
4820
+ }
4821
+ giveUpUnwrittenCompaction(threadId);
4822
+ }
4823
+ /**
4824
+ * A compaction whose thread/compact/start still waits for the terminal's frame
4825
+ * to end would land right after the terminal's work and interrupt it: it gives
4826
+ * up instead, as it does at every check before that write.
4827
+ */
4828
+ function giveUpUnwrittenCompaction(threadId) {
4829
+ const pending = threads.get(threadId)?.pending;
4830
+ if (!pending || pending.compactId === null) return;
4831
+ if (!deferredWrites.some((entry) => entry.ownedId === pending.compactId)) return;
4832
+ fail(threadId, 'Codex state changed during compaction');
4833
+ }
4834
+ function terminalWorkInFlight(threadId) {
4835
+ if (terminalWorkSaturated) return true;
4836
+ for (const work of terminalWork.values()) if (work.threadId === threadId) return true;
4837
+ return false;
4838
+ }
4839
+ function forgetTerminalWork(requestKey) {
4840
+ const work = terminalWork.get(requestKey);
4841
+ if (!work) return null;
4842
+ terminalWork.delete(requestKey);
4843
+ work.cancel();
4844
+ if (terminalWork.size === 0) terminalWorkSaturated = false;
4845
+ return work;
4846
+ }
4847
+ /** The answer came: an error started nothing; a result waits for the status event. */
4848
+ function answerTerminalWork(requestKey, succeeded) {
4849
+ const work = terminalWork.get(requestKey);
4850
+ if (!work) return;
4851
+ if (succeeded) work.answered = true;
4852
+ else terminalWorkEnded(requestKey);
4853
+ }
4854
+ function settleAnsweredTerminalWork(threadId) {
4855
+ for (const [requestKey, work] of [...terminalWork])
4856
+ if (work.threadId === threadId && work.answered) forgetTerminalWork(requestKey);
4857
+ }
4858
+ function settleTerminalWorkOf(threadId) {
4859
+ for (const [requestKey, work] of [...terminalWork])
4860
+ if (work.threadId === threadId) forgetTerminalWork(requestKey);
4861
+ }
4862
+ /** Work that ended without a status event: what it held back may run now. */
4863
+ function terminalWorkEnded(requestKey) {
4864
+ const work = forgetTerminalWork(requestKey);
4865
+ if (work === null || stopped) return;
4866
+ const state = threads.get(work.threadId);
4867
+ if (state?.owned && state.idle) void requestCompaction(work.threadId, state);
4868
+ else notifyWorkerRoleIdle(work.threadId);
4869
+ }
4455
4870
 
4456
4871
  const decoder = new StringDecoder('utf8');
4457
4872
  let inputBuffer = '';
@@ -4522,23 +4937,389 @@ export function createCodexContextProxy({
4522
4937
  if (ownedId !== null) {
4523
4938
  stderr.write('codex-context: oversized internal response rejected\n');
4524
4939
  failOversizedInternal(ownedId, Buffer.byteLength(line, 'utf8') + 1);
4525
- } else forward(`${line}\n`);
4940
+ } else {
4941
+ settleOversizedAnswer(line);
4942
+ forward(`${line}\n`);
4943
+ }
4526
4944
  return;
4527
4945
  }
4528
4946
  let forwardLine = true;
4529
4947
  try {
4530
4948
  const message = JSON.parse(line.endsWith('\r') ? line.slice(0, -1) : line);
4949
+ if (managerRole !== null) trackManagerGateServerMessage(message);
4531
4950
  observeClientResponse(message);
4532
4951
  if (isEngineeringTrigger(message)) {
4533
4952
  holdForEngineering(`${line}\n`);
4534
4953
  return;
4535
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;
4536
4960
  forwardLine = handle(message);
4961
+ if (forwardLine && workerRole !== null)
4962
+ forwardLine = workerRoleObserves(message, `${line}\n`);
4537
4963
  } catch {
4538
4964
  /* preserve malformed external protocol lines */
4539
4965
  }
4540
4966
  if (forwardLine) forward(`${line}\n`);
4541
4967
  };
4968
+ /** A key for a server request id, or null for anything that is not one. */
4969
+ function serverRequestKey(message) {
4970
+ if (!isRecord(message) || typeof message.method !== 'string') return null;
4971
+ return clientRequestKey(message.id);
4972
+ }
4973
+ /** The thread a server message is about, or null. */
4974
+ function messageThreadId(message) {
4975
+ const threadId = isRecord(message.params) ? message.params.threadId : undefined;
4976
+ return typeof threadId === 'string' && threadId.length > 0 && threadId.length <= 256
4977
+ ? threadId
4978
+ : null;
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
+ }
5015
+ /**
5016
+ * A held request the app-server no longer waits for is dropped, never forwarded:
5017
+ * it was resolved (answered elsewhere, or dropped when the turn ended), or its
5018
+ * thread closed. The role sees the same notification right after.
5019
+ */
5020
+ function dropSettledWorkerHeld(message) {
5021
+ if (message.method === 'serverRequest/resolved' && isRecord(message.params)) {
5022
+ const key = clientRequestKey(message.params.requestId);
5023
+ if (key !== null) workerHeldRequests.delete(key);
5024
+ return;
5025
+ }
5026
+ if (message.method !== 'thread/closed' && message.method !== 'thread/deleted') return;
5027
+ const threadId = messageThreadId(message);
5028
+ for (const [key, held] of [...workerHeldRequests])
5029
+ if (held.threadId === threadId) workerHeldRequests.delete(key);
5030
+ }
5031
+ /**
5032
+ * Show the role a line the terminal is about to get. False means the role
5033
+ * holds it. `canHold` tells the role whether the adapter would: only a command
5034
+ * or file-change approval of a thread, not already held, under the bound. When
5035
+ * the adapter would not, the line goes to the terminal whatever the role says.
5036
+ * A role that fails never keeps a line from the terminal.
5037
+ */
5038
+ function workerRoleObserves(message, text) {
5039
+ if (workerRoleStopped) return true;
5040
+ dropSettledWorkerHeld(message);
5041
+ const key = serverRequestKey(message);
5042
+ const threadId = messageThreadId(message);
5043
+ const canHold =
5044
+ key !== null &&
5045
+ threadId !== null &&
5046
+ WORKER_HOLDABLE_METHODS.has(message.method) &&
5047
+ !workerHeldRequests.has(key) &&
5048
+ workerHeldRequests.size < MAX_WORKER_HELD_REQUESTS;
5049
+ let held = false;
5050
+ try {
5051
+ held = workerRole.onServerMessage(message, text, { canHold }) === false;
5052
+ } catch {
5053
+ held = false;
5054
+ }
5055
+ if (!held || !canHold) return true;
5056
+ workerHeldRequests.set(key, { text, id: message.id, threadId });
5057
+ return false;
5058
+ }
5059
+ function notifyManagerRoleIdle(threadId) {
5060
+ if (managerRole === null || stopped || managerRoleStopped || managerThreadBusy(threadId))
5061
+ return;
5062
+ try {
5063
+ managerRole.onAdapterIdle(threadId);
5064
+ } catch {
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
+ }
5076
+ }
5077
+ notifyManagerRoleIdle(threadId);
5078
+ }
5079
+ /** A start, resume or fork of the terminal awaits its answer: the thread may change. */
5080
+ function threadBindingPending(threadId) {
5081
+ for (const binding of clientRequestBindings.values())
5082
+ if (binding.method === 'thread/start' || binding.threadId === threadId) return true;
5083
+ return false;
5084
+ }
5085
+ /**
5086
+ * A turn/start of the role the app-server has not answered. It has no deadline:
5087
+ * an answer that comes late still starts that turn, and a second one written
5088
+ * meanwhile would merge into it.
5089
+ */
5090
+ function workerTurnUnanswered(threadId) {
5091
+ for (const owned of ownedRequests.values())
5092
+ if ((owned.kind === 'worker' || owned.kind === 'manager') && owned.threadId === threadId)
5093
+ return true;
5094
+ return false;
5095
+ }
5096
+ /**
5097
+ * Whether a lifecycle of this adapter, or work of the terminal, runs or is about
5098
+ * to run on the thread.
5099
+ */
5100
+ function workerThreadBusy(threadId) {
5101
+ if (terminalWorkInFlight(threadId) || threadBindingPending(threadId)) return true;
5102
+ if (workerTurnUnanswered(threadId)) return true;
5103
+ const state = threads.get(threadId);
5104
+ if (!state) return false;
5105
+ return (
5106
+ state.pending !== null ||
5107
+ state.resumePending ||
5108
+ state.recoveryAttach !== null ||
5109
+ state.lifecycleChecks > 0
5110
+ );
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
+ }
5117
+ /** A refusal of this adapter's own gate: nothing was written, so it is not the app-server's. */
5118
+ function workerGateRejection(reason) {
5119
+ return Object.assign(new Error(reason), { adapterGate: true });
5120
+ }
5121
+ /** A plain object: no prototype of its own, so no toJSON or inherited fields. */
5122
+ function isPlainRecord(value) {
5123
+ if (!isRecord(value) || Array.isArray(value)) return false;
5124
+ const prototype = Object.getPrototypeOf(value);
5125
+ return prototype === Object.prototype || prototype === null;
5126
+ }
5127
+ /**
5128
+ * One text input and nothing else: the role cannot override how the thread runs.
5129
+ * Each field is read once and the turn written is built from those reads, so
5130
+ * what the app-server gets is exactly what was checked. Null when not allowed.
5131
+ */
5132
+ function workerTurnFrom(params) {
5133
+ if (!isPlainRecord(params) || Object.keys(params).some((key) => !WORKER_TURN_KEYS.has(key)))
5134
+ return null;
5135
+ const { threadId, clientUserMessageId, input } = params;
5136
+ if (typeof threadId !== 'string' || threadId.length === 0 || threadId.length > 256) return null;
5137
+ if (typeof clientUserMessageId !== 'string') return null;
5138
+ if (!Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype) return null;
5139
+ if (input.length !== 1) return null;
5140
+ const item = input[0];
5141
+ if (!isPlainRecord(item) || Object.keys(item).some((key) => !WORKER_INPUT_KEYS.has(key)))
5142
+ return null;
5143
+ const { type, text } = item;
5144
+ if (type !== 'text' || typeof text !== 'string') return null;
5145
+ return { threadId, clientUserMessageId, input: [{ type: 'text', text }] };
5146
+ }
5147
+ /** A role turn is written and not yet reported; it stops counting at the deadline. */
5148
+ function beginWorkerTurnStart(state) {
5149
+ endWorkerTurnStart(state);
5150
+ state.workerTurnStarting = true;
5151
+ state.workerTurnTimer = scheduleTimeout(() => {
5152
+ state.workerTurnTimer = null;
5153
+ state.workerTurnStarting = false;
5154
+ }, WORKER_TURN_START_DEADLINE_MS);
5155
+ }
5156
+ function endWorkerTurnStart(state) {
5157
+ if (!state) return;
5158
+ state.workerTurnStarting = false;
5159
+ const cancel = state.workerTurnTimer;
5160
+ state.workerTurnTimer = null;
5161
+ if (typeof cancel === 'function') cancel();
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
+ }
5195
+ /** A deferred line still worth writing: an answer, or a request not given up on. */
5196
+ function isLiveWrite(entry) {
5197
+ return entry.ownedId === null || ownedRequests.has(entry.ownedId);
5198
+ }
5199
+ /**
5200
+ * Write to the app-server once no terminal frame is half written to it: a line
5201
+ * of the adapter's inside a terminal line corrupts both. `ownedId` names the
5202
+ * adapter request the line carries, so one given up on meanwhile is not sent.
5203
+ */
5204
+ function writeAtClientBoundary(value, ownedId = null) {
5205
+ if (deferredWrites.length === 0 && clientAtLineBoundary()) {
5206
+ writeJsonLine(child.stdin, value);
5207
+ return;
5208
+ }
5209
+ // Requests given up on leave here, so a terminal that never ends its frame
5210
+ // cannot grow the queue past the adapter's own request and hold limits.
5211
+ for (let index = deferredWrites.length - 1; index >= 0; index -= 1)
5212
+ if (!isLiveWrite(deferredWrites[index])) deferredWrites.splice(index, 1);
5213
+ deferredWrites.push({ value, ownedId });
5214
+ }
5215
+ function flushDeferredWrites() {
5216
+ while (!stopped && deferredWrites.length > 0 && clientAtLineBoundary()) {
5217
+ const entry = deferredWrites.shift();
5218
+ if (!isLiveWrite(entry)) continue;
5219
+ try {
5220
+ writeJsonLine(child.stdin, entry.value);
5221
+ } catch {
5222
+ if (entry.ownedId !== null) cleanupRequest(entry.ownedId);
5223
+ }
5224
+ }
5225
+ }
5226
+ // What the worker role may do through this adapter, and nothing more.
5227
+ const workerPort = {
5228
+ request(method, params) {
5229
+ return requestRoleTurn('worker', method, params);
5230
+ },
5231
+ /** True when the answer was written, or waits only for the terminal's frame to end. */
5232
+ respond(requestId, result) {
5233
+ const key = clientRequestKey(requestId);
5234
+ const held = key === null ? undefined : workerHeldRequests.get(key);
5235
+ if (held === undefined || !isPlainRecord(result)) return false;
5236
+ const keys = Object.keys(result);
5237
+ if (keys.length !== 1 || keys[0] !== 'decision') return false;
5238
+ // Read once, from the object's own data property: an accessor gives no value.
5239
+ const decision = Object.getOwnPropertyDescriptor(result, 'decision')?.value;
5240
+ if (!WORKER_ROLE_DECISIONS.has(decision)) return false;
5241
+ workerHeldRequests.delete(key);
5242
+ writeAtClientBoundary({ id: held.id, result: { decision } });
5243
+ return true;
5244
+ },
5245
+ forward(text) {
5246
+ for (const [key, held] of workerHeldRequests) {
5247
+ if (held.text !== text) continue;
5248
+ workerHeldRequests.delete(key);
5249
+ forward(held.text);
5250
+ return;
5251
+ }
5252
+ },
5253
+ threadBusy: workerThreadBusy,
5254
+ clientAtLineBoundary: () => clientAtLineBoundary(),
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
+ };
5266
+ /** Everything the role still holds goes to the terminal, in the order it came. */
5267
+ function releaseWorkerHeld() {
5268
+ const held = [...workerHeldRequests.values()];
5269
+ workerHeldRequests.clear();
5270
+ for (const entry of held) forward(entry.text);
5271
+ }
5272
+ /**
5273
+ * The terminal gets every held request first, so a role that never finishes
5274
+ * stopping keeps none of them; then the role's stop() gets a bounded wait.
5275
+ */
5276
+ async function stopWorkerRole() {
5277
+ if (workerRole === null || workerRoleStopped) return;
5278
+ workerRoleStopped = true;
5279
+ releaseWorkerHeld();
5280
+ let stopping;
5281
+ try {
5282
+ stopping = Promise.resolve(workerRole.stop()).catch(() => undefined);
5283
+ } catch {
5284
+ /* the role's cleanup never keeps the adapter from stopping */
5285
+ return;
5286
+ }
5287
+ let cancel = () => undefined;
5288
+ const bound = new Promise((resolve) => {
5289
+ cancel = scheduleTimeout(resolve, WORKER_ROLE_STOP_TIMEOUT_MS);
5290
+ });
5291
+ try {
5292
+ await Promise.race([stopping, bound]);
5293
+ } finally {
5294
+ cancel();
5295
+ }
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
+ }
5316
+ /** No timer of the adapter's own outlives it. */
5317
+ function cancelAdapterTimers() {
5318
+ for (const work of terminalWork.values()) work.cancel();
5319
+ terminalWork.clear();
5320
+ terminalWorkSaturated = false;
5321
+ for (const state of threads.values()) endWorkerTurnStart(state);
5322
+ }
4542
5323
  function internalRequestId(line) {
4543
5324
  const match =
4544
5325
  /^\s*\{\s*(?:"id"\s*:\s*"(ai-brain-context-[A-Za-z0-9._:-]{1,128})"|"jsonrpc"\s*:\s*"2\.0"\s*,\s*"id"\s*:\s*"(ai-brain-context-[A-Za-z0-9._:-]{1,128})")/u.exec(
@@ -4570,7 +5351,7 @@ export function createCodexContextProxy({
4570
5351
  return;
4571
5352
  }
4572
5353
  cleanupRequest(id);
4573
- if (owned.kind === 'telemetry') return;
5354
+ if (owned.kind === 'telemetry' || owned.kind === 'worker' || owned.kind === 'manager') return;
4574
5355
  const failure = new Error('oversized internal response');
4575
5356
  failure.diagnosticReason = 'capture_size_exceeded';
4576
5357
  failure.responseBytes = responseBytes;
@@ -4611,6 +5392,7 @@ export function createCodexContextProxy({
4611
5392
  discardOversized = true;
4612
5393
  inputBuffer = '';
4613
5394
  } else {
5395
+ settleOversizedAnswer(inputBuffer);
4614
5396
  forward(inputBuffer);
4615
5397
  inputBuffer = '';
4616
5398
  passthrough = true;
@@ -4643,12 +5425,46 @@ export function createCodexContextProxy({
4643
5425
  child.stderr.on('data', () => undefined);
4644
5426
  child.stderr.resume?.();
4645
5427
  }
5428
+ if (typeof createWorkerRole === 'function') {
5429
+ try {
5430
+ workerRole = createWorkerRole(workerPort) ?? null;
5431
+ if (workerRole !== null) void Promise.resolve(workerRole.start()).catch(() => undefined);
5432
+ } catch {
5433
+ workerRole = null;
5434
+ }
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
+ }
4646
5444
  return {
4647
5445
  threads,
4648
5446
  observeClientRequest,
4649
5447
  observeClientResponse,
5448
+ /** Every parsed terminal frame: the adapter's own bookkeeping, then the role's. */
5449
+ observeClientMessage(message) {
5450
+ observeClientRequest(message);
5451
+ if (managerRole !== null) resolveManagerGateClientResponse(message);
5452
+ if (workerRole === null || workerRoleStopped) return;
5453
+ try {
5454
+ workerRole.onClientMessage(message);
5455
+ } catch {
5456
+ /* the role only observes */
5457
+ }
5458
+ },
5459
+ /** The terminal's last chunk reached the app-server: deferred writes may go. */
5460
+ clientChunkWritten() {
5461
+ flushDeferredWrites();
5462
+ },
4650
5463
  async stop() {
4651
5464
  releaseEngineering();
5465
+ await stopWorkerRole();
5466
+ await stopManagerRole();
5467
+ cancelAdapterTimers();
4652
5468
  if (stopped) {
4653
5469
  await Promise.all(
4654
5470
  [...diagnosticSinks.values()].map((sink) =>
@@ -4690,6 +5506,102 @@ export function engineeringSkillsRootFrom(value) {
4690
5506
  return value;
4691
5507
  }
4692
5508
 
5509
+ /**
5510
+ * The launcher's worker module, or null. Only an absolute, normalized path
5511
+ * without control characters that names the client's worker module is loaded.
5512
+ */
5513
+ export function workerModulePathFrom(value) {
5514
+ if (typeof value !== 'string' || value.length === 0) return null;
5515
+ if (value.length > MAX_ENGINEERING_PATH_LENGTH || /[\u0000-\u001f\u007f]/u.test(value))
5516
+ return null;
5517
+ if (!value.startsWith('/') || resolve(value) !== value) return null;
5518
+ return value.endsWith(WORKER_MODULE_SUFFIX) ? value : null;
5519
+ }
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
+
5530
+ /**
5531
+ * How this adapter gets its worker role (ADR-0058), or null: no role in the
5532
+ * environment, no module, or a module that does not load all leave the adapter
5533
+ * exactly as it is without the feature.
5534
+ */
5535
+ export async function workerRoleFactoryFrom(environment) {
5536
+ if (typeof environment[WORKER_ROLE_ENV] !== 'string') return null;
5537
+ const modulePath = workerModulePathFrom(environment[WORKER_MODULE_ENV]);
5538
+ if (modulePath === null) return null;
5539
+ try {
5540
+ const module = await import(pathToFileURL(modulePath).href);
5541
+ if (typeof module.createWorkerRoleFromEnvironment !== 'function') return null;
5542
+ // The role and the Codex home whose config the reserve protects; nothing else.
5543
+ const role = {
5544
+ [WORKER_ROLE_ENV]: environment[WORKER_ROLE_ENV],
5545
+ ...(typeof environment.CODEX_HOME === 'string' ? { CODEX_HOME: environment.CODEX_HOME } : {}),
5546
+ };
5547
+ return (port) => module.createWorkerRoleFromEnvironment(role, port, { cwd: process.cwd() });
5548
+ } catch {
5549
+ return null;
5550
+ }
5551
+ }
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
+
4693
5605
  async function main() {
4694
5606
  if (process.argv.includes('--help')) {
4695
5607
  process.stderr.write(
@@ -4738,6 +5650,13 @@ async function main() {
4738
5650
  diagnosticFactory = null;
4739
5651
  }
4740
5652
  }
5653
+ const clientDecoder = new StringDecoder('utf8');
5654
+ let clientInputBuffer = '';
5655
+ let discardOversizedClientFrame = false;
5656
+ // True from the moment a terminal chunk arrives until the pipe below has
5657
+ // written it: nothing of the adapter's may be written in between.
5658
+ let clientChunkInFlight = false;
5659
+ const roleFactories = await adapterRoleFactoriesFrom(process.env);
4741
5660
  const proxy = createCodexContextProxy({
4742
5661
  child,
4743
5662
  threshold: numberEnv('CODEX_CONTEXT_COMPACT_AT', DEFAULT_THRESHOLD),
@@ -4745,11 +5664,13 @@ async function main() {
4745
5664
  policy,
4746
5665
  createDiagnosticSink: diagnosticFactory,
4747
5666
  engineeringSkillsRoot: engineeringSkillsRootFrom(process.env[ENGINEERING_SKILLS_ROOT_ENV]),
5667
+ createWorkerRole: roleFactories.worker,
5668
+ createManagerRole: roleFactories.manager,
5669
+ clientAtLineBoundary: () =>
5670
+ !clientChunkInFlight && clientInputBuffer.length === 0 && !discardOversizedClientFrame,
4748
5671
  });
4749
- const clientDecoder = new StringDecoder('utf8');
4750
- let clientInputBuffer = '';
4751
- let discardOversizedClientFrame = false;
4752
5672
  process.stdin.on('data', (chunk) => {
5673
+ clientChunkInFlight = true;
4753
5674
  const decoded = clientDecoder.write(chunk);
4754
5675
  if (discardOversizedClientFrame) {
4755
5676
  const newline = decoded.indexOf('\n');
@@ -4765,7 +5686,7 @@ async function main() {
4765
5686
  if (!line) continue;
4766
5687
  if (Buffer.byteLength(line, 'utf8') + 1 > MAX_LINE_BYTES) continue;
4767
5688
  try {
4768
- proxy.observeClientRequest(JSON.parse(line));
5689
+ proxy.observeClientMessage(JSON.parse(line));
4769
5690
  } catch {
4770
5691
  /* Preserve malformed/native frames unchanged; the app-server owns validation. */
4771
5692
  }
@@ -4776,6 +5697,11 @@ async function main() {
4776
5697
  }
4777
5698
  });
4778
5699
  process.stdin.pipe(child.stdin);
5700
+ // Registered after the pipe, so it runs once the chunk is written.
5701
+ process.stdin.on('data', () => {
5702
+ clientChunkInFlight = false;
5703
+ proxy.clientChunkWritten();
5704
+ });
4779
5705
  process.stdin.on('end', () => child.stdin.end());
4780
5706
  child.on('exit', async (code, signal) => {
4781
5707
  await proxy.stop();