@aisac/cli 0.0.0-stage → 0.4.0-beta.2
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 +166 -2
- package/dist/assets/claude/.claude-plugin/plugin.json +147 -0
- package/dist/assets/claude/hooks/context-compaction.ts +6930 -0
- package/dist/assets/claude/hooks/hooks.json +3 -0
- package/dist/assets/claude/hooks/native-host-contract-runtime.ts +18 -0
- package/dist/assets/claude/hooks/native-host-contract.test.ts +51 -0
- package/dist/assets/claude/hooks/provider-window.js +263 -0
- package/dist/assets/claude/hooks/state-fitting.d.mts +47 -0
- package/dist/assets/claude/hooks/state-fitting.mjs +324 -0
- package/dist/assets/codex-context-compaction.mjs +4689 -0
- package/dist/assets/context-selection-fitting.mjs +194 -0
- package/dist/assets/context-state-fitting.mjs +324 -0
- package/dist/assets/context-telemetry-reporter.mjs +305 -0
- package/dist/assets/jev-paid-pilot-terminal.mjs +1066 -0
- package/dist/claude-checkpoint.mjs +1338 -0
- package/dist/claude-compatibility.mjs +506 -0
- package/dist/claude-observation.mjs +1338 -0
- package/dist/cli.mjs +771 -0
- package/dist/codex-compatibility.mjs +481 -0
- package/dist/codex-diagnostics.mjs +447 -0
- package/dist/codex-permissions.mjs +590 -0
- package/dist/codex-protocol-fingerprint.json +131 -0
- package/dist/context-telemetry.mjs +257 -0
- package/dist/engineering-pack-public-key.json +10 -0
- package/dist/engineering-pack.mjs +722 -0
- package/dist/engineering.mjs +194 -0
- package/dist/launch.mjs +690 -0
- package/dist/mcp.mjs +962 -0
- package/dist/monitor.mjs +133 -0
- package/dist/package.json +5 -0
- package/dist/platform.mjs +126 -0
- package/dist/policy.mjs +218 -0
- package/dist/state.mjs +408 -0
- package/dist/telemetry-report.mjs +133 -0
- package/package.json +24 -4
|
@@ -0,0 +1,1066 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { createServer } from 'node:http';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { tmpdir } from 'node:os';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
10
|
+
|
|
11
|
+
const MAX_FRAME_BYTES = 16 * 1024 * 1024;
|
|
12
|
+
const MAX_MONITOR_RESPONSE_BYTES = 64 * 1024 * 1024;
|
|
13
|
+
const MAX_MONITOR_PENDING_BYTES = 32 * 1024 * 1024;
|
|
14
|
+
const MAX_QUEUED_FRAMES = 64;
|
|
15
|
+
const MAX_QUEUED_BYTES = 32 * 1024 * 1024;
|
|
16
|
+
const STARTUP_HANDOFF_GRACE_MS = 5_000;
|
|
17
|
+
const MAX_AUXILIARY_CONNECTIONS = 1;
|
|
18
|
+
const MAX_AUXILIARY_MESSAGES = 64;
|
|
19
|
+
const MAX_AUXILIARY_IN_FLIGHT = 32;
|
|
20
|
+
const MAX_AUXILIARY_NOTIFICATIONS = 256;
|
|
21
|
+
const DEFAULT_AUXILIARY_IDLE_TIMEOUT_MS = 120_000;
|
|
22
|
+
const NORMAL_DISCOVERY_CLOSE_CODES = new Set([1000, 1001, 1005]);
|
|
23
|
+
|
|
24
|
+
function repoRoot() {
|
|
25
|
+
return fileURLToPath(new URL('..', import.meta.url)).replace(/\/$/u, '');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function safeError(error) {
|
|
29
|
+
const message = error instanceof Error ? error.message : '';
|
|
30
|
+
return /^(?:bridge_|monitor_|terminal_|initialize_|socket_|CODEX_|app_server)/u.test(message)
|
|
31
|
+
? message.slice(0, 400)
|
|
32
|
+
: 'terminal_bridge_failed';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function parseInitialize(text) {
|
|
36
|
+
let message;
|
|
37
|
+
try {
|
|
38
|
+
message = JSON.parse(text);
|
|
39
|
+
} catch {
|
|
40
|
+
throw new Error('initialize_invalid_json');
|
|
41
|
+
}
|
|
42
|
+
if (message?.method !== 'initialize') throw new Error('initialize_required_first');
|
|
43
|
+
if (message?.params?.capabilities?.experimentalApi !== true)
|
|
44
|
+
throw new Error('initialize_experimental_api_required');
|
|
45
|
+
if (!(
|
|
46
|
+
(typeof message.id === 'string' && message.id.length > 0 && message.id.length <= 128) ||
|
|
47
|
+
(Number.isSafeInteger(message.id) && message.id >= 0)
|
|
48
|
+
))
|
|
49
|
+
throw new Error('initialize_id_invalid');
|
|
50
|
+
return message;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function closeSocket(socket, statusCode, reason) {
|
|
54
|
+
socket.on('error', () => undefined);
|
|
55
|
+
try {
|
|
56
|
+
socket.write(`HTTP/1.1 ${statusCode} Error\r\nConnection: close\r\n\r\n`);
|
|
57
|
+
} finally {
|
|
58
|
+
socket.destroy(new Error(reason));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function main() {
|
|
63
|
+
const root = repoRoot();
|
|
64
|
+
const monitorCommand =
|
|
65
|
+
process.env.CODEX_MONITOR_COMMAND ?? join(root, 'scripts/jev-paid-pilot-codex.sh');
|
|
66
|
+
const monitorCwd = process.env.CODEX_MONITOR_CWD ?? process.cwd();
|
|
67
|
+
const codexBinary = process.env.CODEX_BIN ?? 'codex';
|
|
68
|
+
const nativeArgs =
|
|
69
|
+
process.argv.slice(2)[0] === '--' ? process.argv.slice(3) : process.argv.slice(2);
|
|
70
|
+
// The bridge owns an interactive Codex TUI transport. Any native command
|
|
71
|
+
// that reaches this bridge may perform a short-lived read-only bootstrap
|
|
72
|
+
// before attaching its conversation transport. The protocol boundary below
|
|
73
|
+
// is the authority: initialize, same-client identity, successful allowlisted
|
|
74
|
+
// discovery, no started operation, one candidate, and a five-second deadline.
|
|
75
|
+
// Non-interactive Codex subcommands never open the socket and exit normally.
|
|
76
|
+
const allowStartupHandoff = true;
|
|
77
|
+
const childEnv = { ...process.env };
|
|
78
|
+
delete childEnv.JEV_API_KEY;
|
|
79
|
+
delete childEnv.TYPESAFE_API_KEY;
|
|
80
|
+
const bridgeRoot = await mkdtemp(join(tmpdir(), 'ai-brain-codex-terminal-'));
|
|
81
|
+
await chmod(bridgeRoot, 0o700);
|
|
82
|
+
const socketPath = join(bridgeRoot, 'codex.sock');
|
|
83
|
+
let terminal = null;
|
|
84
|
+
const generations = new Set();
|
|
85
|
+
let activeConnection = null;
|
|
86
|
+
let pendingCandidate = null;
|
|
87
|
+
const auxiliaryConnections = new Set();
|
|
88
|
+
let handoffCount = 0;
|
|
89
|
+
let handoffAttemptCount = 0;
|
|
90
|
+
let socketUpgradeCount = 0;
|
|
91
|
+
let secondConnectionRejectCount = 0;
|
|
92
|
+
let candidateRejectCount = 0;
|
|
93
|
+
let auxiliaryConnectionCount = 0;
|
|
94
|
+
let auxiliaryRejectCount = 0;
|
|
95
|
+
let auxiliaryMutationRejectCount = 0;
|
|
96
|
+
let auxiliaryUnknownResponseCount = 0;
|
|
97
|
+
let auxiliaryIdleTimeoutCount = 0;
|
|
98
|
+
let auxiliaryMessageCount = 0;
|
|
99
|
+
let auxiliaryNotificationCount = 0;
|
|
100
|
+
let shuttingDown = false;
|
|
101
|
+
const reportPath = process.env.CODEX_TERMINAL_BRIDGE_REPORT;
|
|
102
|
+
let initializeReceived = false;
|
|
103
|
+
let experimentalApi = false;
|
|
104
|
+
let initializeAck = false;
|
|
105
|
+
let initializeResponseSeen = false;
|
|
106
|
+
let initializeErrorCode = null;
|
|
107
|
+
let turnStartCount = 0;
|
|
108
|
+
let threadResumeCount = 0;
|
|
109
|
+
let threadResumeResponseSeen = false;
|
|
110
|
+
let threadResumeErrorCode = null;
|
|
111
|
+
let threadResumeErrorCategory = null;
|
|
112
|
+
let handoffInitializeAck = false;
|
|
113
|
+
const observedMethods = new Set();
|
|
114
|
+
const observedThreadIds = new Set();
|
|
115
|
+
let monitorLineCount = 0;
|
|
116
|
+
let monitorByteCount = 0;
|
|
117
|
+
let monitorExitCode = null;
|
|
118
|
+
let transportAbortReason = null;
|
|
119
|
+
let transportAbortBytes = null;
|
|
120
|
+
let transportAbortMethod = null;
|
|
121
|
+
let maxMonitorFrameBytes = 0;
|
|
122
|
+
let maxMonitorFrameMethod = null;
|
|
123
|
+
let outputPauseCount = 0;
|
|
124
|
+
let terminalExitCode = null;
|
|
125
|
+
let server;
|
|
126
|
+
let webSocketServer;
|
|
127
|
+
let cleanupPromise = null;
|
|
128
|
+
let failureReported = false;
|
|
129
|
+
let startupGraceTimer = null;
|
|
130
|
+
let cleanupInitiator = 'unknown';
|
|
131
|
+
let lastSocketCloseCode = null;
|
|
132
|
+
let terminalAliveAtSocketClose = null;
|
|
133
|
+
let terminalExitSignal = null;
|
|
134
|
+
const lifecycleEvents = [];
|
|
135
|
+
const recordLifecycle = (event) => {
|
|
136
|
+
if (lifecycleEvents.length < 32) lifecycleEvents.push(event);
|
|
137
|
+
};
|
|
138
|
+
const READ_ONLY_DISCOVERY = new Set([
|
|
139
|
+
'account/read',
|
|
140
|
+
'account/bedrock/checkGovCloudRequirements',
|
|
141
|
+
'config/read',
|
|
142
|
+
'configRequirements/read',
|
|
143
|
+
'thread/list',
|
|
144
|
+
'thread/read',
|
|
145
|
+
'model/list',
|
|
146
|
+
'collaborationMode/list',
|
|
147
|
+
'hooks/list',
|
|
148
|
+
'thread/turns/list',
|
|
149
|
+
'thread/items/list',
|
|
150
|
+
'thread/loaded/list',
|
|
151
|
+
'thread/goal/get',
|
|
152
|
+
'skills/list',
|
|
153
|
+
'plugin/list',
|
|
154
|
+
'app/installed',
|
|
155
|
+
]);
|
|
156
|
+
const PRIMARY_DISCOVERY = new Set(['account/read', 'thread/list', 'thread/read']);
|
|
157
|
+
const MAX_PENDING_DISCOVERY = 128;
|
|
158
|
+
const MAX_DIAGNOSTIC_ENTRIES = 128;
|
|
159
|
+
const DIAGNOSTIC_METHODS = new Set([
|
|
160
|
+
'initialize',
|
|
161
|
+
'initialized',
|
|
162
|
+
'account/read',
|
|
163
|
+
'account/bedrock/checkGovCloudRequirements',
|
|
164
|
+
'config/read',
|
|
165
|
+
'thread/list',
|
|
166
|
+
'thread/read',
|
|
167
|
+
'model/list',
|
|
168
|
+
'configRequirements/read',
|
|
169
|
+
'collaborationMode/list',
|
|
170
|
+
'hooks/list',
|
|
171
|
+
'thread/turns/list',
|
|
172
|
+
'thread/items/list',
|
|
173
|
+
'thread/loaded/list',
|
|
174
|
+
'thread/goal/get',
|
|
175
|
+
'skills/list',
|
|
176
|
+
'plugin/list',
|
|
177
|
+
'app/installed',
|
|
178
|
+
'thread/resume',
|
|
179
|
+
'thread/start',
|
|
180
|
+
'thread/fork',
|
|
181
|
+
'turn/start',
|
|
182
|
+
'thread/unsubscribe',
|
|
183
|
+
]);
|
|
184
|
+
let unknownMethodCount = 0;
|
|
185
|
+
const killOwned = (child, signal) => {
|
|
186
|
+
if (!child) return;
|
|
187
|
+
try {
|
|
188
|
+
if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal);
|
|
189
|
+
else child.kill(signal);
|
|
190
|
+
} catch {
|
|
191
|
+
child.kill(signal);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
const spawnMonitor = () => {
|
|
196
|
+
const generation = {
|
|
197
|
+
child: null,
|
|
198
|
+
connection: null,
|
|
199
|
+
retiring: false,
|
|
200
|
+
monitorFrameParts: [],
|
|
201
|
+
monitorFrameBytes: 0,
|
|
202
|
+
monitorPendingChunk: Buffer.alloc(0),
|
|
203
|
+
monitorPaused: false,
|
|
204
|
+
monitorWritable: true,
|
|
205
|
+
pendingToMonitor: [],
|
|
206
|
+
queuedFrames: 0,
|
|
207
|
+
queuedBytes: 0,
|
|
208
|
+
retirementTimer: null,
|
|
209
|
+
};
|
|
210
|
+
const child = spawn(monitorCommand, [], {
|
|
211
|
+
cwd: monitorCwd,
|
|
212
|
+
env: childEnv,
|
|
213
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
214
|
+
detached: process.platform !== 'win32',
|
|
215
|
+
});
|
|
216
|
+
generation.child = child;
|
|
217
|
+
generations.add(generation);
|
|
218
|
+
// Native app-server diagnostics may contain terminal control sequences or
|
|
219
|
+
// private operational text. Keep the monitor outside the user's TTY while
|
|
220
|
+
// preserving protocol frames and child exit/error handling separately.
|
|
221
|
+
child.stderr?.on('data', () => undefined);
|
|
222
|
+
child.stderr?.resume?.();
|
|
223
|
+
const fail = (code = 1) => {
|
|
224
|
+
if (shuttingDown || generation.retiring) return;
|
|
225
|
+
if (generation.connection?.isCandidate) {
|
|
226
|
+
rejectCandidate(generation.connection, 1011, 'candidate_monitor_failed');
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (generation.connection?.isAuxiliary) {
|
|
230
|
+
rejectAuxiliary(generation.connection, 'auxiliary_monitor_failed');
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
monitorExitCode = code;
|
|
234
|
+
void cleanup().finally(() => process.exit(code));
|
|
235
|
+
};
|
|
236
|
+
child.on('error', () => fail(1));
|
|
237
|
+
child.stdin.on('error', () => fail(1));
|
|
238
|
+
child.stdout.on('error', () => fail(1));
|
|
239
|
+
child.stdin.on('drain', () => {
|
|
240
|
+
if (generation.retiring || shuttingDown) return;
|
|
241
|
+
generation.monitorWritable = true;
|
|
242
|
+
flushGeneration(generation);
|
|
243
|
+
});
|
|
244
|
+
child.stdout.on('data', (chunk) => {
|
|
245
|
+
if (generation.retiring || shuttingDown) return;
|
|
246
|
+
const part = Buffer.from(chunk);
|
|
247
|
+
if (generation.monitorPaused) {
|
|
248
|
+
if (generation.monitorPendingChunk.length + part.length > MAX_MONITOR_PENDING_BYTES) {
|
|
249
|
+
abortGeneration(
|
|
250
|
+
generation,
|
|
251
|
+
'monitor_backpressure_limit',
|
|
252
|
+
generation.monitorPendingChunk.length + part.length,
|
|
253
|
+
);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
generation.monitorPendingChunk =
|
|
257
|
+
generation.monitorPendingChunk.length === 0
|
|
258
|
+
? part
|
|
259
|
+
: Buffer.concat([generation.monitorPendingChunk, part]);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
processMonitorChunk(generation, part);
|
|
263
|
+
});
|
|
264
|
+
child.on('exit', (code) => {
|
|
265
|
+
if (generation.retiring || shuttingDown) {
|
|
266
|
+
generation.pendingToMonitor.length = 0;
|
|
267
|
+
generation.monitorFrameParts = [];
|
|
268
|
+
generation.monitorFrameBytes = 0;
|
|
269
|
+
generation.monitorPendingChunk = Buffer.alloc(0);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
fail(code ?? 0);
|
|
273
|
+
});
|
|
274
|
+
return generation;
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
let initialGeneration;
|
|
278
|
+
const resumeMonitor = (generation) => {
|
|
279
|
+
if (!generation.monitorPaused || generation.retiring || shuttingDown) return;
|
|
280
|
+
generation.monitorPaused = false;
|
|
281
|
+
processMonitorBuffer(generation);
|
|
282
|
+
if (!generation.retiring && !shuttingDown && !generation.monitorPaused)
|
|
283
|
+
generation.child.stdout.resume();
|
|
284
|
+
};
|
|
285
|
+
const pauseMonitor = (generation) => {
|
|
286
|
+
if (generation.monitorPaused || generation.retiring || shuttingDown) return;
|
|
287
|
+
generation.monitorPaused = true;
|
|
288
|
+
outputPauseCount += 1;
|
|
289
|
+
generation.child.stdout.pause();
|
|
290
|
+
};
|
|
291
|
+
const processMonitorChunk = (generation, incoming) => {
|
|
292
|
+
if (generation.retiring || shuttingDown) return;
|
|
293
|
+
let offset = 0;
|
|
294
|
+
while (offset < incoming.length && !generation.monitorPaused && !generation.retiring) {
|
|
295
|
+
const newline = incoming.indexOf(10, offset);
|
|
296
|
+
const end = newline < 0 ? incoming.length : newline;
|
|
297
|
+
const part = incoming.subarray(offset, end);
|
|
298
|
+
if (generation.monitorFrameBytes + part.length > MAX_MONITOR_RESPONSE_BYTES) {
|
|
299
|
+
abortGeneration(
|
|
300
|
+
generation,
|
|
301
|
+
'monitor_frame_limit',
|
|
302
|
+
generation.monitorFrameBytes + part.length,
|
|
303
|
+
);
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (part.length > 0) {
|
|
307
|
+
generation.monitorFrameParts.push(part);
|
|
308
|
+
generation.monitorFrameBytes += part.length;
|
|
309
|
+
}
|
|
310
|
+
offset = newline < 0 ? incoming.length : newline + 1;
|
|
311
|
+
if (newline >= 0) {
|
|
312
|
+
const line = Buffer.concat(generation.monitorFrameParts, generation.monitorFrameBytes);
|
|
313
|
+
generation.monitorFrameParts = [];
|
|
314
|
+
generation.monitorFrameBytes = 0;
|
|
315
|
+
handleMonitorLine(generation, line);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (offset < incoming.length) generation.monitorPendingChunk = incoming.subarray(offset);
|
|
319
|
+
};
|
|
320
|
+
const processMonitorBuffer = (generation) => {
|
|
321
|
+
if (generation.retiring || shuttingDown) return;
|
|
322
|
+
if (generation.monitorPendingChunk.length > 0) {
|
|
323
|
+
const pending = generation.monitorPendingChunk;
|
|
324
|
+
generation.monitorPendingChunk = Buffer.alloc(0);
|
|
325
|
+
processMonitorChunk(generation, pending);
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
const flushGeneration = (generation) => {
|
|
329
|
+
while (generation.monitorWritable && generation.pendingToMonitor.length > 0) {
|
|
330
|
+
const frame = generation.pendingToMonitor.shift();
|
|
331
|
+
generation.queuedFrames -= 1;
|
|
332
|
+
generation.queuedBytes -= frame.length;
|
|
333
|
+
generation.monitorWritable = generation.child.stdin.write(`${frame.toString('utf8')}\n`);
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
const enqueueForMonitor = (connection, frame) => {
|
|
338
|
+
const generation = connection.generation;
|
|
339
|
+
if (generation === null || generation.retiring) throw new Error('bridge_monitor_unavailable');
|
|
340
|
+
if (
|
|
341
|
+
frame.length > MAX_FRAME_BYTES ||
|
|
342
|
+
generation.queuedFrames >= MAX_QUEUED_FRAMES ||
|
|
343
|
+
generation.queuedBytes + frame.length > MAX_QUEUED_BYTES
|
|
344
|
+
)
|
|
345
|
+
throw new Error('bridge_queue_limit');
|
|
346
|
+
generation.pendingToMonitor.push(frame);
|
|
347
|
+
generation.queuedFrames += 1;
|
|
348
|
+
generation.queuedBytes += frame.length;
|
|
349
|
+
flushGeneration(generation);
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
const cleanupGeneration = (generation) => {
|
|
353
|
+
if (!generation || generation.retiring) return;
|
|
354
|
+
generation.retiring = true;
|
|
355
|
+
killOwned(generation.child, 'SIGTERM');
|
|
356
|
+
generation.retirementTimer = setTimeout(() => {
|
|
357
|
+
killOwned(generation.child, 'SIGKILL');
|
|
358
|
+
generation.pendingToMonitor.length = 0;
|
|
359
|
+
generation.monitorFrameParts = [];
|
|
360
|
+
generation.monitorFrameBytes = 0;
|
|
361
|
+
generation.monitorPendingChunk = Buffer.alloc(0);
|
|
362
|
+
generations.delete(generation);
|
|
363
|
+
}, 500);
|
|
364
|
+
};
|
|
365
|
+
const abortGeneration = (generation, reason, bytes = null, method = null) => {
|
|
366
|
+
const connection = generation.connection;
|
|
367
|
+
const primaryConnection = connection?.isCandidate !== true && connection?.isAuxiliary !== true;
|
|
368
|
+
if (transportAbortReason === null || primaryConnection) {
|
|
369
|
+
transportAbortReason = reason;
|
|
370
|
+
transportAbortBytes = Number.isSafeInteger(bytes) ? bytes : null;
|
|
371
|
+
transportAbortMethod = typeof method === 'string' ? method : null;
|
|
372
|
+
}
|
|
373
|
+
if (primaryConnection && cleanupInitiator === 'unknown') {
|
|
374
|
+
cleanupInitiator = `transport_${reason}`;
|
|
375
|
+
process.stderr.write(
|
|
376
|
+
`${JSON.stringify({
|
|
377
|
+
event: 'codex_terminal_bridge_error',
|
|
378
|
+
category: reason,
|
|
379
|
+
...(transportAbortBytes === null ? {} : { bytes: transportAbortBytes }),
|
|
380
|
+
...(transportAbortMethod === null ? {} : { method: transportAbortMethod }),
|
|
381
|
+
})}\n`,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
if (connection?.isCandidate) {
|
|
385
|
+
rejectCandidate(connection, 1013, reason);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
if (connection?.isAuxiliary) {
|
|
389
|
+
rejectAuxiliary(connection, reason);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (connection) connection.retiring = true;
|
|
393
|
+
cleanupGeneration(generation);
|
|
394
|
+
connection?.socket.close(1013, reason);
|
|
395
|
+
void cleanup().finally(() => process.exit(1));
|
|
396
|
+
};
|
|
397
|
+
const clearStartupGrace = () => {
|
|
398
|
+
if (startupGraceTimer !== null) clearTimeout(startupGraceTimer);
|
|
399
|
+
startupGraceTimer = null;
|
|
400
|
+
};
|
|
401
|
+
const armStartupGrace = (connection) => {
|
|
402
|
+
if (startupGraceTimer !== null || !allowStartupHandoff || terminal?.exitCode !== null) return;
|
|
403
|
+
recordLifecycle('startup_grace_started');
|
|
404
|
+
startupGraceTimer = setTimeout(() => {
|
|
405
|
+
startupGraceTimer = null;
|
|
406
|
+
if (!shuttingDown && activeConnection === connection && terminal?.exitCode === null) {
|
|
407
|
+
recordLifecycle('startup_handoff_timeout');
|
|
408
|
+
failBridge('startup_handoff_timeout');
|
|
409
|
+
}
|
|
410
|
+
}, STARTUP_HANDOFF_GRACE_MS);
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
const cleanup = () => {
|
|
414
|
+
if (cleanupPromise) return cleanupPromise;
|
|
415
|
+
cleanupPromise = (async () => {
|
|
416
|
+
shuttingDown = true;
|
|
417
|
+
recordLifecycle('cleanup_started');
|
|
418
|
+
clearStartupGrace();
|
|
419
|
+
for (const generation of generations) cleanupGeneration(generation);
|
|
420
|
+
killOwned(terminal, 'SIGTERM');
|
|
421
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
422
|
+
for (const generation of generations) killOwned(generation.child, 'SIGKILL');
|
|
423
|
+
killOwned(terminal, 'SIGKILL');
|
|
424
|
+
await Promise.race([
|
|
425
|
+
Promise.all(
|
|
426
|
+
[terminal, ...[...generations].map((generation) => generation.child)]
|
|
427
|
+
.filter((child) => child?.exitCode === null)
|
|
428
|
+
.map((child) => new Promise((resolve) => child.once('exit', resolve))),
|
|
429
|
+
),
|
|
430
|
+
new Promise((resolve) => setTimeout(resolve, 500)),
|
|
431
|
+
]);
|
|
432
|
+
for (const connection of [activeConnection, pendingCandidate, ...auxiliaryConnections]) {
|
|
433
|
+
if (connection?.socket.readyState === WebSocket.OPEN)
|
|
434
|
+
connection.socket.close(1001, 'bridge stopped');
|
|
435
|
+
connection?.socket.terminate();
|
|
436
|
+
}
|
|
437
|
+
if (server)
|
|
438
|
+
await Promise.race([
|
|
439
|
+
new Promise((resolve) => server.close(() => resolve())),
|
|
440
|
+
new Promise((resolve) => setTimeout(resolve, 1_000)),
|
|
441
|
+
]);
|
|
442
|
+
webSocketServer?.close();
|
|
443
|
+
await rm(socketPath, { force: true }).catch(() => undefined);
|
|
444
|
+
await rm(bridgeRoot, { recursive: true, force: true }).catch(() => undefined);
|
|
445
|
+
if (reportPath !== undefined)
|
|
446
|
+
await writeFile(
|
|
447
|
+
reportPath,
|
|
448
|
+
`${JSON.stringify({
|
|
449
|
+
initialize_received: initializeReceived,
|
|
450
|
+
experimental_api: experimentalApi,
|
|
451
|
+
initialize_ack: initializeAck,
|
|
452
|
+
initialize_response_seen: initializeResponseSeen,
|
|
453
|
+
initialize_error_code: initializeErrorCode,
|
|
454
|
+
turn_start_count: turnStartCount,
|
|
455
|
+
thread_resume_count: threadResumeCount,
|
|
456
|
+
thread_resume_response_seen: threadResumeResponseSeen,
|
|
457
|
+
thread_resume_error_code: threadResumeErrorCode,
|
|
458
|
+
thread_resume_error_category: threadResumeErrorCategory,
|
|
459
|
+
handoff_initialize_ack: handoffInitializeAck,
|
|
460
|
+
observed_methods: [...observedMethods],
|
|
461
|
+
observed_thread_ids: [...observedThreadIds],
|
|
462
|
+
monitor_line_count: monitorLineCount,
|
|
463
|
+
monitor_byte_count: monitorByteCount,
|
|
464
|
+
monitor_exit_code: monitorExitCode,
|
|
465
|
+
transport_abort_reason: transportAbortReason,
|
|
466
|
+
transport_abort_bytes: transportAbortBytes,
|
|
467
|
+
transport_abort_method: transportAbortMethod,
|
|
468
|
+
max_monitor_frame_bytes: maxMonitorFrameBytes,
|
|
469
|
+
max_monitor_frame_method: maxMonitorFrameMethod,
|
|
470
|
+
output_pause_count: outputPauseCount,
|
|
471
|
+
terminal_exit_code: terminalExitCode,
|
|
472
|
+
handoff_count: handoffCount,
|
|
473
|
+
handoff_attempt_count: handoffAttemptCount,
|
|
474
|
+
unknown_method_count: unknownMethodCount,
|
|
475
|
+
socket_upgrade_count: socketUpgradeCount,
|
|
476
|
+
second_connection_reject_count: secondConnectionRejectCount,
|
|
477
|
+
candidate_reject_count: candidateRejectCount,
|
|
478
|
+
auxiliary_connection_count: auxiliaryConnectionCount,
|
|
479
|
+
auxiliary_reject_count: auxiliaryRejectCount,
|
|
480
|
+
auxiliary_mutation_reject_count: auxiliaryMutationRejectCount,
|
|
481
|
+
auxiliary_unknown_response_count: auxiliaryUnknownResponseCount,
|
|
482
|
+
auxiliary_idle_timeout_count: auxiliaryIdleTimeoutCount,
|
|
483
|
+
auxiliary_message_count: auxiliaryMessageCount,
|
|
484
|
+
auxiliary_notification_count: auxiliaryNotificationCount,
|
|
485
|
+
cleanup_initiator: cleanupInitiator,
|
|
486
|
+
last_socket_close_code: lastSocketCloseCode,
|
|
487
|
+
terminal_alive_at_socket_close: terminalAliveAtSocketClose,
|
|
488
|
+
terminal_exit_signal: terminalExitSignal,
|
|
489
|
+
lifecycle_events: lifecycleEvents,
|
|
490
|
+
cleanup_complete: true,
|
|
491
|
+
})}\n`,
|
|
492
|
+
{ mode: 0o600, flag: 'wx' },
|
|
493
|
+
);
|
|
494
|
+
})();
|
|
495
|
+
return cleanupPromise;
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
const shutdown = () => {
|
|
499
|
+
cleanupInitiator = 'signal';
|
|
500
|
+
clearStartupGrace();
|
|
501
|
+
void cleanup().finally(() => process.exit(0));
|
|
502
|
+
};
|
|
503
|
+
const failBridge = (category) => {
|
|
504
|
+
if (failureReported || shuttingDown) return;
|
|
505
|
+
failureReported = true;
|
|
506
|
+
cleanupInitiator = category;
|
|
507
|
+
process.stderr.write(`${JSON.stringify({ event: 'codex_terminal_bridge_error', category })}\n`);
|
|
508
|
+
void cleanup().finally(() => process.exit(1));
|
|
509
|
+
};
|
|
510
|
+
process.once('SIGINT', shutdown);
|
|
511
|
+
process.once('SIGTERM', shutdown);
|
|
512
|
+
|
|
513
|
+
initialGeneration = spawnMonitor();
|
|
514
|
+
|
|
515
|
+
server = createServer((_request, response) => {
|
|
516
|
+
response.writeHead(404);
|
|
517
|
+
response.end();
|
|
518
|
+
});
|
|
519
|
+
webSocketServer = new WebSocketServer({
|
|
520
|
+
noServer: true,
|
|
521
|
+
maxPayload: MAX_FRAME_BYTES,
|
|
522
|
+
perMessageDeflate: false,
|
|
523
|
+
});
|
|
524
|
+
const sameClient = (left, right) => {
|
|
525
|
+
const leftInfo = left ?? {};
|
|
526
|
+
const rightInfo = right ?? {};
|
|
527
|
+
const hasOriginalIdentity = ['name', 'version'].some((key) => leftInfo[key] !== undefined);
|
|
528
|
+
if (!hasOriginalIdentity) return true;
|
|
529
|
+
if (!right) return false;
|
|
530
|
+
for (const key of ['name', 'version']) {
|
|
531
|
+
if (leftInfo[key] !== undefined && rightInfo?.[key] !== leftInfo[key]) return false;
|
|
532
|
+
}
|
|
533
|
+
return true;
|
|
534
|
+
};
|
|
535
|
+
const canHandoff = (connection) =>
|
|
536
|
+
!shuttingDown &&
|
|
537
|
+
allowStartupHandoff &&
|
|
538
|
+
handoffAttemptCount === 0 &&
|
|
539
|
+
pendingCandidate === null &&
|
|
540
|
+
connection?.handoffEligible === true &&
|
|
541
|
+
connection.startedOperation === false &&
|
|
542
|
+
connection.initialized === true &&
|
|
543
|
+
connection.initializeAck === true &&
|
|
544
|
+
(connection.socket.readyState === WebSocket.OPEN || connection.discoveryClosed === true);
|
|
545
|
+
const auxiliaryIdleTimeoutMs = (() => {
|
|
546
|
+
const value = Number.parseInt(process.env.CODEX_AUXILIARY_IDLE_TIMEOUT_MS ?? '', 10);
|
|
547
|
+
return Number.isSafeInteger(value) && value >= 1_000 && value <= 300_000
|
|
548
|
+
? value
|
|
549
|
+
: DEFAULT_AUXILIARY_IDLE_TIMEOUT_MS;
|
|
550
|
+
})();
|
|
551
|
+
const rejectAuxiliary = (connection, reason = 'auxiliary_rejected') => {
|
|
552
|
+
if (!connection || connection.retiring || !connection.isAuxiliary) return;
|
|
553
|
+
connection.retiring = true;
|
|
554
|
+
if (connection.auxiliaryTimer !== null) clearTimeout(connection.auxiliaryTimer);
|
|
555
|
+
auxiliaryConnections.delete(connection);
|
|
556
|
+
auxiliaryRejectCount += 1;
|
|
557
|
+
if (reason === 'auxiliary_idle_timeout') auxiliaryIdleTimeoutCount += 1;
|
|
558
|
+
if (connection.socket.readyState === WebSocket.OPEN)
|
|
559
|
+
connection.socket.close(1008, reason);
|
|
560
|
+
else connection.socket.terminate();
|
|
561
|
+
cleanupGeneration(connection.generation);
|
|
562
|
+
};
|
|
563
|
+
const rejectCandidate = (connection, statusCode = 1008, reason = 'handoff_rejected') => {
|
|
564
|
+
if (!connection || connection.retiring) return;
|
|
565
|
+
if (connection?.candidateTimer) clearTimeout(connection.candidateTimer);
|
|
566
|
+
if (pendingCandidate === connection) pendingCandidate = null;
|
|
567
|
+
candidateRejectCount += 1;
|
|
568
|
+
connection.retiring = true;
|
|
569
|
+
connection.pendingClientFrames.length = 0;
|
|
570
|
+
connection.pendingClientBytes = 0;
|
|
571
|
+
cleanupGeneration(connection.generation);
|
|
572
|
+
if (connection.socket.readyState === WebSocket.OPEN)
|
|
573
|
+
connection.socket.close(statusCode, reason);
|
|
574
|
+
else connection.socket.terminate();
|
|
575
|
+
if (activeConnection?.socket.readyState !== WebSocket.OPEN && pendingCandidate === null)
|
|
576
|
+
failBridge('startup_handoff_failed');
|
|
577
|
+
};
|
|
578
|
+
const retireConnection = (connection) => {
|
|
579
|
+
if (!connection) return;
|
|
580
|
+
connection.retiring = true;
|
|
581
|
+
if (connection.candidateTimer) clearTimeout(connection.candidateTimer);
|
|
582
|
+
cleanupGeneration(connection.generation);
|
|
583
|
+
if (connection.socket.readyState === WebSocket.OPEN)
|
|
584
|
+
connection.socket.close(1001, 'startup handoff');
|
|
585
|
+
connection.socket.terminate();
|
|
586
|
+
};
|
|
587
|
+
const completeHandoff = (candidate) => {
|
|
588
|
+
if (candidate.retiring || pendingCandidate !== candidate || candidate.initializeAck !== true)
|
|
589
|
+
return;
|
|
590
|
+
candidate.handoffComplete = true;
|
|
591
|
+
if (candidate.candidateTimer) clearTimeout(candidate.candidateTimer);
|
|
592
|
+
const previous = activeConnection;
|
|
593
|
+
if (
|
|
594
|
+
previous === null ||
|
|
595
|
+
previous.handoffEligible !== true ||
|
|
596
|
+
previous.startedOperation === true
|
|
597
|
+
) {
|
|
598
|
+
rejectCandidate(candidate, 1008, 'handoff_no_longer_eligible');
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
pendingCandidate = null;
|
|
602
|
+
handoffCount += 1;
|
|
603
|
+
clearStartupGrace();
|
|
604
|
+
recordLifecycle('handoff_ack');
|
|
605
|
+
if (previous) retireConnection(previous);
|
|
606
|
+
activeConnection = candidate;
|
|
607
|
+
candidate.isCandidate = false;
|
|
608
|
+
candidate.isActive = true;
|
|
609
|
+
const pendingFrames = candidate.pendingClientFrames.splice(0);
|
|
610
|
+
candidate.pendingClientBytes = 0;
|
|
611
|
+
for (const frame of pendingFrames) enqueueForMonitor(candidate, frame);
|
|
612
|
+
};
|
|
613
|
+
const handleMonitorLine = (generation, line) => {
|
|
614
|
+
if (shuttingDown) return;
|
|
615
|
+
monitorLineCount += 1;
|
|
616
|
+
monitorByteCount += line.length + 1;
|
|
617
|
+
if (line.length === 0) return;
|
|
618
|
+
const connection = generation.connection;
|
|
619
|
+
if (!connection || connection.retiring) return;
|
|
620
|
+
if (line.length > MAX_MONITOR_RESPONSE_BYTES) {
|
|
621
|
+
abortGeneration(generation, 'monitor_frame_limit', line.length);
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
let parsed;
|
|
625
|
+
let responseMethod;
|
|
626
|
+
try {
|
|
627
|
+
parsed = JSON.parse(line.toString('utf8'));
|
|
628
|
+
const isInitializeResponse =
|
|
629
|
+
connection.initializeId !== null &&
|
|
630
|
+
parsed.id === connection.initializeId &&
|
|
631
|
+
connection.initializeResponseConsumed === false;
|
|
632
|
+
if (isInitializeResponse) {
|
|
633
|
+
connection.initializeResponseConsumed = true;
|
|
634
|
+
initializeResponseSeen = true;
|
|
635
|
+
initializeErrorCode = parsed.error?.code ?? null;
|
|
636
|
+
if (parsed.error === undefined && parsed.result !== undefined) {
|
|
637
|
+
initializeAck = true;
|
|
638
|
+
connection.initializeAck = true;
|
|
639
|
+
if (connection.isCandidate) {
|
|
640
|
+
handoffInitializeAck = true;
|
|
641
|
+
completeHandoff(connection);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (
|
|
646
|
+
typeof parsed.params?.threadId === 'string' &&
|
|
647
|
+
parsed.params.threadId.length <= 128 &&
|
|
648
|
+
observedThreadIds.size < MAX_DIAGNOSTIC_ENTRIES
|
|
649
|
+
)
|
|
650
|
+
observedThreadIds.add(parsed.params.threadId);
|
|
651
|
+
if (
|
|
652
|
+
typeof parsed.result?.thread?.id === 'string' &&
|
|
653
|
+
parsed.result.thread.id.length <= 128 &&
|
|
654
|
+
observedThreadIds.size < MAX_DIAGNOSTIC_ENTRIES
|
|
655
|
+
)
|
|
656
|
+
observedThreadIds.add(parsed.result.thread.id);
|
|
657
|
+
const isJsonRpcResponse =
|
|
658
|
+
Object.prototype.hasOwnProperty.call(parsed, 'result') ||
|
|
659
|
+
Object.prototype.hasOwnProperty.call(parsed, 'error');
|
|
660
|
+
if (connection.isAuxiliary && parsed.method !== undefined && parsed.id === undefined) {
|
|
661
|
+
auxiliaryNotificationCount += 1;
|
|
662
|
+
connection.auxiliaryNotificationCount += 1;
|
|
663
|
+
if (connection.auxiliaryNotificationCount > MAX_AUXILIARY_NOTIFICATIONS) {
|
|
664
|
+
rejectAuxiliary(connection, 'auxiliary_notification_limit');
|
|
665
|
+
}
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
if (
|
|
669
|
+
connection.isAuxiliary &&
|
|
670
|
+
(parsed.method !== undefined ||
|
|
671
|
+
(isJsonRpcResponse &&
|
|
672
|
+
!isInitializeResponse &&
|
|
673
|
+
!connection.pendingRequests.has(parsed.id)))
|
|
674
|
+
) {
|
|
675
|
+
auxiliaryUnknownResponseCount += 1;
|
|
676
|
+
rejectAuxiliary(connection, 'auxiliary_response_rejected');
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
if (
|
|
680
|
+
isJsonRpcResponse &&
|
|
681
|
+
parsed.id !== undefined &&
|
|
682
|
+
connection.pendingRequests.has(parsed.id)
|
|
683
|
+
) {
|
|
684
|
+
const method = connection.pendingRequests.get(parsed.id);
|
|
685
|
+
responseMethod = method;
|
|
686
|
+
connection.pendingRequests.delete(parsed.id);
|
|
687
|
+
if (parsed.error === undefined && PRIMARY_DISCOVERY.has(method)) {
|
|
688
|
+
connection.discoverySatisfied = true;
|
|
689
|
+
if (!connection.startedOperation) connection.handoffEligible = true;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
if (
|
|
693
|
+
isJsonRpcResponse &&
|
|
694
|
+
parsed.id !== undefined &&
|
|
695
|
+
connection.threadResumeRequestIds.has(parsed.id)
|
|
696
|
+
) {
|
|
697
|
+
connection.threadResumeRequestIds.delete(parsed.id);
|
|
698
|
+
if (parsed.error === undefined) threadResumeResponseSeen = true;
|
|
699
|
+
else {
|
|
700
|
+
if (Number.isSafeInteger(parsed.error?.code)) threadResumeErrorCode = parsed.error.code;
|
|
701
|
+
const message =
|
|
702
|
+
typeof parsed.error?.message === 'string' ? parsed.error.message.toLowerCase() : '';
|
|
703
|
+
threadResumeErrorCategory = /no.?rollout|rollout.*not.?found/u.test(message)
|
|
704
|
+
? 'no_rollout_found'
|
|
705
|
+
: /thread.*not.?found|unknown.*thread/u.test(message)
|
|
706
|
+
? 'thread_not_found'
|
|
707
|
+
: /sqlite|database|locked|busy/u.test(message)
|
|
708
|
+
? 'database_state'
|
|
709
|
+
: /config|invalid.*param|parameter/u.test(message)
|
|
710
|
+
? 'protocol_configuration'
|
|
711
|
+
: /model|provider|auth|credential/u.test(message)
|
|
712
|
+
? 'model_or_auth'
|
|
713
|
+
: 'native_internal_error';
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (line.length > maxMonitorFrameBytes) {
|
|
717
|
+
maxMonitorFrameBytes = line.length;
|
|
718
|
+
maxMonitorFrameMethod = responseMethod ?? null;
|
|
719
|
+
}
|
|
720
|
+
} catch {
|
|
721
|
+
abortGeneration(generation, 'monitor_frame_invalid', line.length, responseMethod);
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
if (connection.isAuxiliary && parsed === null) {
|
|
725
|
+
auxiliaryUnknownResponseCount += 1;
|
|
726
|
+
rejectAuxiliary(connection, 'auxiliary_response_rejected');
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (connection.socket.readyState !== WebSocket.OPEN) return;
|
|
730
|
+
pauseMonitor(generation);
|
|
731
|
+
connection.socket.send(line.toString('utf8'), { binary: false }, (error) => {
|
|
732
|
+
if (error && !generation.retiring && !shuttingDown) {
|
|
733
|
+
abortGeneration(generation, 'bridge_output_failed', line.length, responseMethod);
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
resumeMonitor(generation);
|
|
737
|
+
});
|
|
738
|
+
};
|
|
739
|
+
const handleClientMessage = (connection, data, isBinary) => {
|
|
740
|
+
if (shuttingDown) return;
|
|
741
|
+
try {
|
|
742
|
+
const frame = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
743
|
+
if (isBinary || frame.length > MAX_FRAME_BYTES) throw new Error('bridge_frame_invalid');
|
|
744
|
+
const parsed = JSON.parse(frame.toString('utf8'));
|
|
745
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
746
|
+
throw new Error('bridge_message_not_object');
|
|
747
|
+
if (
|
|
748
|
+
connection.isAuxiliary &&
|
|
749
|
+
(typeof parsed.method !== 'string' ||
|
|
750
|
+
Object.prototype.hasOwnProperty.call(parsed, 'result') ||
|
|
751
|
+
Object.prototype.hasOwnProperty.call(parsed, 'error'))
|
|
752
|
+
) {
|
|
753
|
+
auxiliaryMutationRejectCount += 1;
|
|
754
|
+
rejectAuxiliary(connection, 'auxiliary_client_frame_rejected');
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
const normalizedFrame = Buffer.from(JSON.stringify(parsed), 'utf8');
|
|
758
|
+
const wasInitialized = connection.initialized;
|
|
759
|
+
if (!connection.initialized) {
|
|
760
|
+
const initialize = parseInitialize(normalizedFrame.toString('utf8'));
|
|
761
|
+
if (
|
|
762
|
+
(connection.isCandidate || connection.isAuxiliary) &&
|
|
763
|
+
!sameClient(activeConnection?.clientInfo, initialize.params.clientInfo)
|
|
764
|
+
)
|
|
765
|
+
throw new Error('handoff_client_mismatch');
|
|
766
|
+
connection.initialized = true;
|
|
767
|
+
connection.initializeId = initialize.id;
|
|
768
|
+
connection.clientInfo = initialize.params.clientInfo;
|
|
769
|
+
if (!connection.isCandidate && !connection.isAuxiliary) {
|
|
770
|
+
initializeReceived = true;
|
|
771
|
+
experimentalApi = initialize.params.capabilities.experimentalApi === true;
|
|
772
|
+
}
|
|
773
|
+
if (connection.isCandidate && connection.generation === null) {
|
|
774
|
+
handoffAttemptCount += 1;
|
|
775
|
+
connection.generation = spawnMonitor();
|
|
776
|
+
connection.generation.connection = connection;
|
|
777
|
+
}
|
|
778
|
+
if (connection.isAuxiliary && connection.generation === null) {
|
|
779
|
+
connection.generation = spawnMonitor();
|
|
780
|
+
connection.generation.connection = connection;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
if (connection.isAuxiliary) {
|
|
784
|
+
auxiliaryMessageCount += 1;
|
|
785
|
+
connection.auxiliaryMessageCount += 1;
|
|
786
|
+
if (connection.auxiliaryMessageCount > MAX_AUXILIARY_MESSAGES) {
|
|
787
|
+
rejectAuxiliary(connection, 'auxiliary_message_limit');
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
if (connection.auxiliaryTimer !== null) clearTimeout(connection.auxiliaryTimer);
|
|
791
|
+
connection.auxiliaryTimer = setTimeout(
|
|
792
|
+
() => rejectAuxiliary(connection, 'auxiliary_idle_timeout'),
|
|
793
|
+
auxiliaryIdleTimeoutMs,
|
|
794
|
+
);
|
|
795
|
+
}
|
|
796
|
+
if (connection.isAuxiliary && wasInitialized && parsed.method === 'initialize') {
|
|
797
|
+
auxiliaryMutationRejectCount += 1;
|
|
798
|
+
rejectAuxiliary(connection, 'auxiliary_duplicate_initialize');
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
if (parsed.method === 'turn/start' && !connection.isAuxiliary) turnStartCount += 1;
|
|
802
|
+
if (typeof parsed.method === 'string') {
|
|
803
|
+
if (DIAGNOSTIC_METHODS.has(parsed.method)) {
|
|
804
|
+
if (observedMethods.size < MAX_DIAGNOSTIC_ENTRIES) observedMethods.add(parsed.method);
|
|
805
|
+
} else {
|
|
806
|
+
unknownMethodCount += 1;
|
|
807
|
+
}
|
|
808
|
+
if (parsed.method === 'thread/resume') threadResumeCount += 1;
|
|
809
|
+
if (parsed.method === 'initialize' || parsed.method === 'initialized') {
|
|
810
|
+
if (connection.isAuxiliary && parsed.method === 'initialized') {
|
|
811
|
+
if (connection.initializedNotificationSeen) {
|
|
812
|
+
auxiliaryMutationRejectCount += 1;
|
|
813
|
+
rejectAuxiliary(connection, 'auxiliary_duplicate_initialized');
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
connection.initializedNotificationSeen = true;
|
|
817
|
+
}
|
|
818
|
+
// The notification is part of the handshake and does not affect startup eligibility.
|
|
819
|
+
} else if (connection.isAuxiliary) {
|
|
820
|
+
if (!READ_ONLY_DISCOVERY.has(parsed.method)) {
|
|
821
|
+
auxiliaryMutationRejectCount += 1;
|
|
822
|
+
rejectAuxiliary(connection, 'auxiliary_mutation_rejected');
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
const validRequestId =
|
|
826
|
+
(typeof parsed.id === 'string' && parsed.id.length > 0 && parsed.id.length <= 128) ||
|
|
827
|
+
(Number.isSafeInteger(parsed.id) && parsed.id >= 0);
|
|
828
|
+
if (
|
|
829
|
+
!validRequestId ||
|
|
830
|
+
connection.pendingRequests.has(parsed.id) ||
|
|
831
|
+
connection.pendingRequests.size >= MAX_AUXILIARY_IN_FLIGHT
|
|
832
|
+
) {
|
|
833
|
+
rejectAuxiliary(connection, 'auxiliary_request_limit');
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
connection.pendingRequests.set(parsed.id, parsed.method);
|
|
837
|
+
} else if (READ_ONLY_DISCOVERY.has(parsed.method)) {
|
|
838
|
+
const validRequestId =
|
|
839
|
+
(typeof parsed.id === 'string' && parsed.id.length > 0 && parsed.id.length <= 128) ||
|
|
840
|
+
(Number.isSafeInteger(parsed.id) && parsed.id >= 0);
|
|
841
|
+
if (validRequestId && connection.pendingRequests.size < MAX_PENDING_DISCOVERY)
|
|
842
|
+
connection.pendingRequests.set(parsed.id, parsed.method);
|
|
843
|
+
else {
|
|
844
|
+
connection.startedOperation = true;
|
|
845
|
+
connection.handoffEligible = false;
|
|
846
|
+
}
|
|
847
|
+
} else {
|
|
848
|
+
connection.startedOperation = true;
|
|
849
|
+
connection.handoffEligible = false;
|
|
850
|
+
if (
|
|
851
|
+
parsed.method === 'thread/resume' &&
|
|
852
|
+
((typeof parsed.id === 'string' && parsed.id.length > 0 && parsed.id.length <= 128) ||
|
|
853
|
+
(Number.isSafeInteger(parsed.id) && parsed.id >= 0)) &&
|
|
854
|
+
connection.threadResumeRequestIds.size < MAX_PENDING_DISCOVERY
|
|
855
|
+
)
|
|
856
|
+
connection.threadResumeRequestIds.add(parsed.id);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
if (connection.discoverySatisfied === true && connection.startedOperation === false)
|
|
860
|
+
connection.handoffEligible = true;
|
|
861
|
+
if (
|
|
862
|
+
connection.isCandidate &&
|
|
863
|
+
connection.initializeAck !== true &&
|
|
864
|
+
parsed.method !== 'initialize'
|
|
865
|
+
) {
|
|
866
|
+
if (
|
|
867
|
+
connection.pendingClientFrames.length >= MAX_QUEUED_FRAMES ||
|
|
868
|
+
connection.pendingClientBytes + normalizedFrame.length > MAX_QUEUED_BYTES
|
|
869
|
+
)
|
|
870
|
+
throw new Error('handoff_queue_limit');
|
|
871
|
+
connection.pendingClientFrames.push(normalizedFrame);
|
|
872
|
+
connection.pendingClientBytes += normalizedFrame.length;
|
|
873
|
+
} else {
|
|
874
|
+
enqueueForMonitor(connection, normalizedFrame);
|
|
875
|
+
}
|
|
876
|
+
} catch (error) {
|
|
877
|
+
if (connection.isCandidate) rejectCandidate(connection, 1008, safeError(error));
|
|
878
|
+
else if (connection.isAuxiliary) rejectAuxiliary(connection, safeError(error));
|
|
879
|
+
else connection.socket.close(1008, safeError(error));
|
|
880
|
+
}
|
|
881
|
+
};
|
|
882
|
+
const attachConnection = (webSocket, isCandidate, isAuxiliary = false) => {
|
|
883
|
+
const connection = {
|
|
884
|
+
socket: webSocket,
|
|
885
|
+
generation: isCandidate || isAuxiliary ? null : initialGeneration,
|
|
886
|
+
isCandidate,
|
|
887
|
+
isAuxiliary,
|
|
888
|
+
isActive: !isCandidate && !isAuxiliary,
|
|
889
|
+
retiring: false,
|
|
890
|
+
initialized: false,
|
|
891
|
+
initializeId: null,
|
|
892
|
+
initializeResponseConsumed: false,
|
|
893
|
+
initializedNotificationSeen: false,
|
|
894
|
+
initializeAck: false,
|
|
895
|
+
clientInfo: null,
|
|
896
|
+
pendingRequests: new Map(),
|
|
897
|
+
threadResumeRequestIds: new Set(),
|
|
898
|
+
pendingClientFrames: [],
|
|
899
|
+
pendingClientBytes: 0,
|
|
900
|
+
discoverySatisfied: false,
|
|
901
|
+
handoffEligible: false,
|
|
902
|
+
startedOperation: false,
|
|
903
|
+
handoffComplete: false,
|
|
904
|
+
discoveryClosed: false,
|
|
905
|
+
candidateTimer: null,
|
|
906
|
+
auxiliaryTimer: null,
|
|
907
|
+
auxiliaryMessageCount: 0,
|
|
908
|
+
auxiliaryNotificationCount: 0,
|
|
909
|
+
};
|
|
910
|
+
if (!isCandidate && !isAuxiliary) {
|
|
911
|
+
activeConnection = connection;
|
|
912
|
+
initialGeneration.connection = connection;
|
|
913
|
+
}
|
|
914
|
+
if (isAuxiliary) {
|
|
915
|
+
auxiliaryConnections.add(connection);
|
|
916
|
+
auxiliaryConnectionCount += 1;
|
|
917
|
+
connection.auxiliaryTimer = setTimeout(
|
|
918
|
+
() => rejectAuxiliary(connection, 'auxiliary_idle_timeout'),
|
|
919
|
+
auxiliaryIdleTimeoutMs,
|
|
920
|
+
);
|
|
921
|
+
}
|
|
922
|
+
webSocket.on('message', (data, isBinary) => handleClientMessage(connection, data, isBinary));
|
|
923
|
+
webSocket.on('error', () => {
|
|
924
|
+
if (connection.retiring || shuttingDown) return;
|
|
925
|
+
if (connection.isCandidate) rejectCandidate(connection, 1011, 'candidate_socket_error');
|
|
926
|
+
else if (connection.isAuxiliary) rejectAuxiliary(connection, 'auxiliary_socket_error');
|
|
927
|
+
else {
|
|
928
|
+
cleanupInitiator = 'socket_error';
|
|
929
|
+
recordLifecycle('socket_error');
|
|
930
|
+
clearStartupGrace();
|
|
931
|
+
void cleanup().finally(() => process.exit(1));
|
|
932
|
+
}
|
|
933
|
+
});
|
|
934
|
+
webSocket.once('close', (code) => {
|
|
935
|
+
if (connection.retiring || shuttingDown) return;
|
|
936
|
+
lastSocketCloseCode = code;
|
|
937
|
+
terminalAliveAtSocketClose = terminal?.exitCode === null;
|
|
938
|
+
recordLifecycle('socket_close');
|
|
939
|
+
if (connection.isAuxiliary) {
|
|
940
|
+
if (connection.auxiliaryTimer !== null) clearTimeout(connection.auxiliaryTimer);
|
|
941
|
+
auxiliaryConnections.delete(connection);
|
|
942
|
+
cleanupGeneration(connection.generation);
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
if (connection.isCandidate) {
|
|
946
|
+
rejectCandidate(connection);
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
if (
|
|
950
|
+
pendingCandidate !== null &&
|
|
951
|
+
connection.handoffEligible === true &&
|
|
952
|
+
connection.startedOperation === false &&
|
|
953
|
+
NORMAL_DISCOVERY_CLOSE_CODES.has(code) &&
|
|
954
|
+
terminal?.exitCode === null
|
|
955
|
+
) {
|
|
956
|
+
connection.discoveryClosed = true;
|
|
957
|
+
cleanupGeneration(connection.generation);
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
if (pendingCandidate !== null) {
|
|
961
|
+
cleanupInitiator = 'socket_abnormal_close';
|
|
962
|
+
cleanupGeneration(connection.generation);
|
|
963
|
+
failBridge('startup_handoff_failed');
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
if (
|
|
967
|
+
allowStartupHandoff &&
|
|
968
|
+
handoffCount === 0 &&
|
|
969
|
+
handoffAttemptCount === 0 &&
|
|
970
|
+
connection.initialized === true &&
|
|
971
|
+
connection.initializeAck === true &&
|
|
972
|
+
connection.handoffEligible === true &&
|
|
973
|
+
connection.startedOperation === false &&
|
|
974
|
+
NORMAL_DISCOVERY_CLOSE_CODES.has(code) &&
|
|
975
|
+
terminal?.exitCode === null
|
|
976
|
+
) {
|
|
977
|
+
connection.discoveryClosed = true;
|
|
978
|
+
cleanupGeneration(connection.generation);
|
|
979
|
+
armStartupGrace(connection);
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
cleanupInitiator = code === 1006 ? 'socket_abnormal_close' : 'socket_close';
|
|
983
|
+
clearStartupGrace();
|
|
984
|
+
void cleanup().finally(() => process.exit(0));
|
|
985
|
+
});
|
|
986
|
+
return connection;
|
|
987
|
+
};
|
|
988
|
+
server.on('upgrade', (request, socket, head) => {
|
|
989
|
+
socketUpgradeCount += 1;
|
|
990
|
+
if (shuttingDown) {
|
|
991
|
+
closeSocket(socket, 503, 'bridge_stopped');
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
if (request.headers.origin !== undefined) {
|
|
995
|
+
closeSocket(socket, 403, 'origin_rejected');
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
const isCandidate = activeConnection !== null && canHandoff(activeConnection);
|
|
999
|
+
const isAuxiliary =
|
|
1000
|
+
activeConnection !== null &&
|
|
1001
|
+
!isCandidate &&
|
|
1002
|
+
activeConnection.initialized === true &&
|
|
1003
|
+
activeConnection.startedOperation === true;
|
|
1004
|
+
if (
|
|
1005
|
+
activeConnection !== null &&
|
|
1006
|
+
!isCandidate &&
|
|
1007
|
+
(!isAuxiliary || auxiliaryConnections.size >= MAX_AUXILIARY_CONNECTIONS)
|
|
1008
|
+
) {
|
|
1009
|
+
secondConnectionRejectCount += 1;
|
|
1010
|
+
closeSocket(socket, 409, 'second_connection_rejected');
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
webSocketServer.handleUpgrade(request, socket, head, (webSocket) => {
|
|
1014
|
+
const connection = attachConnection(webSocket, isCandidate, isAuxiliary);
|
|
1015
|
+
if (isCandidate) {
|
|
1016
|
+
pendingCandidate = connection;
|
|
1017
|
+
connection.candidateTimer = setTimeout(
|
|
1018
|
+
() => rejectCandidate(connection, 1008, 'handoff_timeout'),
|
|
1019
|
+
5_000,
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
1022
|
+
});
|
|
1023
|
+
});
|
|
1024
|
+
try {
|
|
1025
|
+
await new Promise((resolve, reject) => {
|
|
1026
|
+
server.once('error', reject);
|
|
1027
|
+
server.listen(socketPath, async () => {
|
|
1028
|
+
await chmod(socketPath, 0o600);
|
|
1029
|
+
resolve();
|
|
1030
|
+
});
|
|
1031
|
+
});
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
await cleanup();
|
|
1034
|
+
throw error;
|
|
1035
|
+
}
|
|
1036
|
+
if (process.env.CODEX_TERMINAL_BRIDGE_READY_FILE !== undefined) {
|
|
1037
|
+
await mkdir(dirname(process.env.CODEX_TERMINAL_BRIDGE_READY_FILE), {
|
|
1038
|
+
recursive: true,
|
|
1039
|
+
mode: 0o700,
|
|
1040
|
+
});
|
|
1041
|
+
await writeFile(process.env.CODEX_TERMINAL_BRIDGE_READY_FILE, socketPath, { mode: 0o600 });
|
|
1042
|
+
}
|
|
1043
|
+
terminal = spawn(codexBinary, ['--remote', `unix://${socketPath}`, ...nativeArgs], {
|
|
1044
|
+
cwd: process.cwd(),
|
|
1045
|
+
env: childEnv,
|
|
1046
|
+
stdio: ['inherit', 'inherit', 'inherit'],
|
|
1047
|
+
});
|
|
1048
|
+
terminal.on('error', () => void cleanup().finally(() => process.exit(1)));
|
|
1049
|
+
terminal.on('exit', (code, signal) => {
|
|
1050
|
+
terminalExitCode = code;
|
|
1051
|
+
terminalExitSignal = signal;
|
|
1052
|
+
recordLifecycle('terminal_exit');
|
|
1053
|
+
clearStartupGrace();
|
|
1054
|
+
if (!shuttingDown) {
|
|
1055
|
+
if (cleanupInitiator === 'unknown') cleanupInitiator = 'terminal_exit';
|
|
1056
|
+
void cleanup().finally(() => process.exit(signal === null ? (code ?? 0) : 1));
|
|
1057
|
+
}
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
main().catch((error) => {
|
|
1062
|
+
process.stderr.write(
|
|
1063
|
+
`${JSON.stringify({ event: 'codex_terminal_bridge_error', category: safeError(error) })}\n`,
|
|
1064
|
+
);
|
|
1065
|
+
process.exitCode = 1;
|
|
1066
|
+
});
|