@shumkov/orchestra 0.6.0 → 0.7.0
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 +12 -4
- package/docs/CLAUDE_CODE_2_1_220.md +1 -1
- package/docs/codex-app-server-compatibility.md +631 -0
- package/index.js +18 -3
- package/lib/codex/app-server-client.js +2866 -0
- package/lib/codex/app-server-supervisor.mjs +41 -0
- package/lib/codex/preflight.js +1073 -0
- package/lib/codex/protocol-schema.json +237 -0
- package/lib/process/codex-process.js +2814 -0
- package/lib/process/factory.js +345 -1
- package/lib/process/process-manager.js +1140 -84
- package/lib/process/process.js +16 -0
- package/package.json +5 -3
|
@@ -0,0 +1,2866 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { execFile, spawn } = require('node:child_process');
|
|
4
|
+
const { createHash } = require('node:crypto');
|
|
5
|
+
const { EventEmitter } = require('node:events');
|
|
6
|
+
const {
|
|
7
|
+
createReadStream,
|
|
8
|
+
lstatSync,
|
|
9
|
+
realpathSync,
|
|
10
|
+
statSync,
|
|
11
|
+
} = require('node:fs');
|
|
12
|
+
const os = require('node:os');
|
|
13
|
+
const path = require('node:path');
|
|
14
|
+
const { StringDecoder } = require('node:string_decoder');
|
|
15
|
+
const { promisify } = require('node:util');
|
|
16
|
+
|
|
17
|
+
function deepFreeze(value) {
|
|
18
|
+
if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
|
|
19
|
+
for (const child of Object.values(value)) deepFreeze(child);
|
|
20
|
+
return Object.freeze(value);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const protocolSchema = deepFreeze(
|
|
24
|
+
JSON.parse(JSON.stringify(require('./protocol-schema.json'))),
|
|
25
|
+
);
|
|
26
|
+
const execFileAsync = promisify(execFile);
|
|
27
|
+
|
|
28
|
+
const CONTROLLED_PATH = '/usr/bin:/bin';
|
|
29
|
+
const SUPERVISOR_PATH = path.join(__dirname, 'app-server-supervisor.mjs');
|
|
30
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
|
|
31
|
+
const DEFAULT_CLOSE_GRACE_MS = 1_000;
|
|
32
|
+
const DEFAULT_CLOSE_KILL_MS = 1_000;
|
|
33
|
+
const DEFAULT_MAX_LINE_BYTES = 1024 * 1024;
|
|
34
|
+
const DEFAULT_MAX_STDERR_BYTES = 64 * 1024;
|
|
35
|
+
const DEFAULT_MAX_PENDING_REQUESTS = 64;
|
|
36
|
+
const DEFAULT_MAX_USED_REQUEST_IDS = 65_536;
|
|
37
|
+
const DEFAULT_MAX_QUEUED_LINES = 256;
|
|
38
|
+
const DEFAULT_MAX_QUEUED_BYTES = 4 * 1024 * 1024;
|
|
39
|
+
const DEFAULT_SINK_TIMEOUT_MS = 5_000;
|
|
40
|
+
const MAX_ID_BYTES = 512;
|
|
41
|
+
const MAX_TEXT_BYTES = 64 * 1024;
|
|
42
|
+
const MAX_COMPLETED_ITEMS = 512;
|
|
43
|
+
const MAX_RESPONSE_ARRAY_ITEMS = 512;
|
|
44
|
+
const MAX_RESPONSE_OBJECT_KEYS = 512;
|
|
45
|
+
const MAX_RESPONSE_NODES = 8_192;
|
|
46
|
+
const MAX_RESPONSE_DEPTH = 12;
|
|
47
|
+
const SAFE_METHOD_PATTERN = /^[A-Za-z][A-Za-z0-9]*(?:\/[A-Za-z][A-Za-z0-9]*)*$/;
|
|
48
|
+
const FORBIDDEN_REQUEST_FIELDS = new Set([
|
|
49
|
+
'sandbox_mode',
|
|
50
|
+
'sandbox_workspace_write',
|
|
51
|
+
'sandbox',
|
|
52
|
+
'sandboxPolicy',
|
|
53
|
+
'permissions',
|
|
54
|
+
'permissionProfile',
|
|
55
|
+
'config',
|
|
56
|
+
]);
|
|
57
|
+
const CONSTRUCTOR_KEYS = new Set([
|
|
58
|
+
'binary',
|
|
59
|
+
'cwd',
|
|
60
|
+
'codexHome',
|
|
61
|
+
'env',
|
|
62
|
+
'spawnFn',
|
|
63
|
+
'killFn',
|
|
64
|
+
'setTimer',
|
|
65
|
+
'clearTimer',
|
|
66
|
+
'requestIdFactory',
|
|
67
|
+
'onNotification',
|
|
68
|
+
'onFault',
|
|
69
|
+
'attestBinaryFn',
|
|
70
|
+
'attestCodexHomeFn',
|
|
71
|
+
'expectedConfigSha256',
|
|
72
|
+
'requestTimeoutMs',
|
|
73
|
+
'sinkTimeoutMs',
|
|
74
|
+
'closeGraceMs',
|
|
75
|
+
'closeKillMs',
|
|
76
|
+
'maxLineBytes',
|
|
77
|
+
'maxStderrBytes',
|
|
78
|
+
'maxPendingRequests',
|
|
79
|
+
'maxUsedRequestIds',
|
|
80
|
+
'maxQueuedLines',
|
|
81
|
+
'maxQueuedBytes',
|
|
82
|
+
]);
|
|
83
|
+
|
|
84
|
+
const CLIENT_REQUESTS = new Map(Object.entries(protocolSchema.clientRequests));
|
|
85
|
+
const CLIENT_NOTIFICATIONS = new Set(protocolSchema.clientNotifications);
|
|
86
|
+
const DENIED_CLIENT_REQUESTS = new Set(protocolSchema.deniedClientRequests);
|
|
87
|
+
const DELIVERED_NOTIFICATIONS = new Set(
|
|
88
|
+
protocolSchema.deliveredServerNotifications,
|
|
89
|
+
);
|
|
90
|
+
const DROPPED_NOTIFICATIONS = new Set(
|
|
91
|
+
protocolSchema.droppedServerNotifications,
|
|
92
|
+
);
|
|
93
|
+
const DENIED_SERVER_REQUESTS = new Map(
|
|
94
|
+
Object.entries(protocolSchema.deniedServerRequests),
|
|
95
|
+
);
|
|
96
|
+
const RECOGNIZED_RPC_ERRORS = new Map(
|
|
97
|
+
Object.entries(protocolSchema.recognizedRpcErrors)
|
|
98
|
+
.map(([method, messages]) => [method, new Set(messages)]),
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
function assertProtocolSchema() {
|
|
102
|
+
const experimental = [...CLIENT_REQUESTS]
|
|
103
|
+
.filter(([, spec]) => spec.experimental)
|
|
104
|
+
.map(([method]) => method)
|
|
105
|
+
.sort();
|
|
106
|
+
if (
|
|
107
|
+
JSON.stringify(experimental) !== JSON.stringify([
|
|
108
|
+
'thread/backgroundTerminals/clean',
|
|
109
|
+
'thread/backgroundTerminals/list',
|
|
110
|
+
])
|
|
111
|
+
|| !CLIENT_NOTIFICATIONS.has('initialized')
|
|
112
|
+
|| CLIENT_NOTIFICATIONS.size !== 1
|
|
113
|
+
|| protocolSchema.requestIdTypes.join(',') !== 'integer,string'
|
|
114
|
+
|| typeof protocolSchema.generatedProtocolV2CanonicalSha256 !== 'string'
|
|
115
|
+
|| !/^[a-f0-9]{64}$/.test(protocolSchema.generatedProtocolV2CanonicalSha256)
|
|
116
|
+
) {
|
|
117
|
+
throw new Error('Codex app-server protocol pin is inconsistent');
|
|
118
|
+
}
|
|
119
|
+
for (const method of DELIVERED_NOTIFICATIONS) {
|
|
120
|
+
if (DROPPED_NOTIFICATIONS.has(method)) {
|
|
121
|
+
throw new Error('Codex app-server notification classes overlap');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (
|
|
125
|
+
CLIENT_REQUESTS.has('thread/backgroundTerminals/terminate')
|
|
126
|
+
|| CLIENT_REQUESTS.has('command/exec')
|
|
127
|
+
|| !DENIED_CLIENT_REQUESTS.has('command/exec')
|
|
128
|
+
) {
|
|
129
|
+
throw new Error('Codex app-server privileged method policy drifted');
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
assertProtocolSchema();
|
|
134
|
+
|
|
135
|
+
class CodexAppServerError extends Error {
|
|
136
|
+
constructor(message, code, options) {
|
|
137
|
+
super(message, options);
|
|
138
|
+
this.name = 'CodexAppServerError';
|
|
139
|
+
this.code = code;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function buildCodexAppServerEnv(codexHome, hostEnv = process.env) {
|
|
144
|
+
return Object.fromEntries(
|
|
145
|
+
Object.entries({
|
|
146
|
+
HOME: hostEnv.HOME,
|
|
147
|
+
PATH: CONTROLLED_PATH,
|
|
148
|
+
TMPDIR: hostEnv.TMPDIR,
|
|
149
|
+
LANG: hostEnv.LANG,
|
|
150
|
+
LC_ALL: hostEnv.LC_ALL,
|
|
151
|
+
CODEX_HOME: codexHome,
|
|
152
|
+
}).filter(([, value]) => value !== undefined),
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function binaryFingerprint(binary) {
|
|
157
|
+
const stat = statSync(binary, { bigint: true });
|
|
158
|
+
if (!stat.isFile()) {
|
|
159
|
+
throw new CodexAppServerError(
|
|
160
|
+
'pinned Codex binary is not a regular file',
|
|
161
|
+
'CODEX_BINARY_MISMATCH',
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
dev: stat.dev.toString(),
|
|
166
|
+
ino: stat.ino.toString(),
|
|
167
|
+
size: stat.size.toString(),
|
|
168
|
+
mtimeNs: stat.mtimeNs.toString(),
|
|
169
|
+
ctimeNs: stat.ctimeNs.toString(),
|
|
170
|
+
mode: Number(stat.mode),
|
|
171
|
+
uid: Number(stat.uid),
|
|
172
|
+
nlink: Number(stat.nlink),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function hashFile(binary) {
|
|
177
|
+
const hash = createHash('sha256');
|
|
178
|
+
await new Promise((resolve, reject) => {
|
|
179
|
+
const stream = createReadStream(binary);
|
|
180
|
+
stream.on('data', (chunk) => hash.update(chunk));
|
|
181
|
+
stream.once('error', reject);
|
|
182
|
+
stream.once('end', resolve);
|
|
183
|
+
});
|
|
184
|
+
return hash.digest('hex');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function attestPinnedCodexBinary(binary) {
|
|
188
|
+
if (realpathSync(binary) !== binary) {
|
|
189
|
+
throw new CodexAppServerError(
|
|
190
|
+
'pinned Codex binary path is not canonical',
|
|
191
|
+
'CODEX_BINARY_MISMATCH',
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
const root = path.parse(binary).root;
|
|
195
|
+
let component = root;
|
|
196
|
+
for (const part of binary.slice(root.length).split('/').filter(Boolean)) {
|
|
197
|
+
component = path.join(component, part);
|
|
198
|
+
const stat = lstatSync(component);
|
|
199
|
+
if (
|
|
200
|
+
stat.isSymbolicLink()
|
|
201
|
+
|| ![0, process.getuid?.()].includes(stat.uid)
|
|
202
|
+
|| (stat.mode & 0o022) !== 0
|
|
203
|
+
) {
|
|
204
|
+
throw new CodexAppServerError(
|
|
205
|
+
'pinned Codex binary path ownership or mode is unsafe',
|
|
206
|
+
'CODEX_BINARY_MISMATCH',
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const fingerprint = binaryFingerprint(binary);
|
|
211
|
+
if (
|
|
212
|
+
(fingerprint.mode & 0o022) !== 0
|
|
213
|
+
|| (process.platform !== 'win32' && (fingerprint.mode & 0o111) === 0)
|
|
214
|
+
|| ![0, process.getuid?.()].includes(fingerprint.uid)
|
|
215
|
+
|| fingerprint.nlink !== 1
|
|
216
|
+
) {
|
|
217
|
+
throw new CodexAppServerError(
|
|
218
|
+
'pinned Codex binary ownership or mode is unsafe',
|
|
219
|
+
'CODEX_BINARY_MISMATCH',
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
const sha256 = await hashFile(binary);
|
|
223
|
+
if (sha256 !== protocolSchema.binarySha256) {
|
|
224
|
+
throw new CodexAppServerError(
|
|
225
|
+
'pinned Codex binary hash mismatch',
|
|
226
|
+
'CODEX_BINARY_MISMATCH',
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
let stdout;
|
|
230
|
+
try {
|
|
231
|
+
({ stdout } = await execFileAsync(binary, ['--version'], {
|
|
232
|
+
encoding: 'utf8',
|
|
233
|
+
timeout: 10_000,
|
|
234
|
+
maxBuffer: 4 * 1024,
|
|
235
|
+
env: { PATH: CONTROLLED_PATH },
|
|
236
|
+
}));
|
|
237
|
+
} catch {
|
|
238
|
+
throw new CodexAppServerError(
|
|
239
|
+
'pinned Codex binary version probe failed',
|
|
240
|
+
'CODEX_BINARY_MISMATCH',
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
if (stdout.trim() !== protocolSchema.cliVersion) {
|
|
244
|
+
throw new CodexAppServerError(
|
|
245
|
+
'pinned Codex binary version mismatch',
|
|
246
|
+
'CODEX_BINARY_MISMATCH',
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
path: binary,
|
|
251
|
+
sha256,
|
|
252
|
+
version: stdout.trim(),
|
|
253
|
+
fingerprint,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function pathFingerprint(target) {
|
|
258
|
+
const stat = lstatSync(target, { bigint: true });
|
|
259
|
+
return {
|
|
260
|
+
dev: stat.dev.toString(),
|
|
261
|
+
ino: stat.ino.toString(),
|
|
262
|
+
size: stat.size.toString(),
|
|
263
|
+
mtimeNs: stat.mtimeNs.toString(),
|
|
264
|
+
ctimeNs: stat.ctimeNs.toString(),
|
|
265
|
+
mode: Number(stat.mode),
|
|
266
|
+
uid: Number(stat.uid),
|
|
267
|
+
nlink: Number(stat.nlink),
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function canonicalTemporaryRoots() {
|
|
272
|
+
const roots = new Set();
|
|
273
|
+
for (const candidate of [
|
|
274
|
+
os.tmpdir(),
|
|
275
|
+
'/tmp',
|
|
276
|
+
'/private/tmp',
|
|
277
|
+
'/var/tmp',
|
|
278
|
+
'/private/var/folders',
|
|
279
|
+
]) {
|
|
280
|
+
try {
|
|
281
|
+
roots.add(realpathSync(candidate));
|
|
282
|
+
} catch {}
|
|
283
|
+
}
|
|
284
|
+
return [...roots];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function assertSecureOwnedPath(target, {
|
|
288
|
+
kind,
|
|
289
|
+
expectedMode,
|
|
290
|
+
temporaryRoots = canonicalTemporaryRoots(),
|
|
291
|
+
}) {
|
|
292
|
+
if (realpathSync(target) !== target) {
|
|
293
|
+
throw new CodexAppServerError(
|
|
294
|
+
`pinned Codex ${kind} path is not canonical`,
|
|
295
|
+
'CODEX_CONFIG_MISMATCH',
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
if (temporaryRoots.some((root) => isWithin(root, target))) {
|
|
299
|
+
throw new CodexAppServerError(
|
|
300
|
+
`pinned Codex ${kind} cannot be stored in a temporary directory`,
|
|
301
|
+
'CODEX_CONFIG_MISMATCH',
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
const root = path.parse(target).root;
|
|
305
|
+
let component = root;
|
|
306
|
+
for (const part of target.slice(root.length).split('/').filter(Boolean)) {
|
|
307
|
+
component = path.join(component, part);
|
|
308
|
+
const stat = lstatSync(component);
|
|
309
|
+
const isTarget = component === target;
|
|
310
|
+
if (
|
|
311
|
+
stat.isSymbolicLink()
|
|
312
|
+
|| ![0, process.getuid?.()].includes(stat.uid)
|
|
313
|
+
|| (stat.mode & 0o022) !== 0
|
|
314
|
+
|| (
|
|
315
|
+
isTarget
|
|
316
|
+
&& expectedMode !== undefined
|
|
317
|
+
&& (stat.mode & 0o777) !== expectedMode
|
|
318
|
+
)
|
|
319
|
+
) {
|
|
320
|
+
throw new CodexAppServerError(
|
|
321
|
+
`pinned Codex ${kind} ownership or mode is unsafe`,
|
|
322
|
+
'CODEX_CONFIG_MISMATCH',
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function assertSecureCredentialFile(file, label) {
|
|
329
|
+
const stat = lstatSync(file);
|
|
330
|
+
if (
|
|
331
|
+
stat.isSymbolicLink()
|
|
332
|
+
|| !stat.isFile()
|
|
333
|
+
|| (
|
|
334
|
+
typeof process.getuid === 'function'
|
|
335
|
+
&& stat.uid !== process.getuid()
|
|
336
|
+
)
|
|
337
|
+
|| (stat.mode & 0o777) !== 0o600
|
|
338
|
+
|| stat.nlink !== 1
|
|
339
|
+
) {
|
|
340
|
+
throw new CodexAppServerError(
|
|
341
|
+
`pinned Codex ${label} ownership or mode is unsafe`,
|
|
342
|
+
'CODEX_CONFIG_MISMATCH',
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
return pathFingerprint(file);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async function attestPinnedCodexHome(
|
|
349
|
+
codexHome,
|
|
350
|
+
expectedConfigSha256,
|
|
351
|
+
{ temporaryRoots = canonicalTemporaryRoots() } = {},
|
|
352
|
+
) {
|
|
353
|
+
if (
|
|
354
|
+
typeof expectedConfigSha256 !== 'string'
|
|
355
|
+
|| !/^[a-f0-9]{64}$/.test(expectedConfigSha256)
|
|
356
|
+
) {
|
|
357
|
+
throw new TypeError(
|
|
358
|
+
'CodexAppServerClient: expectedConfigSha256 must be a lowercase SHA-256',
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
assertSecureOwnedPath(codexHome, {
|
|
362
|
+
kind: 'credential home',
|
|
363
|
+
expectedMode: 0o700,
|
|
364
|
+
temporaryRoots,
|
|
365
|
+
});
|
|
366
|
+
const homeStat = lstatSync(codexHome);
|
|
367
|
+
if (!homeStat.isDirectory() || homeStat.nlink < 1) {
|
|
368
|
+
throw new CodexAppServerError(
|
|
369
|
+
'pinned Codex credential home is not a directory',
|
|
370
|
+
'CODEX_CONFIG_MISMATCH',
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const configPath = path.join(codexHome, 'config.toml');
|
|
375
|
+
const configFingerprint = assertSecureCredentialFile(
|
|
376
|
+
configPath,
|
|
377
|
+
'config.toml',
|
|
378
|
+
);
|
|
379
|
+
const configSha256 = await hashFile(configPath);
|
|
380
|
+
if (configSha256 !== expectedConfigSha256) {
|
|
381
|
+
throw new CodexAppServerError(
|
|
382
|
+
'pinned Codex config.toml hash mismatch',
|
|
383
|
+
'CODEX_CONFIG_MISMATCH',
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const authPath = path.join(codexHome, 'auth.json');
|
|
388
|
+
let authFingerprint = null;
|
|
389
|
+
try {
|
|
390
|
+
authFingerprint = assertSecureCredentialFile(authPath, 'auth.json');
|
|
391
|
+
} catch (error) {
|
|
392
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
393
|
+
}
|
|
394
|
+
return {
|
|
395
|
+
path: codexHome,
|
|
396
|
+
configSha256,
|
|
397
|
+
configFingerprint,
|
|
398
|
+
authFingerprint,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function assertAbsolute(value, label) {
|
|
403
|
+
if (typeof value !== 'string' || !path.isAbsolute(value)) {
|
|
404
|
+
throw new TypeError(`CodexAppServerClient: ${label} must be an absolute path`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function assertPositiveInteger(value, label) {
|
|
409
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
410
|
+
throw new TypeError(`CodexAppServerClient: ${label} must be a positive integer`);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function isWithin(root, candidate) {
|
|
415
|
+
const relative = path.relative(root, candidate);
|
|
416
|
+
return (
|
|
417
|
+
relative === ''
|
|
418
|
+
|| (!relative.startsWith('..') && !path.isAbsolute(relative))
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function assertRequestId(id) {
|
|
423
|
+
if (
|
|
424
|
+
!(typeof id === 'string' && id.length > 0 && Buffer.byteLength(id) <= MAX_ID_BYTES)
|
|
425
|
+
&& !Number.isSafeInteger(id)
|
|
426
|
+
) {
|
|
427
|
+
throw new CodexAppServerError(
|
|
428
|
+
'app-server request ID was outside the pinned schema',
|
|
429
|
+
'CODEX_PROTOCOL_ERROR',
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function boundedString(value, label, maxBytes = MAX_ID_BYTES) {
|
|
435
|
+
if (value == null) return undefined;
|
|
436
|
+
if (typeof value !== 'string' || Buffer.byteLength(value) > maxBytes) {
|
|
437
|
+
throw new CodexAppServerError(
|
|
438
|
+
`app-server ${label} exceeded the size limit`,
|
|
439
|
+
'CODEX_PROTOCOL_ERROR',
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
return value;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function protocolString(value, label, maxBytes = MAX_ID_BYTES) {
|
|
446
|
+
const projected = boundedString(value, label, maxBytes);
|
|
447
|
+
if (projected === undefined) {
|
|
448
|
+
throw new CodexAppServerError(
|
|
449
|
+
`app-server ${label} must be a string`,
|
|
450
|
+
'CODEX_PROTOCOL_ERROR',
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
return projected;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function projectThreadStatus(value, label) {
|
|
457
|
+
const status = protocolObject(value, label);
|
|
458
|
+
const type = protocolRequiredString(status.type, `${label} type`);
|
|
459
|
+
if (!['notLoaded', 'idle', 'systemError', 'active'].includes(type)) {
|
|
460
|
+
throw new CodexAppServerError(
|
|
461
|
+
`app-server ${label} is unsupported`,
|
|
462
|
+
'CODEX_PROTOCOL_ERROR',
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
if (type !== 'active') return { type };
|
|
466
|
+
if (
|
|
467
|
+
!Array.isArray(status.activeFlags)
|
|
468
|
+
|| status.activeFlags.length > 32
|
|
469
|
+
|| status.activeFlags.some((flag) => (
|
|
470
|
+
!['waitingOnApproval', 'waitingOnUserInput'].includes(flag)
|
|
471
|
+
))
|
|
472
|
+
) {
|
|
473
|
+
throw new CodexAppServerError(
|
|
474
|
+
`app-server ${label} active flags are malformed`,
|
|
475
|
+
'CODEX_PROTOCOL_ERROR',
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
return { type, activeFlags: [...status.activeFlags] };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function projectCollaborationMode(value) {
|
|
482
|
+
const collaboration = protocolObject(value, 'collaboration mode');
|
|
483
|
+
const mode = protocolRequiredString(collaboration.mode, 'collaboration mode');
|
|
484
|
+
if (!['plan', 'default'].includes(mode)) {
|
|
485
|
+
throw new CodexAppServerError(
|
|
486
|
+
'app-server collaboration mode is unsupported',
|
|
487
|
+
'CODEX_PROTOCOL_ERROR',
|
|
488
|
+
);
|
|
489
|
+
}
|
|
490
|
+
const settings = protocolObject(
|
|
491
|
+
collaboration.settings,
|
|
492
|
+
'collaboration mode settings',
|
|
493
|
+
);
|
|
494
|
+
const projected = {
|
|
495
|
+
mode,
|
|
496
|
+
model: protocolRequiredString(
|
|
497
|
+
settings.model,
|
|
498
|
+
'collaboration mode model',
|
|
499
|
+
),
|
|
500
|
+
};
|
|
501
|
+
if (settings.reasoning_effort != null) {
|
|
502
|
+
projected.reasoningEffort = protocolRequiredString(
|
|
503
|
+
settings.reasoning_effort,
|
|
504
|
+
'collaboration mode reasoning effort',
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
if (
|
|
508
|
+
settings.developer_instructions !== undefined
|
|
509
|
+
&& settings.developer_instructions !== null
|
|
510
|
+
) {
|
|
511
|
+
protocolString(
|
|
512
|
+
settings.developer_instructions,
|
|
513
|
+
'collaboration mode developer instructions',
|
|
514
|
+
MAX_TEXT_BYTES,
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
return projected;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function projectNotification(message, ownedCwd) {
|
|
521
|
+
const source = protocolObject(
|
|
522
|
+
message.params ?? {},
|
|
523
|
+
`${message.method} notification parameters`,
|
|
524
|
+
);
|
|
525
|
+
const params = {};
|
|
526
|
+
const requiredIds = new Set();
|
|
527
|
+
if (
|
|
528
|
+
message.method === 'thread/status/changed'
|
|
529
|
+
|| message.method === 'thread/settings/updated'
|
|
530
|
+
|| message.method === 'turn/started'
|
|
531
|
+
|| message.method === 'turn/completed'
|
|
532
|
+
) requiredIds.add('threadId');
|
|
533
|
+
if (
|
|
534
|
+
message.method === 'error'
|
|
535
|
+
|| message.method === 'item/started'
|
|
536
|
+
|| message.method === 'item/completed'
|
|
537
|
+
|| message.method === 'item/agentMessage/delta'
|
|
538
|
+
) {
|
|
539
|
+
requiredIds.add('threadId');
|
|
540
|
+
requiredIds.add('turnId');
|
|
541
|
+
}
|
|
542
|
+
if (message.method === 'item/agentMessage/delta') requiredIds.add('itemId');
|
|
543
|
+
for (const key of ['threadId', 'turnId', 'itemId']) {
|
|
544
|
+
const value = requiredIds.has(key)
|
|
545
|
+
? protocolRequiredString(source[key], `notification ${key}`)
|
|
546
|
+
: boundedString(source[key], `notification ${key}`);
|
|
547
|
+
if (value !== undefined) params[key] = value;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
if (message.method === 'error') {
|
|
551
|
+
if (typeof source.willRetry !== 'boolean' || source.error == null) {
|
|
552
|
+
throw new CodexAppServerError(
|
|
553
|
+
'app-server error notification omitted retry ownership',
|
|
554
|
+
'CODEX_PROTOCOL_ERROR',
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
protocolObject(source.error, 'error notification payload');
|
|
558
|
+
params.willRetry = source.willRetry;
|
|
559
|
+
params.error = { present: source.error != null };
|
|
560
|
+
} else if (message.method === 'thread/status/changed') {
|
|
561
|
+
params.status = projectThreadStatus(source.status, 'thread status');
|
|
562
|
+
} else if (message.method === 'thread/settings/updated') {
|
|
563
|
+
const settings = protocolObject(
|
|
564
|
+
source.threadSettings,
|
|
565
|
+
'thread settings',
|
|
566
|
+
);
|
|
567
|
+
if (settings.cwd !== ownedCwd) {
|
|
568
|
+
throw new CodexAppServerError(
|
|
569
|
+
'app-server thread settings changed the owned workspace',
|
|
570
|
+
'CODEX_PROTOCOL_ERROR',
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
const reviewer = protocolRequiredString(
|
|
574
|
+
settings.approvalsReviewer,
|
|
575
|
+
'thread settings approvals reviewer',
|
|
576
|
+
);
|
|
577
|
+
if (!['user', 'auto_review', 'guardian_subagent'].includes(reviewer)) {
|
|
578
|
+
throw new CodexAppServerError(
|
|
579
|
+
'app-server thread settings approvals reviewer is unsupported',
|
|
580
|
+
'CODEX_PROTOCOL_ERROR',
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
params.threadSettings = {
|
|
584
|
+
model: protocolRequiredString(settings.model, 'thread settings model'),
|
|
585
|
+
modelProvider: protocolRequiredString(
|
|
586
|
+
settings.modelProvider,
|
|
587
|
+
'thread settings model provider',
|
|
588
|
+
),
|
|
589
|
+
approvalPolicy: projectApprovalPolicy(settings.approvalPolicy),
|
|
590
|
+
approvalsReviewer: reviewer,
|
|
591
|
+
collaborationMode: projectCollaborationMode(
|
|
592
|
+
settings.collaborationMode,
|
|
593
|
+
),
|
|
594
|
+
sandboxPolicy: projectSandbox(settings.sandboxPolicy, ownedCwd),
|
|
595
|
+
};
|
|
596
|
+
if (settings.effort != null) {
|
|
597
|
+
params.threadSettings.effort = protocolRequiredString(
|
|
598
|
+
settings.effort,
|
|
599
|
+
'thread settings effort',
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
const profile = settings.activePermissionProfile;
|
|
603
|
+
if (profile != null) {
|
|
604
|
+
params.threadSettings.activePermissionProfile = {
|
|
605
|
+
id: protocolRequiredString(profile.id, 'permission profile id'),
|
|
606
|
+
extends: profile.extends == null
|
|
607
|
+
? null
|
|
608
|
+
: boundedString(profile.extends, 'permission profile parent'),
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
} else if (
|
|
612
|
+
message.method === 'turn/started'
|
|
613
|
+
|| message.method === 'turn/completed'
|
|
614
|
+
) {
|
|
615
|
+
const turn = projectTurn(source.turn, 'notification turn');
|
|
616
|
+
params.turn = {
|
|
617
|
+
id: turn.id,
|
|
618
|
+
status: turn.status,
|
|
619
|
+
};
|
|
620
|
+
if (message.method === 'turn/completed') {
|
|
621
|
+
params.turn.error = turn.error;
|
|
622
|
+
params.turn.items = turn.items;
|
|
623
|
+
}
|
|
624
|
+
} else if (
|
|
625
|
+
message.method === 'item/started'
|
|
626
|
+
|| message.method === 'item/completed'
|
|
627
|
+
) {
|
|
628
|
+
const timestamp = message.method === 'item/started'
|
|
629
|
+
? source.startedAtMs
|
|
630
|
+
: source.completedAtMs;
|
|
631
|
+
if (!Number.isSafeInteger(timestamp)) {
|
|
632
|
+
throw new CodexAppServerError(
|
|
633
|
+
'app-server item notification timestamp is malformed',
|
|
634
|
+
'CODEX_PROTOCOL_ERROR',
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
const item = protocolObject(source.item, 'notification item');
|
|
638
|
+
params.item = {
|
|
639
|
+
id: protocolRequiredString(item.id, 'item id'),
|
|
640
|
+
type: protocolRequiredString(item.type, 'item type'),
|
|
641
|
+
};
|
|
642
|
+
const clientId = boundedString(item.clientId, 'item client id');
|
|
643
|
+
if (clientId !== undefined) params.item.clientId = clientId;
|
|
644
|
+
if (item.type === 'agentMessage') {
|
|
645
|
+
const text = boundedString(item.text, 'agent message', MAX_TEXT_BYTES);
|
|
646
|
+
if (text !== undefined) params.item.text = text;
|
|
647
|
+
}
|
|
648
|
+
} else if (message.method === 'item/agentMessage/delta') {
|
|
649
|
+
params.delta = protocolString(
|
|
650
|
+
source.delta,
|
|
651
|
+
'agent message delta',
|
|
652
|
+
MAX_TEXT_BYTES,
|
|
653
|
+
);
|
|
654
|
+
}
|
|
655
|
+
return { method: message.method, params };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function plainObject(value, label) {
|
|
659
|
+
if (
|
|
660
|
+
!value
|
|
661
|
+
|| typeof value !== 'object'
|
|
662
|
+
|| Array.isArray(value)
|
|
663
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value))
|
|
664
|
+
) {
|
|
665
|
+
throw new CodexAppServerError(
|
|
666
|
+
`app-server ${label} must be a plain object`,
|
|
667
|
+
'CODEX_RPC_REJECTED',
|
|
668
|
+
);
|
|
669
|
+
}
|
|
670
|
+
return value;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function protocolObject(value, label) {
|
|
674
|
+
try {
|
|
675
|
+
return plainObject(value, label);
|
|
676
|
+
} catch (error) {
|
|
677
|
+
throw new CodexAppServerError(
|
|
678
|
+
`app-server ${label} must be a plain object`,
|
|
679
|
+
'CODEX_PROTOCOL_ERROR',
|
|
680
|
+
{ cause: error },
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function boundedRequiredString(value, label, maxBytes = MAX_ID_BYTES) {
|
|
686
|
+
const projected = boundedString(value, label, maxBytes);
|
|
687
|
+
if (projected === undefined || projected.length === 0) {
|
|
688
|
+
throw new CodexAppServerError(
|
|
689
|
+
`app-server ${label} is required`,
|
|
690
|
+
'CODEX_RPC_REJECTED',
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
return projected;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function protocolRequiredString(value, label, maxBytes = MAX_ID_BYTES) {
|
|
697
|
+
const projected = boundedString(value, label, maxBytes);
|
|
698
|
+
if (projected === undefined || projected.length === 0) {
|
|
699
|
+
throw new CodexAppServerError(
|
|
700
|
+
`app-server ${label} is required`,
|
|
701
|
+
'CODEX_PROTOCOL_ERROR',
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
return projected;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function protocolOptionalCursor(value, label = 'pagination cursor') {
|
|
708
|
+
if (value == null) return null;
|
|
709
|
+
return protocolRequiredString(value, label);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function cloneBoundedJson(value, label) {
|
|
713
|
+
let nodes = 0;
|
|
714
|
+
const clone = (current, depth) => {
|
|
715
|
+
nodes += 1;
|
|
716
|
+
if (nodes > MAX_RESPONSE_NODES || depth > MAX_RESPONSE_DEPTH) {
|
|
717
|
+
throw new CodexAppServerError(
|
|
718
|
+
`app-server ${label} exceeded structural bounds`,
|
|
719
|
+
'CODEX_PROTOCOL_ERROR',
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
if (current === null || typeof current === 'boolean') return current;
|
|
723
|
+
if (typeof current === 'string') {
|
|
724
|
+
return protocolString(current, label, MAX_TEXT_BYTES);
|
|
725
|
+
}
|
|
726
|
+
if (typeof current === 'number' && Number.isFinite(current)) return current;
|
|
727
|
+
if (Array.isArray(current)) {
|
|
728
|
+
if (current.length > MAX_RESPONSE_ARRAY_ITEMS) {
|
|
729
|
+
throw new CodexAppServerError(
|
|
730
|
+
`app-server ${label} array exceeded the size limit`,
|
|
731
|
+
'CODEX_PROTOCOL_ERROR',
|
|
732
|
+
);
|
|
733
|
+
}
|
|
734
|
+
return current.map((entry) => clone(entry, depth + 1));
|
|
735
|
+
}
|
|
736
|
+
const object = protocolObject(current, label);
|
|
737
|
+
const entries = Object.entries(object);
|
|
738
|
+
if (entries.length > MAX_RESPONSE_OBJECT_KEYS) {
|
|
739
|
+
throw new CodexAppServerError(
|
|
740
|
+
`app-server ${label} object exceeded the size limit`,
|
|
741
|
+
'CODEX_PROTOCOL_ERROR',
|
|
742
|
+
);
|
|
743
|
+
}
|
|
744
|
+
return Object.fromEntries(entries.map(([key, entry]) => [
|
|
745
|
+
protocolString(key, `${label} key`),
|
|
746
|
+
clone(entry, depth + 1),
|
|
747
|
+
]));
|
|
748
|
+
};
|
|
749
|
+
return clone(value, 0);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function canonicalJson(value) {
|
|
753
|
+
if (Array.isArray(value)) return value.map(canonicalJson);
|
|
754
|
+
if (value && typeof value === 'object') {
|
|
755
|
+
return Object.fromEntries(
|
|
756
|
+
Object.keys(value)
|
|
757
|
+
.sort()
|
|
758
|
+
.map((key) => [key, canonicalJson(value[key])]),
|
|
759
|
+
);
|
|
760
|
+
}
|
|
761
|
+
return value;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function jsonDigest(value) {
|
|
765
|
+
return createHash('sha256')
|
|
766
|
+
.update(JSON.stringify(canonicalJson(value)))
|
|
767
|
+
.digest('hex');
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function projectedOptionalString(value, label, maxBytes = MAX_ID_BYTES) {
|
|
771
|
+
if (value == null) return null;
|
|
772
|
+
return protocolString(value, label, maxBytes);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
function objectKeys(value, label) {
|
|
776
|
+
if (value == null) return [];
|
|
777
|
+
return Object.keys(protocolObject(value, label))
|
|
778
|
+
.map((key) => protocolString(key, `${label} key`))
|
|
779
|
+
.sort();
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
function projectedObjectIndex(value, label) {
|
|
783
|
+
const keys = objectKeys(value, label);
|
|
784
|
+
return {
|
|
785
|
+
count: keys.length,
|
|
786
|
+
keySha256: keys
|
|
787
|
+
.map((key) => createHash('sha256').update(key).digest('hex'))
|
|
788
|
+
.sort(),
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
function projectEffectiveConfig(value) {
|
|
793
|
+
const config = cloneBoundedJson(value, 'config');
|
|
794
|
+
const profileSource = config.permissions == null
|
|
795
|
+
? {}
|
|
796
|
+
: protocolObject(config.permissions, 'permission profiles');
|
|
797
|
+
const permissionProfiles = Object.entries(profileSource)
|
|
798
|
+
.map(([id, rawProfile]) => {
|
|
799
|
+
const profile = protocolObject(rawProfile, 'permission profile config');
|
|
800
|
+
const filesystem = profile.filesystem == null
|
|
801
|
+
? {}
|
|
802
|
+
: protocolObject(profile.filesystem, 'permission profile filesystem');
|
|
803
|
+
const network = profile.network == null
|
|
804
|
+
? {}
|
|
805
|
+
: protocolObject(profile.network, 'permission profile network');
|
|
806
|
+
if (
|
|
807
|
+
network.enabled !== undefined
|
|
808
|
+
&& typeof network.enabled !== 'boolean'
|
|
809
|
+
) {
|
|
810
|
+
throw new CodexAppServerError(
|
|
811
|
+
'app-server permission profile network policy is malformed',
|
|
812
|
+
'CODEX_PROTOCOL_ERROR',
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
return {
|
|
816
|
+
id: protocolRequiredString(id, 'permission profile id'),
|
|
817
|
+
extends: projectedOptionalString(
|
|
818
|
+
profile.extends,
|
|
819
|
+
'permission profile parent',
|
|
820
|
+
),
|
|
821
|
+
networkEnabled: network.enabled ?? null,
|
|
822
|
+
filesystemSha256: jsonDigest(filesystem),
|
|
823
|
+
filesystem: Object.entries(filesystem)
|
|
824
|
+
.filter(([, access]) => typeof access === 'string')
|
|
825
|
+
.map(([root, access]) => ({
|
|
826
|
+
rootSha256: createHash('sha256').update(root).digest('hex'),
|
|
827
|
+
access: protocolRequiredString(
|
|
828
|
+
access,
|
|
829
|
+
'permission profile filesystem access',
|
|
830
|
+
),
|
|
831
|
+
}))
|
|
832
|
+
.sort((left, right) => (
|
|
833
|
+
left.rootSha256.localeCompare(right.rootSha256)
|
|
834
|
+
)),
|
|
835
|
+
};
|
|
836
|
+
})
|
|
837
|
+
.sort((left, right) => left.id.localeCompare(right.id));
|
|
838
|
+
const shellEnvironment = config.shell_environment_policy == null
|
|
839
|
+
? {}
|
|
840
|
+
: protocolObject(
|
|
841
|
+
config.shell_environment_policy,
|
|
842
|
+
'shell environment policy',
|
|
843
|
+
);
|
|
844
|
+
if (
|
|
845
|
+
config.allow_login_shell !== undefined
|
|
846
|
+
&& typeof config.allow_login_shell !== 'boolean'
|
|
847
|
+
) {
|
|
848
|
+
throw new CodexAppServerError(
|
|
849
|
+
'app-server login shell policy is malformed',
|
|
850
|
+
'CODEX_PROTOCOL_ERROR',
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
return {
|
|
854
|
+
sha256: jsonDigest(config),
|
|
855
|
+
model: projectedOptionalString(config.model, 'configured model'),
|
|
856
|
+
modelProvider: projectedOptionalString(
|
|
857
|
+
config.model_provider,
|
|
858
|
+
'configured model provider',
|
|
859
|
+
),
|
|
860
|
+
defaultPermissions: projectedOptionalString(
|
|
861
|
+
config.default_permissions,
|
|
862
|
+
'default permission profile',
|
|
863
|
+
),
|
|
864
|
+
approvalPolicy: config.approval_policy == null
|
|
865
|
+
? null
|
|
866
|
+
: projectApprovalPolicy(config.approval_policy),
|
|
867
|
+
approvalsReviewer: projectedOptionalString(
|
|
868
|
+
config.approvals_reviewer,
|
|
869
|
+
'configured approvals reviewer',
|
|
870
|
+
),
|
|
871
|
+
webSearch: projectedOptionalString(config.web_search, 'web search policy'),
|
|
872
|
+
allowLoginShell: config.allow_login_shell ?? null,
|
|
873
|
+
shellEnvironmentInherit: projectedOptionalString(
|
|
874
|
+
shellEnvironment.inherit,
|
|
875
|
+
'shell environment inheritance',
|
|
876
|
+
),
|
|
877
|
+
permissionProfiles,
|
|
878
|
+
mcpServers: projectedObjectIndex(config.mcp_servers, 'MCP servers'),
|
|
879
|
+
plugins: projectedObjectIndex(config.plugins, 'plugins'),
|
|
880
|
+
modelProviders: projectedObjectIndex(
|
|
881
|
+
config.model_providers,
|
|
882
|
+
'model providers',
|
|
883
|
+
),
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
function projectConfigLayer(value) {
|
|
888
|
+
const layer = protocolObject(value, 'config layer');
|
|
889
|
+
const name = (
|
|
890
|
+
typeof layer.name === 'string'
|
|
891
|
+
? { type: layer.name }
|
|
892
|
+
: protocolObject(layer.name, 'config layer source')
|
|
893
|
+
);
|
|
894
|
+
return {
|
|
895
|
+
type: protocolRequiredString(name.type, 'config layer source type'),
|
|
896
|
+
version: protocolString(layer.version, 'config layer version'),
|
|
897
|
+
disabled: layer.disabledReason != null,
|
|
898
|
+
configSha256: jsonDigest(cloneBoundedJson(layer.config, 'config layer')),
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
function projectTurn(value, label) {
|
|
903
|
+
const turn = protocolObject(value, label);
|
|
904
|
+
if (!Array.isArray(turn.items) || turn.items.length > MAX_COMPLETED_ITEMS) {
|
|
905
|
+
throw new CodexAppServerError(
|
|
906
|
+
`app-server ${label} item list exceeded the size limit`,
|
|
907
|
+
'CODEX_PROTOCOL_ERROR',
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
const status = protocolRequiredString(turn.status, `${label} status`);
|
|
911
|
+
if (!['completed', 'interrupted', 'failed', 'inProgress'].includes(status)) {
|
|
912
|
+
throw new CodexAppServerError(
|
|
913
|
+
`app-server ${label} status is unsupported`,
|
|
914
|
+
'CODEX_PROTOCOL_ERROR',
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
return {
|
|
918
|
+
id: protocolRequiredString(turn.id, `${label} id`),
|
|
919
|
+
status,
|
|
920
|
+
items: turn.items.map((item) => {
|
|
921
|
+
const projected = protocolObject(item, `${label} item`);
|
|
922
|
+
return {
|
|
923
|
+
id: protocolRequiredString(projected.id, `${label} item id`),
|
|
924
|
+
type: protocolRequiredString(projected.type, `${label} item type`),
|
|
925
|
+
};
|
|
926
|
+
}),
|
|
927
|
+
error: turn.error == null ? null : { present: true },
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
function projectThread(value, label, ownedCwd, modelProvider) {
|
|
932
|
+
const thread = protocolObject(value, label);
|
|
933
|
+
const status = projectThreadStatus(thread.status, `${label} status`);
|
|
934
|
+
if (!Array.isArray(thread.turns) || thread.turns.length > MAX_COMPLETED_ITEMS) {
|
|
935
|
+
throw new CodexAppServerError(
|
|
936
|
+
`app-server ${label} turn list exceeded the size limit`,
|
|
937
|
+
'CODEX_PROTOCOL_ERROR',
|
|
938
|
+
);
|
|
939
|
+
}
|
|
940
|
+
for (const [key, maxBytes] of [
|
|
941
|
+
['cliVersion', MAX_ID_BYTES],
|
|
942
|
+
['cwd', MAX_TEXT_BYTES],
|
|
943
|
+
['id', MAX_ID_BYTES],
|
|
944
|
+
['modelProvider', MAX_ID_BYTES],
|
|
945
|
+
['preview', MAX_TEXT_BYTES],
|
|
946
|
+
['sessionId', MAX_ID_BYTES],
|
|
947
|
+
['source', MAX_ID_BYTES],
|
|
948
|
+
]) {
|
|
949
|
+
protocolString(thread[key], `${label} ${key}`, maxBytes);
|
|
950
|
+
}
|
|
951
|
+
if (
|
|
952
|
+
!Number.isSafeInteger(thread.createdAt)
|
|
953
|
+
|| !Number.isSafeInteger(thread.updatedAt)
|
|
954
|
+
|| typeof thread.ephemeral !== 'boolean'
|
|
955
|
+
|| thread.cwd !== ownedCwd
|
|
956
|
+
|| thread.modelProvider !== modelProvider
|
|
957
|
+
) {
|
|
958
|
+
throw new CodexAppServerError(
|
|
959
|
+
`app-server ${label} metadata is malformed`,
|
|
960
|
+
'CODEX_PROTOCOL_ERROR',
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
return {
|
|
964
|
+
id: protocolRequiredString(thread.id, `${label} id`),
|
|
965
|
+
status,
|
|
966
|
+
turns: thread.turns.map((turn) => projectTurn(turn, `${label} turn`)),
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
function projectApprovalPolicy(value) {
|
|
971
|
+
if (typeof value === 'string') {
|
|
972
|
+
if (!['untrusted', 'on-request', 'never'].includes(value)) {
|
|
973
|
+
throw new CodexAppServerError(
|
|
974
|
+
'app-server approval policy is unsupported',
|
|
975
|
+
'CODEX_PROTOCOL_ERROR',
|
|
976
|
+
);
|
|
977
|
+
}
|
|
978
|
+
return value;
|
|
979
|
+
}
|
|
980
|
+
const policy = protocolObject(value, 'approval policy');
|
|
981
|
+
const granular = protocolObject(policy.granular, 'granular approval policy');
|
|
982
|
+
for (const key of ['mcp_elicitations', 'rules', 'sandbox_approval']) {
|
|
983
|
+
if (typeof granular[key] !== 'boolean') {
|
|
984
|
+
throw new CodexAppServerError(
|
|
985
|
+
'app-server granular approval policy is malformed',
|
|
986
|
+
'CODEX_PROTOCOL_ERROR',
|
|
987
|
+
);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
return {
|
|
991
|
+
granular: {
|
|
992
|
+
mcp_elicitations: granular.mcp_elicitations,
|
|
993
|
+
rules: granular.rules,
|
|
994
|
+
sandbox_approval: granular.sandbox_approval,
|
|
995
|
+
request_permissions: granular.request_permissions === true,
|
|
996
|
+
skill_approval: granular.skill_approval === true,
|
|
997
|
+
},
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function projectSandbox(value, ownedCwd) {
|
|
1002
|
+
const sandbox = protocolObject(value, 'sandbox policy');
|
|
1003
|
+
const type = protocolRequiredString(sandbox.type, 'sandbox policy type');
|
|
1004
|
+
if (
|
|
1005
|
+
![
|
|
1006
|
+
'dangerFullAccess',
|
|
1007
|
+
'readOnly',
|
|
1008
|
+
'externalSandbox',
|
|
1009
|
+
'workspaceWrite',
|
|
1010
|
+
].includes(type)
|
|
1011
|
+
) {
|
|
1012
|
+
throw new CodexAppServerError(
|
|
1013
|
+
'app-server sandbox policy is unsupported',
|
|
1014
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1015
|
+
);
|
|
1016
|
+
}
|
|
1017
|
+
const projected = { type };
|
|
1018
|
+
if (sandbox.networkAccess !== undefined) {
|
|
1019
|
+
if (
|
|
1020
|
+
typeof sandbox.networkAccess !== 'boolean'
|
|
1021
|
+
&& !['restricted', 'enabled'].includes(sandbox.networkAccess)
|
|
1022
|
+
) {
|
|
1023
|
+
throw new CodexAppServerError(
|
|
1024
|
+
'app-server sandbox network policy is malformed',
|
|
1025
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1026
|
+
);
|
|
1027
|
+
}
|
|
1028
|
+
projected.networkAccess = sandbox.networkAccess;
|
|
1029
|
+
}
|
|
1030
|
+
if (type === 'workspaceWrite') {
|
|
1031
|
+
if (
|
|
1032
|
+
sandbox.writableRoots !== undefined
|
|
1033
|
+
&& !Array.isArray(sandbox.writableRoots)
|
|
1034
|
+
) {
|
|
1035
|
+
throw new CodexAppServerError(
|
|
1036
|
+
'app-server writable root list is malformed',
|
|
1037
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1038
|
+
);
|
|
1039
|
+
}
|
|
1040
|
+
const roots = sandbox.writableRoots ?? [];
|
|
1041
|
+
if (roots.length > 64) {
|
|
1042
|
+
throw new CodexAppServerError(
|
|
1043
|
+
'app-server writable root list is malformed',
|
|
1044
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
const validatedRoots = roots.map((root) => (
|
|
1048
|
+
protocolRequiredString(root, 'sandbox writable root', MAX_TEXT_BYTES)
|
|
1049
|
+
));
|
|
1050
|
+
if (validatedRoots.some((root) => (
|
|
1051
|
+
!path.isAbsolute(root)
|
|
1052
|
+
|| path.normalize(root) !== root
|
|
1053
|
+
|| !isWithin(ownedCwd, root)
|
|
1054
|
+
))) {
|
|
1055
|
+
throw new CodexAppServerError(
|
|
1056
|
+
'app-server writable root escaped the owned workspace',
|
|
1057
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1058
|
+
);
|
|
1059
|
+
}
|
|
1060
|
+
projected.writableRootCount = validatedRoots.length;
|
|
1061
|
+
projected.writableRootSha256 = validatedRoots
|
|
1062
|
+
.map((root) => createHash('sha256').update(root).digest('hex'))
|
|
1063
|
+
.sort();
|
|
1064
|
+
}
|
|
1065
|
+
return projected;
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
function projectRpcResult(method, value, ownedCwd) {
|
|
1069
|
+
const result = protocolObject(value, `${method} result`);
|
|
1070
|
+
if (method === 'initialize') {
|
|
1071
|
+
return {
|
|
1072
|
+
codexHome: protocolRequiredString(
|
|
1073
|
+
result.codexHome,
|
|
1074
|
+
'initialized credential home',
|
|
1075
|
+
MAX_TEXT_BYTES,
|
|
1076
|
+
),
|
|
1077
|
+
platformFamily: protocolRequiredString(
|
|
1078
|
+
result.platformFamily,
|
|
1079
|
+
'server platform family',
|
|
1080
|
+
),
|
|
1081
|
+
platformOs: protocolRequiredString(result.platformOs, 'server platform OS'),
|
|
1082
|
+
userAgent: protocolRequiredString(
|
|
1083
|
+
result.userAgent,
|
|
1084
|
+
'server user agent',
|
|
1085
|
+
4_096,
|
|
1086
|
+
),
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
if (method === 'config/read') {
|
|
1090
|
+
if (
|
|
1091
|
+
!Array.isArray(result.layers)
|
|
1092
|
+
|| result.layers.length > 64
|
|
1093
|
+
) {
|
|
1094
|
+
throw new CodexAppServerError(
|
|
1095
|
+
'app-server config layers must be an array',
|
|
1096
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1097
|
+
);
|
|
1098
|
+
}
|
|
1099
|
+
const origins = cloneBoundedJson(result.origins, 'config origins');
|
|
1100
|
+
return {
|
|
1101
|
+
config: projectEffectiveConfig(result.config),
|
|
1102
|
+
layers: result.layers.map(projectConfigLayer),
|
|
1103
|
+
originsSha256: jsonDigest(origins),
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
if (method === 'configRequirements/read') {
|
|
1107
|
+
const requirements = result.requirements == null
|
|
1108
|
+
? null
|
|
1109
|
+
: cloneBoundedJson(result.requirements, 'config requirements');
|
|
1110
|
+
return {
|
|
1111
|
+
requirements: requirements == null
|
|
1112
|
+
? null
|
|
1113
|
+
: {
|
|
1114
|
+
sha256: jsonDigest(requirements),
|
|
1115
|
+
keys: objectKeys(requirements, 'config requirements'),
|
|
1116
|
+
},
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
if (method === 'permissionProfile/list') {
|
|
1120
|
+
if (!Array.isArray(result.data) || result.data.length > 100) {
|
|
1121
|
+
throw new CodexAppServerError(
|
|
1122
|
+
'app-server permission profile page exceeded the size limit',
|
|
1123
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
return {
|
|
1127
|
+
data: result.data.map((profile) => {
|
|
1128
|
+
const source = protocolObject(profile, 'permission profile');
|
|
1129
|
+
if (typeof source.allowed !== 'boolean') {
|
|
1130
|
+
throw new CodexAppServerError(
|
|
1131
|
+
'app-server permission profile allowed flag is malformed',
|
|
1132
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1133
|
+
);
|
|
1134
|
+
}
|
|
1135
|
+
return {
|
|
1136
|
+
id: protocolRequiredString(source.id, 'permission profile id'),
|
|
1137
|
+
allowed: source.allowed,
|
|
1138
|
+
descriptionSha256: source.description == null
|
|
1139
|
+
? null
|
|
1140
|
+
: createHash('sha256')
|
|
1141
|
+
.update(protocolString(
|
|
1142
|
+
source.description,
|
|
1143
|
+
'permission profile description',
|
|
1144
|
+
MAX_TEXT_BYTES,
|
|
1145
|
+
))
|
|
1146
|
+
.digest('hex'),
|
|
1147
|
+
};
|
|
1148
|
+
}),
|
|
1149
|
+
nextCursor: protocolOptionalCursor(result.nextCursor),
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
if (method === 'account/read') {
|
|
1153
|
+
if (typeof result.requiresOpenaiAuth !== 'boolean') {
|
|
1154
|
+
throw new CodexAppServerError(
|
|
1155
|
+
'app-server account auth requirement is malformed',
|
|
1156
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1157
|
+
);
|
|
1158
|
+
}
|
|
1159
|
+
if (result.account == null) {
|
|
1160
|
+
return {
|
|
1161
|
+
account: null,
|
|
1162
|
+
requiresOpenaiAuth: result.requiresOpenaiAuth,
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
const account = protocolObject(result.account, 'account');
|
|
1166
|
+
const type = protocolRequiredString(account.type, 'account type');
|
|
1167
|
+
if (!['apiKey', 'chatgpt', 'amazonBedrock'].includes(type)) {
|
|
1168
|
+
throw new CodexAppServerError(
|
|
1169
|
+
'app-server account type is unsupported',
|
|
1170
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1171
|
+
);
|
|
1172
|
+
}
|
|
1173
|
+
if (type === 'chatgpt') {
|
|
1174
|
+
if (account.email !== null) {
|
|
1175
|
+
protocolString(account.email, 'ChatGPT account email', MAX_TEXT_BYTES);
|
|
1176
|
+
}
|
|
1177
|
+
const planType = protocolRequiredString(
|
|
1178
|
+
account.planType,
|
|
1179
|
+
'ChatGPT plan type',
|
|
1180
|
+
);
|
|
1181
|
+
if (![
|
|
1182
|
+
'free',
|
|
1183
|
+
'go',
|
|
1184
|
+
'plus',
|
|
1185
|
+
'pro',
|
|
1186
|
+
'prolite',
|
|
1187
|
+
'team',
|
|
1188
|
+
'self_serve_business_usage_based',
|
|
1189
|
+
'business',
|
|
1190
|
+
'enterprise_cbp_usage_based',
|
|
1191
|
+
'enterprise',
|
|
1192
|
+
'edu',
|
|
1193
|
+
'unknown',
|
|
1194
|
+
].includes(planType)) {
|
|
1195
|
+
throw new CodexAppServerError(
|
|
1196
|
+
'app-server ChatGPT plan type is unsupported',
|
|
1197
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
if (
|
|
1202
|
+
type === 'amazonBedrock'
|
|
1203
|
+
&& account.usesCodexManagedCredentials !== undefined
|
|
1204
|
+
&& typeof account.usesCodexManagedCredentials !== 'boolean'
|
|
1205
|
+
) {
|
|
1206
|
+
throw new CodexAppServerError(
|
|
1207
|
+
'app-server Bedrock credential flag is malformed',
|
|
1208
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1209
|
+
);
|
|
1210
|
+
}
|
|
1211
|
+
return {
|
|
1212
|
+
account: { type },
|
|
1213
|
+
requiresOpenaiAuth: result.requiresOpenaiAuth,
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
if (method === 'model/list') {
|
|
1217
|
+
if (!Array.isArray(result.data) || result.data.length > 100) {
|
|
1218
|
+
throw new CodexAppServerError(
|
|
1219
|
+
'app-server model page exceeded the size limit',
|
|
1220
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1221
|
+
);
|
|
1222
|
+
}
|
|
1223
|
+
return {
|
|
1224
|
+
data: result.data.map((model) => {
|
|
1225
|
+
const source = protocolObject(model, 'model');
|
|
1226
|
+
if (
|
|
1227
|
+
typeof source.hidden !== 'boolean'
|
|
1228
|
+
|| typeof source.isDefault !== 'boolean'
|
|
1229
|
+
|| !Array.isArray(source.supportedReasoningEfforts)
|
|
1230
|
+
|| source.supportedReasoningEfforts.length > 32
|
|
1231
|
+
) {
|
|
1232
|
+
throw new CodexAppServerError(
|
|
1233
|
+
'app-server model catalog entry is malformed',
|
|
1234
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1235
|
+
);
|
|
1236
|
+
}
|
|
1237
|
+
const projected = {
|
|
1238
|
+
id: protocolRequiredString(source.id, 'model id'),
|
|
1239
|
+
model: protocolRequiredString(source.model, 'model slug'),
|
|
1240
|
+
description: protocolString(
|
|
1241
|
+
source.description,
|
|
1242
|
+
'model description',
|
|
1243
|
+
MAX_TEXT_BYTES,
|
|
1244
|
+
),
|
|
1245
|
+
displayName: protocolString(source.displayName, 'model display name'),
|
|
1246
|
+
defaultReasoningEffort: protocolRequiredString(
|
|
1247
|
+
source.defaultReasoningEffort,
|
|
1248
|
+
'model default reasoning effort',
|
|
1249
|
+
),
|
|
1250
|
+
hidden: source.hidden,
|
|
1251
|
+
isDefault: source.isDefault,
|
|
1252
|
+
};
|
|
1253
|
+
projected.supportedReasoningEfforts = source.supportedReasoningEfforts
|
|
1254
|
+
.map((entry) => {
|
|
1255
|
+
const effort = protocolObject(entry, 'model reasoning effort');
|
|
1256
|
+
protocolString(
|
|
1257
|
+
effort.description,
|
|
1258
|
+
'model reasoning effort description',
|
|
1259
|
+
MAX_TEXT_BYTES,
|
|
1260
|
+
);
|
|
1261
|
+
return protocolRequiredString(
|
|
1262
|
+
effort.reasoningEffort,
|
|
1263
|
+
'model reasoning effort',
|
|
1264
|
+
);
|
|
1265
|
+
});
|
|
1266
|
+
if (
|
|
1267
|
+
new Set(projected.supportedReasoningEfforts).size
|
|
1268
|
+
!== projected.supportedReasoningEfforts.length
|
|
1269
|
+
||
|
|
1270
|
+
!projected.supportedReasoningEfforts
|
|
1271
|
+
.includes(projected.defaultReasoningEffort)
|
|
1272
|
+
) {
|
|
1273
|
+
throw new CodexAppServerError(
|
|
1274
|
+
'app-server model default reasoning effort is unsupported',
|
|
1275
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1276
|
+
);
|
|
1277
|
+
}
|
|
1278
|
+
return projected;
|
|
1279
|
+
}),
|
|
1280
|
+
nextCursor: protocolOptionalCursor(result.nextCursor),
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
if (method === 'thread/start' || method === 'thread/resume') {
|
|
1284
|
+
if (
|
|
1285
|
+
result.cwd !== ownedCwd
|
|
1286
|
+
|| !['user', 'auto_review', 'guardian_subagent']
|
|
1287
|
+
.includes(result.approvalsReviewer)
|
|
1288
|
+
) {
|
|
1289
|
+
throw new CodexAppServerError(
|
|
1290
|
+
'app-server thread policy response is inconsistent',
|
|
1291
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1292
|
+
);
|
|
1293
|
+
}
|
|
1294
|
+
const projected = {
|
|
1295
|
+
cwd: ownedCwd,
|
|
1296
|
+
model: protocolRequiredString(result.model, 'thread model'),
|
|
1297
|
+
modelProvider: protocolRequiredString(
|
|
1298
|
+
result.modelProvider,
|
|
1299
|
+
'thread model provider',
|
|
1300
|
+
),
|
|
1301
|
+
approvalPolicy: projectApprovalPolicy(result.approvalPolicy),
|
|
1302
|
+
approvalsReviewer: result.approvalsReviewer,
|
|
1303
|
+
sandbox: projectSandbox(result.sandbox, ownedCwd),
|
|
1304
|
+
};
|
|
1305
|
+
projected.thread = projectThread(
|
|
1306
|
+
result.thread,
|
|
1307
|
+
'thread',
|
|
1308
|
+
ownedCwd,
|
|
1309
|
+
projected.modelProvider,
|
|
1310
|
+
);
|
|
1311
|
+
if (result.reasoningEffort != null) {
|
|
1312
|
+
projected.reasoningEffort = protocolRequiredString(
|
|
1313
|
+
result.reasoningEffort,
|
|
1314
|
+
'thread reasoning effort',
|
|
1315
|
+
);
|
|
1316
|
+
}
|
|
1317
|
+
if (result.activePermissionProfile != null) {
|
|
1318
|
+
const profile = protocolObject(
|
|
1319
|
+
result.activePermissionProfile,
|
|
1320
|
+
'active permission profile',
|
|
1321
|
+
);
|
|
1322
|
+
projected.activePermissionProfile = {
|
|
1323
|
+
id: protocolRequiredString(profile.id, 'permission profile id'),
|
|
1324
|
+
extends: profile.extends == null
|
|
1325
|
+
? null
|
|
1326
|
+
: protocolRequiredString(profile.extends, 'permission profile parent'),
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
return projected;
|
|
1330
|
+
}
|
|
1331
|
+
if (method === 'turn/start') {
|
|
1332
|
+
return { turn: projectTurn(result.turn, 'started turn') };
|
|
1333
|
+
}
|
|
1334
|
+
if (method === 'turn/steer') {
|
|
1335
|
+
return {
|
|
1336
|
+
turnId: protocolRequiredString(result.turnId, 'steered turn id'),
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
if (
|
|
1340
|
+
method === 'turn/interrupt'
|
|
1341
|
+
|| method === 'thread/backgroundTerminals/clean'
|
|
1342
|
+
) {
|
|
1343
|
+
if (Object.keys(result).length !== 0) {
|
|
1344
|
+
throw new CodexAppServerError(
|
|
1345
|
+
`app-server ${method} returned an unexpected result`,
|
|
1346
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1347
|
+
);
|
|
1348
|
+
}
|
|
1349
|
+
return {};
|
|
1350
|
+
}
|
|
1351
|
+
if (method === 'thread/backgroundTerminals/list') {
|
|
1352
|
+
if (!Array.isArray(result.data) || result.data.length > 100) {
|
|
1353
|
+
throw new CodexAppServerError(
|
|
1354
|
+
'app-server terminal page exceeded the size limit',
|
|
1355
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1356
|
+
);
|
|
1357
|
+
}
|
|
1358
|
+
return {
|
|
1359
|
+
count: result.data.length,
|
|
1360
|
+
nextCursor: protocolOptionalCursor(result.nextCursor),
|
|
1361
|
+
};
|
|
1362
|
+
}
|
|
1363
|
+
throw new CodexAppServerError(
|
|
1364
|
+
'app-server result projection is missing',
|
|
1365
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1366
|
+
);
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
function projectRpcError(value) {
|
|
1370
|
+
const error = protocolObject(value, 'RPC error');
|
|
1371
|
+
if (
|
|
1372
|
+
!Number.isSafeInteger(error.code)
|
|
1373
|
+
|| Object.keys(error).some((key) => !['code', 'message', 'data'].includes(key))
|
|
1374
|
+
) {
|
|
1375
|
+
throw new CodexAppServerError(
|
|
1376
|
+
'app-server returned a malformed RPC error',
|
|
1377
|
+
'CODEX_PROTOCOL_ERROR',
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
return {
|
|
1381
|
+
code: error.code,
|
|
1382
|
+
message: protocolRequiredString(error.message, 'RPC error message', 4_096),
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
function projectTextInput(input) {
|
|
1387
|
+
if (!Array.isArray(input) || input.length === 0 || input.length > 64) {
|
|
1388
|
+
throw new CodexAppServerError(
|
|
1389
|
+
'app-server input list exceeded the supported bounds',
|
|
1390
|
+
'CODEX_RPC_REJECTED',
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1393
|
+
return input.map((item) => {
|
|
1394
|
+
plainObject(item, 'input item');
|
|
1395
|
+
if (
|
|
1396
|
+
Object.keys(item).some((key) => !['type', 'text'].includes(key))
|
|
1397
|
+
|| item.type !== 'text'
|
|
1398
|
+
) {
|
|
1399
|
+
throw new CodexAppServerError(
|
|
1400
|
+
'app-server input item type is unsupported',
|
|
1401
|
+
'CODEX_RPC_REJECTED',
|
|
1402
|
+
);
|
|
1403
|
+
}
|
|
1404
|
+
return {
|
|
1405
|
+
type: 'text',
|
|
1406
|
+
text: boundedRequiredString(item.text, 'input text', 256 * 1024),
|
|
1407
|
+
};
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
function projectRequestParams(method, params, spec, ownedCwd) {
|
|
1412
|
+
if (spec.params === 'omitted') {
|
|
1413
|
+
if (params !== undefined) {
|
|
1414
|
+
throw new CodexAppServerError(
|
|
1415
|
+
`app-server ${method} parameters must be omitted`,
|
|
1416
|
+
'CODEX_RPC_REJECTED',
|
|
1417
|
+
);
|
|
1418
|
+
}
|
|
1419
|
+
return undefined;
|
|
1420
|
+
}
|
|
1421
|
+
plainObject(params, `${method} parameters`);
|
|
1422
|
+
const allowed = new Set([...spec.required, ...spec.optional]);
|
|
1423
|
+
for (const key of Object.keys(params)) {
|
|
1424
|
+
if (FORBIDDEN_REQUEST_FIELDS.has(key)) {
|
|
1425
|
+
throw new CodexAppServerError(
|
|
1426
|
+
`app-server ${method} forbids ${key}`,
|
|
1427
|
+
'CODEX_RPC_REJECTED',
|
|
1428
|
+
);
|
|
1429
|
+
}
|
|
1430
|
+
if (!allowed.has(key)) {
|
|
1431
|
+
throw new CodexAppServerError(
|
|
1432
|
+
`app-server ${method} received an unexpected parameter`,
|
|
1433
|
+
'CODEX_RPC_REJECTED',
|
|
1434
|
+
);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
for (const key of spec.required) {
|
|
1438
|
+
if (!Object.hasOwn(params, key)) {
|
|
1439
|
+
throw new CodexAppServerError(
|
|
1440
|
+
`app-server ${method} omitted a required parameter`,
|
|
1441
|
+
'CODEX_RPC_REJECTED',
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
const cursor = () => {
|
|
1446
|
+
if (!Object.hasOwn(params, 'cursor')) return {};
|
|
1447
|
+
return { cursor: boundedRequiredString(params.cursor, 'pagination cursor') };
|
|
1448
|
+
};
|
|
1449
|
+
const threadId = () => boundedRequiredString(params.threadId, 'thread id');
|
|
1450
|
+
const clientMessageId = () => (
|
|
1451
|
+
Object.hasOwn(params, 'clientUserMessageId')
|
|
1452
|
+
? {
|
|
1453
|
+
clientUserMessageId: boundedRequiredString(
|
|
1454
|
+
params.clientUserMessageId,
|
|
1455
|
+
'client user message id',
|
|
1456
|
+
),
|
|
1457
|
+
}
|
|
1458
|
+
: {}
|
|
1459
|
+
);
|
|
1460
|
+
if (method === 'initialize') {
|
|
1461
|
+
plainObject(params.clientInfo, 'initialize clientInfo');
|
|
1462
|
+
plainObject(params.capabilities, 'initialize capabilities');
|
|
1463
|
+
if (
|
|
1464
|
+
params.capabilities.experimentalApi !== true
|
|
1465
|
+
|| Object.keys(params.capabilities).length !== 1
|
|
1466
|
+
) {
|
|
1467
|
+
throw new CodexAppServerError(
|
|
1468
|
+
'app-server initialize capabilities changed',
|
|
1469
|
+
'CODEX_RPC_REJECTED',
|
|
1470
|
+
);
|
|
1471
|
+
}
|
|
1472
|
+
return {
|
|
1473
|
+
clientInfo: {
|
|
1474
|
+
name: boundedRequiredString(params.clientInfo.name, 'client name'),
|
|
1475
|
+
title: boundedRequiredString(params.clientInfo.title, 'client title'),
|
|
1476
|
+
version: boundedRequiredString(params.clientInfo.version, 'client version'),
|
|
1477
|
+
},
|
|
1478
|
+
capabilities: { experimentalApi: true },
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
if (method === 'config/read') {
|
|
1482
|
+
if (params.cwd !== ownedCwd || params.includeLayers !== true) {
|
|
1483
|
+
throw new CodexAppServerError(
|
|
1484
|
+
'app-server config read must target the owned workspace and layers',
|
|
1485
|
+
'CODEX_RPC_REJECTED',
|
|
1486
|
+
);
|
|
1487
|
+
}
|
|
1488
|
+
return { cwd: ownedCwd, includeLayers: true };
|
|
1489
|
+
}
|
|
1490
|
+
if (method === 'permissionProfile/list') {
|
|
1491
|
+
if (params.cwd !== ownedCwd) {
|
|
1492
|
+
throw new CodexAppServerError(
|
|
1493
|
+
'app-server permission profile list changed workspace',
|
|
1494
|
+
'CODEX_RPC_REJECTED',
|
|
1495
|
+
);
|
|
1496
|
+
}
|
|
1497
|
+
return { cwd: ownedCwd, ...cursor() };
|
|
1498
|
+
}
|
|
1499
|
+
if (method === 'account/read') {
|
|
1500
|
+
if (params.refreshToken !== false) {
|
|
1501
|
+
throw new CodexAppServerError(
|
|
1502
|
+
'app-server account read cannot refresh credentials',
|
|
1503
|
+
'CODEX_RPC_REJECTED',
|
|
1504
|
+
);
|
|
1505
|
+
}
|
|
1506
|
+
return { refreshToken: false };
|
|
1507
|
+
}
|
|
1508
|
+
if (method === 'model/list') {
|
|
1509
|
+
if (
|
|
1510
|
+
params.includeHidden !== false
|
|
1511
|
+
|| !Number.isSafeInteger(params.limit)
|
|
1512
|
+
|| params.limit < 1
|
|
1513
|
+
|| params.limit > 100
|
|
1514
|
+
) {
|
|
1515
|
+
throw new CodexAppServerError(
|
|
1516
|
+
'app-server model list parameters are outside policy',
|
|
1517
|
+
'CODEX_RPC_REJECTED',
|
|
1518
|
+
);
|
|
1519
|
+
}
|
|
1520
|
+
return { includeHidden: false, limit: params.limit, ...cursor() };
|
|
1521
|
+
}
|
|
1522
|
+
if (method === 'thread/start') {
|
|
1523
|
+
if (params.cwd !== ownedCwd) {
|
|
1524
|
+
throw new CodexAppServerError(
|
|
1525
|
+
'app-server thread start changed workspace',
|
|
1526
|
+
'CODEX_RPC_REJECTED',
|
|
1527
|
+
);
|
|
1528
|
+
}
|
|
1529
|
+
return {
|
|
1530
|
+
cwd: ownedCwd,
|
|
1531
|
+
model: boundedRequiredString(params.model, 'model'),
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
if (method === 'thread/resume') return { threadId: threadId() };
|
|
1535
|
+
if (method === 'turn/start') {
|
|
1536
|
+
const projected = {
|
|
1537
|
+
threadId: threadId(),
|
|
1538
|
+
input: projectTextInput(params.input),
|
|
1539
|
+
...clientMessageId(),
|
|
1540
|
+
};
|
|
1541
|
+
if (Object.hasOwn(params, 'model')) {
|
|
1542
|
+
projected.model = boundedRequiredString(params.model, 'model');
|
|
1543
|
+
}
|
|
1544
|
+
if (Object.hasOwn(params, 'effort')) {
|
|
1545
|
+
const effort = boundedRequiredString(params.effort, 'reasoning effort');
|
|
1546
|
+
if (!['low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(effort)) {
|
|
1547
|
+
throw new CodexAppServerError(
|
|
1548
|
+
'app-server reasoning effort is unsupported',
|
|
1549
|
+
'CODEX_RPC_REJECTED',
|
|
1550
|
+
);
|
|
1551
|
+
}
|
|
1552
|
+
projected.effort = effort;
|
|
1553
|
+
}
|
|
1554
|
+
return projected;
|
|
1555
|
+
}
|
|
1556
|
+
if (method === 'turn/steer') {
|
|
1557
|
+
return {
|
|
1558
|
+
threadId: threadId(),
|
|
1559
|
+
expectedTurnId: boundedRequiredString(
|
|
1560
|
+
params.expectedTurnId,
|
|
1561
|
+
'expected turn id',
|
|
1562
|
+
),
|
|
1563
|
+
input: projectTextInput(params.input),
|
|
1564
|
+
...clientMessageId(),
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
if (method === 'turn/interrupt') {
|
|
1568
|
+
return {
|
|
1569
|
+
threadId: threadId(),
|
|
1570
|
+
turnId: boundedRequiredString(params.turnId, 'turn id'),
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
if (method === 'thread/backgroundTerminals/list') {
|
|
1574
|
+
const projected = { threadId: threadId(), ...cursor() };
|
|
1575
|
+
if (Object.hasOwn(params, 'limit')) {
|
|
1576
|
+
if (
|
|
1577
|
+
!Number.isSafeInteger(params.limit)
|
|
1578
|
+
|| params.limit < 1
|
|
1579
|
+
|| params.limit > 100
|
|
1580
|
+
) {
|
|
1581
|
+
throw new CodexAppServerError(
|
|
1582
|
+
'app-server terminal page limit is outside policy',
|
|
1583
|
+
'CODEX_RPC_REJECTED',
|
|
1584
|
+
);
|
|
1585
|
+
}
|
|
1586
|
+
projected.limit = params.limit;
|
|
1587
|
+
}
|
|
1588
|
+
return projected;
|
|
1589
|
+
}
|
|
1590
|
+
if (method === 'thread/backgroundTerminals/clean') {
|
|
1591
|
+
return { threadId: threadId() };
|
|
1592
|
+
}
|
|
1593
|
+
throw new CodexAppServerError(
|
|
1594
|
+
'app-server request projection is missing',
|
|
1595
|
+
'CODEX_RPC_REJECTED',
|
|
1596
|
+
);
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
function mutationDeliveryError(pending, cause) {
|
|
1600
|
+
const code = pending.writeAttempted
|
|
1601
|
+
? 'CODEX_RPC_OUTCOME_UNKNOWN'
|
|
1602
|
+
: 'CODEX_RPC_NOT_SENT';
|
|
1603
|
+
const message = pending.writeAttempted
|
|
1604
|
+
? `app-server ${pending.method} outcome is unknown`
|
|
1605
|
+
: `app-server ${pending.method} was not sent`;
|
|
1606
|
+
return new CodexAppServerError(message, code, { cause });
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
function sameFingerprint(left, right) {
|
|
1610
|
+
return Boolean(
|
|
1611
|
+
left
|
|
1612
|
+
&& right
|
|
1613
|
+
&& Object.keys(left).every((key) => left[key] === right[key])
|
|
1614
|
+
&& Object.keys(right).every((key) => left[key] === right[key]),
|
|
1615
|
+
);
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
function sameOptionalFingerprint(left, right) {
|
|
1619
|
+
return (
|
|
1620
|
+
(left === null && right === null)
|
|
1621
|
+
|| sameFingerprint(left, right)
|
|
1622
|
+
);
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
class CodexAppServerClient extends EventEmitter {
|
|
1626
|
+
constructor(options = {}) {
|
|
1627
|
+
super();
|
|
1628
|
+
for (const key of Object.keys(options)) {
|
|
1629
|
+
if (!CONSTRUCTOR_KEYS.has(key)) {
|
|
1630
|
+
throw new TypeError(`CodexAppServerClient: unknown option ${key}`);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
const {
|
|
1634
|
+
binary,
|
|
1635
|
+
cwd,
|
|
1636
|
+
codexHome,
|
|
1637
|
+
env = process.env,
|
|
1638
|
+
spawnFn = spawn,
|
|
1639
|
+
killFn = process.kill.bind(process),
|
|
1640
|
+
setTimer = setTimeout,
|
|
1641
|
+
clearTimer = clearTimeout,
|
|
1642
|
+
requestIdFactory = null,
|
|
1643
|
+
onNotification = async () => {},
|
|
1644
|
+
onFault,
|
|
1645
|
+
attestBinaryFn = attestPinnedCodexBinary,
|
|
1646
|
+
attestCodexHomeFn = attestPinnedCodexHome,
|
|
1647
|
+
expectedConfigSha256,
|
|
1648
|
+
requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
|
|
1649
|
+
sinkTimeoutMs = DEFAULT_SINK_TIMEOUT_MS,
|
|
1650
|
+
closeGraceMs = DEFAULT_CLOSE_GRACE_MS,
|
|
1651
|
+
closeKillMs = DEFAULT_CLOSE_KILL_MS,
|
|
1652
|
+
maxLineBytes = DEFAULT_MAX_LINE_BYTES,
|
|
1653
|
+
maxStderrBytes = DEFAULT_MAX_STDERR_BYTES,
|
|
1654
|
+
maxPendingRequests = DEFAULT_MAX_PENDING_REQUESTS,
|
|
1655
|
+
maxUsedRequestIds = DEFAULT_MAX_USED_REQUEST_IDS,
|
|
1656
|
+
maxQueuedLines = DEFAULT_MAX_QUEUED_LINES,
|
|
1657
|
+
maxQueuedBytes = DEFAULT_MAX_QUEUED_BYTES,
|
|
1658
|
+
} = options;
|
|
1659
|
+
assertAbsolute(binary, 'binary');
|
|
1660
|
+
assertAbsolute(cwd, 'cwd');
|
|
1661
|
+
assertAbsolute(codexHome, 'codexHome');
|
|
1662
|
+
if (
|
|
1663
|
+
typeof expectedConfigSha256 !== 'string'
|
|
1664
|
+
|| !/^[a-f0-9]{64}$/.test(expectedConfigSha256)
|
|
1665
|
+
) {
|
|
1666
|
+
throw new TypeError(
|
|
1667
|
+
'CodexAppServerClient: expectedConfigSha256 must be a lowercase SHA-256',
|
|
1668
|
+
);
|
|
1669
|
+
}
|
|
1670
|
+
if (process.platform === 'win32') {
|
|
1671
|
+
throw new CodexAppServerError(
|
|
1672
|
+
'The native Codex app-server beta does not support Windows',
|
|
1673
|
+
'CODEX_UNSUPPORTED_PLATFORM',
|
|
1674
|
+
);
|
|
1675
|
+
}
|
|
1676
|
+
for (const [value, label] of [
|
|
1677
|
+
[cwd, 'cwd'],
|
|
1678
|
+
[codexHome, 'codexHome'],
|
|
1679
|
+
]) {
|
|
1680
|
+
if (realpathSync(value) !== value) {
|
|
1681
|
+
throw new TypeError(
|
|
1682
|
+
`CodexAppServerClient: ${label} must be a canonical path`,
|
|
1683
|
+
);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
const workspaceStat = lstatSync(cwd);
|
|
1687
|
+
const credentialStat = lstatSync(codexHome);
|
|
1688
|
+
if (!workspaceStat.isDirectory()) {
|
|
1689
|
+
throw new TypeError('CodexAppServerClient: cwd must be a directory');
|
|
1690
|
+
}
|
|
1691
|
+
if (
|
|
1692
|
+
!credentialStat.isDirectory()
|
|
1693
|
+
|| credentialStat.isSymbolicLink()
|
|
1694
|
+
|| (
|
|
1695
|
+
typeof process.getuid === 'function'
|
|
1696
|
+
&& credentialStat.uid !== process.getuid()
|
|
1697
|
+
)
|
|
1698
|
+
|| (credentialStat.mode & 0o777) !== 0o700
|
|
1699
|
+
|| isWithin(cwd, codexHome)
|
|
1700
|
+
|| isWithin(codexHome, cwd)
|
|
1701
|
+
) {
|
|
1702
|
+
throw new TypeError(
|
|
1703
|
+
'CodexAppServerClient: codexHome must be a separate owned 0700 directory',
|
|
1704
|
+
);
|
|
1705
|
+
}
|
|
1706
|
+
for (const [value, label] of [
|
|
1707
|
+
[spawnFn, 'spawnFn'],
|
|
1708
|
+
[killFn, 'killFn'],
|
|
1709
|
+
[setTimer, 'setTimer'],
|
|
1710
|
+
[clearTimer, 'clearTimer'],
|
|
1711
|
+
[onNotification, 'onNotification'],
|
|
1712
|
+
[onFault, 'onFault'],
|
|
1713
|
+
[attestBinaryFn, 'attestBinaryFn'],
|
|
1714
|
+
[attestCodexHomeFn, 'attestCodexHomeFn'],
|
|
1715
|
+
]) {
|
|
1716
|
+
if (typeof value !== 'function') {
|
|
1717
|
+
throw new TypeError(`CodexAppServerClient: ${label} must be a function`);
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
if (requestIdFactory !== null && typeof requestIdFactory !== 'function') {
|
|
1721
|
+
throw new TypeError('CodexAppServerClient: requestIdFactory must be a function');
|
|
1722
|
+
}
|
|
1723
|
+
for (const [value, label] of [
|
|
1724
|
+
[requestTimeoutMs, 'requestTimeoutMs'],
|
|
1725
|
+
[sinkTimeoutMs, 'sinkTimeoutMs'],
|
|
1726
|
+
[closeGraceMs, 'closeGraceMs'],
|
|
1727
|
+
[closeKillMs, 'closeKillMs'],
|
|
1728
|
+
[maxLineBytes, 'maxLineBytes'],
|
|
1729
|
+
[maxStderrBytes, 'maxStderrBytes'],
|
|
1730
|
+
[maxPendingRequests, 'maxPendingRequests'],
|
|
1731
|
+
[maxUsedRequestIds, 'maxUsedRequestIds'],
|
|
1732
|
+
[maxQueuedLines, 'maxQueuedLines'],
|
|
1733
|
+
[maxQueuedBytes, 'maxQueuedBytes'],
|
|
1734
|
+
]) {
|
|
1735
|
+
assertPositiveInteger(value, label);
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
Object.assign(this, {
|
|
1739
|
+
binary,
|
|
1740
|
+
cwd,
|
|
1741
|
+
codexHome,
|
|
1742
|
+
spawnFn,
|
|
1743
|
+
killFn,
|
|
1744
|
+
setTimer,
|
|
1745
|
+
clearTimer,
|
|
1746
|
+
requestIdFactory,
|
|
1747
|
+
onNotification,
|
|
1748
|
+
onFault,
|
|
1749
|
+
attestBinaryFn,
|
|
1750
|
+
attestCodexHomeFn,
|
|
1751
|
+
expectedConfigSha256,
|
|
1752
|
+
requestTimeoutMs,
|
|
1753
|
+
sinkTimeoutMs,
|
|
1754
|
+
closeGraceMs,
|
|
1755
|
+
closeKillMs,
|
|
1756
|
+
maxLineBytes,
|
|
1757
|
+
maxStderrBytes,
|
|
1758
|
+
maxPendingRequests,
|
|
1759
|
+
maxUsedRequestIds,
|
|
1760
|
+
maxQueuedLines,
|
|
1761
|
+
maxQueuedBytes,
|
|
1762
|
+
});
|
|
1763
|
+
this.env = buildCodexAppServerEnv(codexHome, env);
|
|
1764
|
+
this.state = 'new';
|
|
1765
|
+
this.child = null;
|
|
1766
|
+
this.startPromise = null;
|
|
1767
|
+
this.closePromise = null;
|
|
1768
|
+
this.exitPromise = null;
|
|
1769
|
+
this.exitInfo = null;
|
|
1770
|
+
this.protocolError = null;
|
|
1771
|
+
this.faultPromise = null;
|
|
1772
|
+
this.faultOutcome = null;
|
|
1773
|
+
this.faultWaitPromise = new Promise((resolve, reject) => {
|
|
1774
|
+
this.resolveFaultWait = resolve;
|
|
1775
|
+
this.rejectFaultWait = reject;
|
|
1776
|
+
});
|
|
1777
|
+
this.faultWaitPromise.catch(() => {});
|
|
1778
|
+
this.sinkGeneration = 0;
|
|
1779
|
+
this.activeSinkControllers = new Set();
|
|
1780
|
+
this.pending = new Map();
|
|
1781
|
+
this.usedRequestIds = new Set();
|
|
1782
|
+
this.nextRequestId = 1;
|
|
1783
|
+
this.stdoutBuffer = '';
|
|
1784
|
+
this.stdoutDecoder = new StringDecoder('utf8');
|
|
1785
|
+
this.stderrBytes = 0;
|
|
1786
|
+
this.messageChain = Promise.resolve();
|
|
1787
|
+
this.queuedLineCount = 0;
|
|
1788
|
+
this.queuedLineBytes = 0;
|
|
1789
|
+
this.stdoutPaused = false;
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
start() {
|
|
1793
|
+
if (this.startPromise) return this.startPromise;
|
|
1794
|
+
this.startPromise = this._start();
|
|
1795
|
+
return this.startPromise;
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
async _start() {
|
|
1799
|
+
if (this.state !== 'new') {
|
|
1800
|
+
throw new CodexAppServerError(
|
|
1801
|
+
'app-server start is only valid once',
|
|
1802
|
+
'CODEX_CLIENT_STATE',
|
|
1803
|
+
);
|
|
1804
|
+
}
|
|
1805
|
+
this.state = 'starting';
|
|
1806
|
+
const args = ['app-server', '--strict-config', '--stdio'];
|
|
1807
|
+
const command = process.execPath;
|
|
1808
|
+
const commandArgs = [SUPERVISOR_PATH, this.binary, ...args];
|
|
1809
|
+
try {
|
|
1810
|
+
const [attestation, homeAttestation] = await Promise.all([
|
|
1811
|
+
this.attestBinaryFn(this.binary),
|
|
1812
|
+
this.attestCodexHomeFn(
|
|
1813
|
+
this.codexHome,
|
|
1814
|
+
this.expectedConfigSha256,
|
|
1815
|
+
),
|
|
1816
|
+
]);
|
|
1817
|
+
if (
|
|
1818
|
+
!attestation
|
|
1819
|
+
|| attestation.path !== this.binary
|
|
1820
|
+
|| attestation.sha256 !== protocolSchema.binarySha256
|
|
1821
|
+
|| attestation.version !== protocolSchema.cliVersion
|
|
1822
|
+
) {
|
|
1823
|
+
throw new CodexAppServerError(
|
|
1824
|
+
'pinned Codex binary attestation was inconsistent',
|
|
1825
|
+
'CODEX_BINARY_MISMATCH',
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
if (
|
|
1829
|
+
!homeAttestation
|
|
1830
|
+
|| homeAttestation.path !== this.codexHome
|
|
1831
|
+
|| homeAttestation.configSha256 !== this.expectedConfigSha256
|
|
1832
|
+
|| !homeAttestation.configFingerprint
|
|
1833
|
+
) {
|
|
1834
|
+
throw new CodexAppServerError(
|
|
1835
|
+
'pinned Codex credential home attestation was inconsistent',
|
|
1836
|
+
'CODEX_CONFIG_MISMATCH',
|
|
1837
|
+
);
|
|
1838
|
+
}
|
|
1839
|
+
if (this.state !== 'starting') {
|
|
1840
|
+
throw new CodexAppServerError(
|
|
1841
|
+
'app-server start was cancelled before spawn',
|
|
1842
|
+
'CODEX_CLIENT_CLOSED',
|
|
1843
|
+
);
|
|
1844
|
+
}
|
|
1845
|
+
this.child = this.spawnFn(command, commandArgs, {
|
|
1846
|
+
cwd: this.cwd,
|
|
1847
|
+
env: this.env,
|
|
1848
|
+
detached: process.platform !== 'win32',
|
|
1849
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1850
|
+
});
|
|
1851
|
+
this._attachChild();
|
|
1852
|
+
if (
|
|
1853
|
+
attestation.fingerprint
|
|
1854
|
+
&& !sameFingerprint(attestation.fingerprint, binaryFingerprint(this.binary))
|
|
1855
|
+
) {
|
|
1856
|
+
throw new CodexAppServerError(
|
|
1857
|
+
'pinned Codex binary changed during spawn',
|
|
1858
|
+
'CODEX_BINARY_MISMATCH',
|
|
1859
|
+
);
|
|
1860
|
+
}
|
|
1861
|
+
const afterSpawnHome = await this.attestCodexHomeFn(
|
|
1862
|
+
this.codexHome,
|
|
1863
|
+
this.expectedConfigSha256,
|
|
1864
|
+
);
|
|
1865
|
+
if (
|
|
1866
|
+
!afterSpawnHome
|
|
1867
|
+
|| afterSpawnHome.path !== this.codexHome
|
|
1868
|
+
|| afterSpawnHome.configSha256 !== this.expectedConfigSha256
|
|
1869
|
+
|| !sameFingerprint(
|
|
1870
|
+
homeAttestation.configFingerprint,
|
|
1871
|
+
afterSpawnHome.configFingerprint,
|
|
1872
|
+
)
|
|
1873
|
+
|| !sameOptionalFingerprint(
|
|
1874
|
+
homeAttestation.authFingerprint,
|
|
1875
|
+
afterSpawnHome.authFingerprint,
|
|
1876
|
+
)
|
|
1877
|
+
) {
|
|
1878
|
+
throw new CodexAppServerError(
|
|
1879
|
+
'pinned Codex credential state changed during spawn',
|
|
1880
|
+
'CODEX_CONFIG_MISMATCH',
|
|
1881
|
+
);
|
|
1882
|
+
}
|
|
1883
|
+
this.state = 'initializing';
|
|
1884
|
+
const result = await this._request('initialize', {
|
|
1885
|
+
clientInfo: {
|
|
1886
|
+
name: 'orchestra',
|
|
1887
|
+
title: 'Orchestra',
|
|
1888
|
+
version: '0.5.0',
|
|
1889
|
+
},
|
|
1890
|
+
capabilities: { experimentalApi: true },
|
|
1891
|
+
}, { internal: true });
|
|
1892
|
+
if (result?.codexHome !== this.codexHome) {
|
|
1893
|
+
throw new CodexAppServerError(
|
|
1894
|
+
'app-server initialized with an unexpected credential home',
|
|
1895
|
+
'CODEX_CONFIG_MISMATCH',
|
|
1896
|
+
);
|
|
1897
|
+
}
|
|
1898
|
+
await this._writeMessage({ method: 'initialized' });
|
|
1899
|
+
this.state = 'ready';
|
|
1900
|
+
return this;
|
|
1901
|
+
} catch (error) {
|
|
1902
|
+
this._fault(error);
|
|
1903
|
+
throw error;
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
_attachChild() {
|
|
1908
|
+
const child = this.child;
|
|
1909
|
+
if (
|
|
1910
|
+
!child
|
|
1911
|
+
|| !child.stdin
|
|
1912
|
+
|| !child.stdout
|
|
1913
|
+
|| !child.stderr
|
|
1914
|
+
|| typeof child.once !== 'function'
|
|
1915
|
+
) {
|
|
1916
|
+
throw new TypeError('CodexAppServerClient: spawnFn returned an invalid child');
|
|
1917
|
+
}
|
|
1918
|
+
this.exitPromise = new Promise((resolve) => {
|
|
1919
|
+
let observed = false;
|
|
1920
|
+
const observeExit = (code, signal) => {
|
|
1921
|
+
if (observed) return;
|
|
1922
|
+
observed = true;
|
|
1923
|
+
this.exitInfo = { code, signal };
|
|
1924
|
+
try { this.emit('exit', this.exitInfo); } catch {}
|
|
1925
|
+
};
|
|
1926
|
+
child.once('exit', observeExit);
|
|
1927
|
+
child.once('close', (code, signal) => {
|
|
1928
|
+
observeExit(code, signal);
|
|
1929
|
+
resolve(this.exitInfo);
|
|
1930
|
+
if (this.state !== 'closing' && this.state !== 'closed') {
|
|
1931
|
+
this._enqueueTerminalFault(new CodexAppServerError(
|
|
1932
|
+
'app-server exited unexpectedly',
|
|
1933
|
+
'CODEX_PROCESS_EXITED',
|
|
1934
|
+
));
|
|
1935
|
+
}
|
|
1936
|
+
});
|
|
1937
|
+
});
|
|
1938
|
+
child.stdout.on('data', (chunk) => this._onStdoutData(chunk));
|
|
1939
|
+
child.stdout.once('end', () => this._onStdoutEnd());
|
|
1940
|
+
child.stdout.once('error', (error) => this._transportFault(
|
|
1941
|
+
'app-server stdout failed',
|
|
1942
|
+
error,
|
|
1943
|
+
));
|
|
1944
|
+
child.stderr.on('data', (chunk) => this._onStderrData(chunk));
|
|
1945
|
+
child.stderr.once('error', (error) => this._transportFault(
|
|
1946
|
+
'app-server stderr failed',
|
|
1947
|
+
error,
|
|
1948
|
+
));
|
|
1949
|
+
child.stdin.on('error', (error) => {
|
|
1950
|
+
this._transportFault('app-server stdin failed', error);
|
|
1951
|
+
});
|
|
1952
|
+
child.once('error', (error) => {
|
|
1953
|
+
if (this.state !== 'closing' && this.state !== 'closed') {
|
|
1954
|
+
this._fault(new CodexAppServerError(
|
|
1955
|
+
'app-server process failed',
|
|
1956
|
+
'CODEX_PROCESS_ERROR',
|
|
1957
|
+
{ cause: error },
|
|
1958
|
+
));
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
request(method, params, {
|
|
1964
|
+
timeoutMs = this.requestTimeoutMs,
|
|
1965
|
+
onWriteAttempted,
|
|
1966
|
+
onResponseObserved,
|
|
1967
|
+
} = {}) {
|
|
1968
|
+
return this._request(method, params, {
|
|
1969
|
+
timeoutMs,
|
|
1970
|
+
onWriteAttempted,
|
|
1971
|
+
onResponseObserved,
|
|
1972
|
+
});
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
_request(method, params, {
|
|
1976
|
+
internal = false,
|
|
1977
|
+
timeoutMs = this.requestTimeoutMs,
|
|
1978
|
+
onWriteAttempted,
|
|
1979
|
+
onResponseObserved,
|
|
1980
|
+
} = {}) {
|
|
1981
|
+
const spec = CLIENT_REQUESTS.get(method);
|
|
1982
|
+
if (
|
|
1983
|
+
!spec
|
|
1984
|
+
|| DENIED_CLIENT_REQUESTS.has(method)
|
|
1985
|
+
|| (spec.internal && !internal)
|
|
1986
|
+
) {
|
|
1987
|
+
return Promise.reject(new CodexAppServerError(
|
|
1988
|
+
'app-server request method is not allowlisted',
|
|
1989
|
+
'CODEX_RPC_REJECTED',
|
|
1990
|
+
));
|
|
1991
|
+
}
|
|
1992
|
+
if (this.protocolError) return Promise.reject(this.protocolError);
|
|
1993
|
+
if (
|
|
1994
|
+
(!internal && this.state !== 'ready')
|
|
1995
|
+
|| (internal && method === 'initialize' && this.state !== 'initializing')
|
|
1996
|
+
) {
|
|
1997
|
+
return Promise.reject(new CodexAppServerError(
|
|
1998
|
+
'app-server client is not ready',
|
|
1999
|
+
'CODEX_CLIENT_STATE',
|
|
2000
|
+
));
|
|
2001
|
+
}
|
|
2002
|
+
let projectedParams;
|
|
2003
|
+
try {
|
|
2004
|
+
projectedParams = projectRequestParams(method, params, spec, this.cwd);
|
|
2005
|
+
assertPositiveInteger(timeoutMs, 'request timeout');
|
|
2006
|
+
} catch (error) {
|
|
2007
|
+
return Promise.reject(error);
|
|
2008
|
+
}
|
|
2009
|
+
if (
|
|
2010
|
+
spec.stateChanging
|
|
2011
|
+
&& (
|
|
2012
|
+
typeof onWriteAttempted !== 'function'
|
|
2013
|
+
|| typeof onResponseObserved !== 'function'
|
|
2014
|
+
)
|
|
2015
|
+
) {
|
|
2016
|
+
return Promise.reject(new CodexAppServerError(
|
|
2017
|
+
`app-server ${method} requires delivery checkpoints`,
|
|
2018
|
+
'CODEX_RPC_REJECTED',
|
|
2019
|
+
));
|
|
2020
|
+
}
|
|
2021
|
+
if (!this._stdinWritable()) {
|
|
2022
|
+
const cause = new CodexAppServerError(
|
|
2023
|
+
'app-server stdin is not writable',
|
|
2024
|
+
'CODEX_TRANSPORT_ERROR',
|
|
2025
|
+
);
|
|
2026
|
+
return Promise.reject(
|
|
2027
|
+
spec.stateChanging
|
|
2028
|
+
? mutationDeliveryError({ method, writeAttempted: false }, cause)
|
|
2029
|
+
: cause,
|
|
2030
|
+
);
|
|
2031
|
+
}
|
|
2032
|
+
if (this.pending.size >= this.maxPendingRequests) {
|
|
2033
|
+
return Promise.reject(new CodexAppServerError(
|
|
2034
|
+
'app-server pending request limit reached',
|
|
2035
|
+
'CODEX_RPC_REJECTED',
|
|
2036
|
+
));
|
|
2037
|
+
}
|
|
2038
|
+
if (this.usedRequestIds.size >= this.maxUsedRequestIds) {
|
|
2039
|
+
const error = new CodexAppServerError(
|
|
2040
|
+
'app-server request ID space is exhausted for this generation',
|
|
2041
|
+
'CODEX_REQUEST_ID_EXHAUSTED',
|
|
2042
|
+
);
|
|
2043
|
+
this._fault(error);
|
|
2044
|
+
return Promise.reject(error);
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
let id;
|
|
2048
|
+
try {
|
|
2049
|
+
id = this.requestIdFactory
|
|
2050
|
+
? this.requestIdFactory(this.nextRequestId)
|
|
2051
|
+
: this.nextRequestId;
|
|
2052
|
+
this.nextRequestId += 1;
|
|
2053
|
+
assertRequestId(id);
|
|
2054
|
+
if (this.usedRequestIds.has(id)) {
|
|
2055
|
+
throw new CodexAppServerError(
|
|
2056
|
+
'app-server request ID was reused',
|
|
2057
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2058
|
+
);
|
|
2059
|
+
}
|
|
2060
|
+
this.usedRequestIds.add(id);
|
|
2061
|
+
} catch (error) {
|
|
2062
|
+
return Promise.reject(error);
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
return new Promise((resolve, reject) => {
|
|
2066
|
+
const pending = {
|
|
2067
|
+
id,
|
|
2068
|
+
method,
|
|
2069
|
+
stateChanging: spec.stateChanging,
|
|
2070
|
+
writeAttempted: false,
|
|
2071
|
+
onWriteAttempted,
|
|
2072
|
+
onResponseObserved,
|
|
2073
|
+
resolve,
|
|
2074
|
+
reject,
|
|
2075
|
+
timer: null,
|
|
2076
|
+
sinkController: null,
|
|
2077
|
+
};
|
|
2078
|
+
pending.timer = this.setTimer(() => {
|
|
2079
|
+
if (this.pending.get(id) !== pending) return;
|
|
2080
|
+
const timeoutError = new CodexAppServerError(
|
|
2081
|
+
`app-server ${method} timed out`,
|
|
2082
|
+
'CODEX_RPC_TIMEOUT',
|
|
2083
|
+
);
|
|
2084
|
+
if (pending.stateChanging && pending.writeAttempted) {
|
|
2085
|
+
this._fault(timeoutError);
|
|
2086
|
+
return;
|
|
2087
|
+
}
|
|
2088
|
+
pending.sinkController?.abort(timeoutError);
|
|
2089
|
+
this.pending.delete(id);
|
|
2090
|
+
reject(
|
|
2091
|
+
pending.stateChanging
|
|
2092
|
+
? mutationDeliveryError(pending, timeoutError)
|
|
2093
|
+
: timeoutError,
|
|
2094
|
+
);
|
|
2095
|
+
}, timeoutMs);
|
|
2096
|
+
this.pending.set(id, pending);
|
|
2097
|
+
void this._dispatchRequest(pending, projectedParams);
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
async _dispatchRequest(pending, params) {
|
|
2102
|
+
try {
|
|
2103
|
+
const message = { id: pending.id, method: pending.method };
|
|
2104
|
+
if (params !== undefined) message.params = params;
|
|
2105
|
+
const line = this._serializeMessage(message);
|
|
2106
|
+
if (pending.stateChanging) {
|
|
2107
|
+
const controller = new AbortController();
|
|
2108
|
+
pending.sinkController = controller;
|
|
2109
|
+
try {
|
|
2110
|
+
await this._runSink(
|
|
2111
|
+
pending.onWriteAttempted,
|
|
2112
|
+
{
|
|
2113
|
+
id: pending.id,
|
|
2114
|
+
method: pending.method,
|
|
2115
|
+
},
|
|
2116
|
+
'write checkpoint',
|
|
2117
|
+
controller,
|
|
2118
|
+
{
|
|
2119
|
+
markWriteCommitted: () => {
|
|
2120
|
+
pending.writeAttempted = true;
|
|
2121
|
+
},
|
|
2122
|
+
},
|
|
2123
|
+
);
|
|
2124
|
+
} finally {
|
|
2125
|
+
if (pending.sinkController === controller) {
|
|
2126
|
+
pending.sinkController = null;
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
if (this.pending.get(pending.id) !== pending) return;
|
|
2130
|
+
pending.writeAttempted = true;
|
|
2131
|
+
}
|
|
2132
|
+
await this._writeLine(line);
|
|
2133
|
+
} catch (error) {
|
|
2134
|
+
if (this.pending.get(pending.id) !== pending) return;
|
|
2135
|
+
if (pending.stateChanging && pending.writeAttempted) {
|
|
2136
|
+
this._fault(error);
|
|
2137
|
+
return;
|
|
2138
|
+
}
|
|
2139
|
+
this.pending.delete(pending.id);
|
|
2140
|
+
this.clearTimer(pending.timer);
|
|
2141
|
+
pending.reject(
|
|
2142
|
+
pending.stateChanging
|
|
2143
|
+
? mutationDeliveryError(pending, error)
|
|
2144
|
+
: error,
|
|
2145
|
+
);
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
_serializeMessage(message) {
|
|
2150
|
+
let line;
|
|
2151
|
+
try {
|
|
2152
|
+
line = `${JSON.stringify(message)}\n`;
|
|
2153
|
+
} catch (error) {
|
|
2154
|
+
throw new CodexAppServerError(
|
|
2155
|
+
'app-server client message was not serializable',
|
|
2156
|
+
'CODEX_RPC_REJECTED',
|
|
2157
|
+
{ cause: error },
|
|
2158
|
+
);
|
|
2159
|
+
}
|
|
2160
|
+
if (Buffer.byteLength(line) > this.maxLineBytes) {
|
|
2161
|
+
throw new CodexAppServerError(
|
|
2162
|
+
'app-server client message exceeded the size limit',
|
|
2163
|
+
'CODEX_RPC_REJECTED',
|
|
2164
|
+
);
|
|
2165
|
+
}
|
|
2166
|
+
return line;
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
_writeMessage(message) {
|
|
2170
|
+
return this._writeLine(this._serializeMessage(message));
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
_writeLine(line) {
|
|
2174
|
+
if (this.protocolError) throw this.protocolError;
|
|
2175
|
+
if (!this._stdinWritable()) {
|
|
2176
|
+
throw new CodexAppServerError(
|
|
2177
|
+
'app-server stdin is not writable',
|
|
2178
|
+
'CODEX_TRANSPORT_ERROR',
|
|
2179
|
+
);
|
|
2180
|
+
}
|
|
2181
|
+
return this._awaitBounded(
|
|
2182
|
+
new Promise((resolve, reject) => {
|
|
2183
|
+
try {
|
|
2184
|
+
this.child.stdin.write(line, (error) => {
|
|
2185
|
+
if (error) reject(error);
|
|
2186
|
+
else resolve();
|
|
2187
|
+
});
|
|
2188
|
+
} catch (error) {
|
|
2189
|
+
reject(error);
|
|
2190
|
+
}
|
|
2191
|
+
}),
|
|
2192
|
+
'transport write',
|
|
2193
|
+
);
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
_awaitBounded(value, label) {
|
|
2197
|
+
let timer;
|
|
2198
|
+
return Promise.race([
|
|
2199
|
+
Promise.resolve(value),
|
|
2200
|
+
new Promise((resolve, reject) => {
|
|
2201
|
+
timer = this.setTimer(() => reject(new CodexAppServerError(
|
|
2202
|
+
`app-server ${label} timed out`,
|
|
2203
|
+
'CODEX_SINK_TIMEOUT',
|
|
2204
|
+
)), this.sinkTimeoutMs);
|
|
2205
|
+
}),
|
|
2206
|
+
]).finally(() => {
|
|
2207
|
+
if (timer !== undefined) this.clearTimer(timer);
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
_runSink(
|
|
2212
|
+
callback,
|
|
2213
|
+
payload,
|
|
2214
|
+
label,
|
|
2215
|
+
controller = new AbortController(),
|
|
2216
|
+
capabilities = {},
|
|
2217
|
+
) {
|
|
2218
|
+
const generation = this.sinkGeneration;
|
|
2219
|
+
let active = true;
|
|
2220
|
+
const sinkPayload = { ...payload };
|
|
2221
|
+
const assertSinkActive = () => {
|
|
2222
|
+
if (
|
|
2223
|
+
!active
|
|
2224
|
+
|| controller.signal.aborted
|
|
2225
|
+
|| generation !== this.sinkGeneration
|
|
2226
|
+
) {
|
|
2227
|
+
throw new CodexAppServerError(
|
|
2228
|
+
`app-server ${label} is no longer active`,
|
|
2229
|
+
'CODEX_SINK_ABORTED',
|
|
2230
|
+
);
|
|
2231
|
+
}
|
|
2232
|
+
};
|
|
2233
|
+
const properties = {
|
|
2234
|
+
signal: {
|
|
2235
|
+
value: controller.signal,
|
|
2236
|
+
enumerable: false,
|
|
2237
|
+
},
|
|
2238
|
+
assertActive: {
|
|
2239
|
+
value: assertSinkActive,
|
|
2240
|
+
enumerable: false,
|
|
2241
|
+
},
|
|
2242
|
+
};
|
|
2243
|
+
for (const [name, capability] of Object.entries(capabilities)) {
|
|
2244
|
+
properties[name] = {
|
|
2245
|
+
value: (...args) => {
|
|
2246
|
+
assertSinkActive();
|
|
2247
|
+
return capability(...args);
|
|
2248
|
+
},
|
|
2249
|
+
enumerable: false,
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
Object.defineProperties(sinkPayload, properties);
|
|
2253
|
+
this.activeSinkControllers.add(controller);
|
|
2254
|
+
let timer;
|
|
2255
|
+
let sinkPromise;
|
|
2256
|
+
try {
|
|
2257
|
+
sinkPromise = Promise.resolve(callback(sinkPayload));
|
|
2258
|
+
} catch (error) {
|
|
2259
|
+
sinkPromise = Promise.reject(error);
|
|
2260
|
+
}
|
|
2261
|
+
return Promise.race([
|
|
2262
|
+
sinkPromise,
|
|
2263
|
+
new Promise((resolve, reject) => {
|
|
2264
|
+
controller.signal.addEventListener('abort', () => {
|
|
2265
|
+
active = false;
|
|
2266
|
+
reject(
|
|
2267
|
+
controller.signal.reason instanceof Error
|
|
2268
|
+
? controller.signal.reason
|
|
2269
|
+
: new CodexAppServerError(
|
|
2270
|
+
`app-server ${label} was aborted`,
|
|
2271
|
+
'CODEX_SINK_ABORTED',
|
|
2272
|
+
),
|
|
2273
|
+
);
|
|
2274
|
+
}, { once: true });
|
|
2275
|
+
}),
|
|
2276
|
+
new Promise((resolve, reject) => {
|
|
2277
|
+
timer = this.setTimer(() => {
|
|
2278
|
+
active = false;
|
|
2279
|
+
const timeoutError = new CodexAppServerError(
|
|
2280
|
+
`app-server ${label} timed out`,
|
|
2281
|
+
'CODEX_SINK_TIMEOUT',
|
|
2282
|
+
);
|
|
2283
|
+
controller.abort(timeoutError);
|
|
2284
|
+
reject(timeoutError);
|
|
2285
|
+
}, this.sinkTimeoutMs);
|
|
2286
|
+
}),
|
|
2287
|
+
]).finally(() => {
|
|
2288
|
+
active = false;
|
|
2289
|
+
controller.abort();
|
|
2290
|
+
this.activeSinkControllers.delete(controller);
|
|
2291
|
+
if (timer !== undefined) this.clearTimer(timer);
|
|
2292
|
+
});
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
_invalidateSinks() {
|
|
2296
|
+
this.sinkGeneration += 1;
|
|
2297
|
+
for (const controller of this.activeSinkControllers) {
|
|
2298
|
+
controller.abort(new CodexAppServerError(
|
|
2299
|
+
'app-server sink generation was invalidated',
|
|
2300
|
+
'CODEX_SINK_ABORTED',
|
|
2301
|
+
));
|
|
2302
|
+
}
|
|
2303
|
+
this.activeSinkControllers.clear();
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
_stdinWritable() {
|
|
2307
|
+
return (
|
|
2308
|
+
this.child
|
|
2309
|
+
&& this.state !== 'closing'
|
|
2310
|
+
&& this.state !== 'closed'
|
|
2311
|
+
&& !this.exitInfo
|
|
2312
|
+
&& this.child.stdin.writable !== false
|
|
2313
|
+
&& this.child.stdin.destroyed !== true
|
|
2314
|
+
);
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2317
|
+
_onStdoutData(chunk) {
|
|
2318
|
+
if (
|
|
2319
|
+
this.state === 'closing'
|
|
2320
|
+
|| this.state === 'closed'
|
|
2321
|
+
|| this.protocolError
|
|
2322
|
+
) return;
|
|
2323
|
+
this.stdoutBuffer += typeof chunk === 'string'
|
|
2324
|
+
? chunk
|
|
2325
|
+
: this.stdoutDecoder.write(chunk);
|
|
2326
|
+
let newline;
|
|
2327
|
+
while ((newline = this.stdoutBuffer.indexOf('\n')) !== -1) {
|
|
2328
|
+
let line = this.stdoutBuffer.slice(0, newline);
|
|
2329
|
+
this.stdoutBuffer = this.stdoutBuffer.slice(newline + 1);
|
|
2330
|
+
if (line.endsWith('\r')) line = line.slice(0, -1);
|
|
2331
|
+
if (Buffer.byteLength(line) > this.maxLineBytes) {
|
|
2332
|
+
this._fault(new CodexAppServerError(
|
|
2333
|
+
'app-server line exceeded the size limit',
|
|
2334
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2335
|
+
));
|
|
2336
|
+
return;
|
|
2337
|
+
}
|
|
2338
|
+
const lineBytes = Buffer.byteLength(line);
|
|
2339
|
+
if (
|
|
2340
|
+
this.queuedLineCount + 1 > this.maxQueuedLines
|
|
2341
|
+
|| this.queuedLineBytes + lineBytes > this.maxQueuedBytes
|
|
2342
|
+
) {
|
|
2343
|
+
this._fault(new CodexAppServerError(
|
|
2344
|
+
'app-server inbound message queue exceeded the size limit',
|
|
2345
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2346
|
+
));
|
|
2347
|
+
return;
|
|
2348
|
+
}
|
|
2349
|
+
this.queuedLineCount += 1;
|
|
2350
|
+
this.queuedLineBytes += lineBytes;
|
|
2351
|
+
if (
|
|
2352
|
+
!this.stdoutPaused
|
|
2353
|
+
&& this.child?.stdout
|
|
2354
|
+
&& typeof this.child.stdout.pause === 'function'
|
|
2355
|
+
&& (
|
|
2356
|
+
this.queuedLineCount >= Math.ceil(this.maxQueuedLines / 2)
|
|
2357
|
+
|| this.queuedLineBytes >= Math.ceil(this.maxQueuedBytes / 2)
|
|
2358
|
+
)
|
|
2359
|
+
) {
|
|
2360
|
+
this.child.stdout.pause();
|
|
2361
|
+
this.stdoutPaused = true;
|
|
2362
|
+
}
|
|
2363
|
+
this.messageChain = this.messageChain
|
|
2364
|
+
.then(async () => {
|
|
2365
|
+
this.queuedLineCount -= 1;
|
|
2366
|
+
this.queuedLineBytes -= lineBytes;
|
|
2367
|
+
this._resumeStdoutIfSafe();
|
|
2368
|
+
if (
|
|
2369
|
+
this.protocolError
|
|
2370
|
+
|| this.state === 'closing'
|
|
2371
|
+
|| this.state === 'closed'
|
|
2372
|
+
) return;
|
|
2373
|
+
await this._handleLine(line);
|
|
2374
|
+
})
|
|
2375
|
+
.catch((error) => this._fault(error));
|
|
2376
|
+
}
|
|
2377
|
+
if (Buffer.byteLength(this.stdoutBuffer) > this.maxLineBytes) {
|
|
2378
|
+
this._fault(new CodexAppServerError(
|
|
2379
|
+
'app-server partial line exceeded the size limit',
|
|
2380
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2381
|
+
));
|
|
2382
|
+
}
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
_onStdoutEnd() {
|
|
2386
|
+
const trailing = this.stdoutBuffer + this.stdoutDecoder.end();
|
|
2387
|
+
this.stdoutBuffer = '';
|
|
2388
|
+
this._enqueueTerminalFault(new CodexAppServerError(
|
|
2389
|
+
trailing.length > 0
|
|
2390
|
+
? 'app-server output ended with a partial message'
|
|
2391
|
+
: 'app-server output closed unexpectedly',
|
|
2392
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2393
|
+
));
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
_resumeStdoutIfSafe() {
|
|
2397
|
+
if (
|
|
2398
|
+
!this.stdoutPaused
|
|
2399
|
+
|| this.protocolError
|
|
2400
|
+
|| this.state === 'closing'
|
|
2401
|
+
|| this.state === 'closed'
|
|
2402
|
+
) return;
|
|
2403
|
+
if (
|
|
2404
|
+
this.queuedLineCount < Math.ceil(this.maxQueuedLines / 2)
|
|
2405
|
+
&& this.queuedLineBytes < Math.ceil(this.maxQueuedBytes / 2)
|
|
2406
|
+
) {
|
|
2407
|
+
this.child?.stdout?.resume?.();
|
|
2408
|
+
this.stdoutPaused = false;
|
|
2409
|
+
}
|
|
2410
|
+
}
|
|
2411
|
+
|
|
2412
|
+
_enqueueTerminalFault(error) {
|
|
2413
|
+
if (
|
|
2414
|
+
this.state === 'closing'
|
|
2415
|
+
|| this.state === 'closed'
|
|
2416
|
+
|| this.protocolError
|
|
2417
|
+
) return;
|
|
2418
|
+
this.messageChain = this.messageChain
|
|
2419
|
+
.then(() => {
|
|
2420
|
+
if (
|
|
2421
|
+
this.state !== 'closing'
|
|
2422
|
+
&& this.state !== 'closed'
|
|
2423
|
+
&& !this.protocolError
|
|
2424
|
+
) this._fault(error);
|
|
2425
|
+
})
|
|
2426
|
+
.catch((cause) => this._fault(cause));
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
_transportFault(message, cause) {
|
|
2430
|
+
if (this.state === 'closing' || this.state === 'closed') return;
|
|
2431
|
+
this._enqueueTerminalFault(new CodexAppServerError(
|
|
2432
|
+
message,
|
|
2433
|
+
'CODEX_TRANSPORT_ERROR',
|
|
2434
|
+
{ cause },
|
|
2435
|
+
));
|
|
2436
|
+
}
|
|
2437
|
+
|
|
2438
|
+
_onStderrData(chunk) {
|
|
2439
|
+
this.stderrBytes += Buffer.isBuffer(chunk)
|
|
2440
|
+
? chunk.length
|
|
2441
|
+
: Buffer.byteLength(String(chunk));
|
|
2442
|
+
if (this.stderrBytes > this.maxStderrBytes) {
|
|
2443
|
+
this._fault(new CodexAppServerError(
|
|
2444
|
+
'app-server stderr exceeded the size limit',
|
|
2445
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2446
|
+
));
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
async _handleLine(line) {
|
|
2451
|
+
let message;
|
|
2452
|
+
try {
|
|
2453
|
+
message = JSON.parse(line);
|
|
2454
|
+
} catch {
|
|
2455
|
+
throw new CodexAppServerError(
|
|
2456
|
+
'app-server emitted malformed JSON',
|
|
2457
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2458
|
+
);
|
|
2459
|
+
}
|
|
2460
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) {
|
|
2461
|
+
throw new CodexAppServerError(
|
|
2462
|
+
'app-server emitted a malformed message',
|
|
2463
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2464
|
+
);
|
|
2465
|
+
}
|
|
2466
|
+
if (Object.hasOwn(message, 'jsonrpc')) {
|
|
2467
|
+
throw new CodexAppServerError(
|
|
2468
|
+
'app-server emitted unsupported JSON-RPC framing',
|
|
2469
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2470
|
+
);
|
|
2471
|
+
}
|
|
2472
|
+
const hasId = Object.hasOwn(message, 'id');
|
|
2473
|
+
const hasMethod = Object.hasOwn(message, 'method');
|
|
2474
|
+
const hasResult = Object.hasOwn(message, 'result');
|
|
2475
|
+
const hasError = Object.hasOwn(message, 'error');
|
|
2476
|
+
const keysAllowed = (allowed) => (
|
|
2477
|
+
Object.keys(message).every((key) => allowed.includes(key))
|
|
2478
|
+
);
|
|
2479
|
+
if (hasId) assertRequestId(message.id);
|
|
2480
|
+
if (
|
|
2481
|
+
hasMethod
|
|
2482
|
+
&& (
|
|
2483
|
+
typeof message.method !== 'string'
|
|
2484
|
+
|| !SAFE_METHOD_PATTERN.test(message.method)
|
|
2485
|
+
)
|
|
2486
|
+
) {
|
|
2487
|
+
throw new CodexAppServerError(
|
|
2488
|
+
'app-server emitted a malformed method',
|
|
2489
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2490
|
+
);
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
if (hasId && hasMethod) {
|
|
2494
|
+
if (hasResult || hasError || !keysAllowed(['id', 'method', 'params'])) {
|
|
2495
|
+
throw new CodexAppServerError(
|
|
2496
|
+
'app-server emitted an ambiguous server request',
|
|
2497
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2498
|
+
);
|
|
2499
|
+
}
|
|
2500
|
+
const denial = DENIED_SERVER_REQUESTS.get(message.method);
|
|
2501
|
+
if (!denial) {
|
|
2502
|
+
throw new CodexAppServerError(
|
|
2503
|
+
'app-server sent an unknown server request',
|
|
2504
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2505
|
+
);
|
|
2506
|
+
}
|
|
2507
|
+
await this._writeMessage({ id: message.id, ...denial });
|
|
2508
|
+
try { this.emit('server-request-denied', { known: true }); } catch {}
|
|
2509
|
+
throw new CodexAppServerError(
|
|
2510
|
+
'app-server sent a disabled server request',
|
|
2511
|
+
'CODEX_SERVER_REQUEST_DENIED',
|
|
2512
|
+
);
|
|
2513
|
+
}
|
|
2514
|
+
|
|
2515
|
+
if (hasId) {
|
|
2516
|
+
if (
|
|
2517
|
+
hasMethod
|
|
2518
|
+
|| hasResult === hasError
|
|
2519
|
+
|| !keysAllowed(hasResult ? ['id', 'result'] : ['id', 'error'])
|
|
2520
|
+
) {
|
|
2521
|
+
return this._handleMalformedResponse(message.id);
|
|
2522
|
+
}
|
|
2523
|
+
const pending = this.pending.get(message.id);
|
|
2524
|
+
if (!pending) {
|
|
2525
|
+
throw new CodexAppServerError(
|
|
2526
|
+
'app-server returned an unexpected response ID',
|
|
2527
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2528
|
+
);
|
|
2529
|
+
}
|
|
2530
|
+
let projectedResult;
|
|
2531
|
+
let projectedError;
|
|
2532
|
+
try {
|
|
2533
|
+
if (hasResult) {
|
|
2534
|
+
projectedResult = projectRpcResult(
|
|
2535
|
+
pending.method,
|
|
2536
|
+
message.result,
|
|
2537
|
+
this.cwd,
|
|
2538
|
+
);
|
|
2539
|
+
} else {
|
|
2540
|
+
projectedError = projectRpcError(message.error);
|
|
2541
|
+
}
|
|
2542
|
+
} catch (error) {
|
|
2543
|
+
this._fault(error);
|
|
2544
|
+
return;
|
|
2545
|
+
}
|
|
2546
|
+
this.clearTimer(pending.timer);
|
|
2547
|
+
try {
|
|
2548
|
+
if (pending.stateChanging) {
|
|
2549
|
+
const controller = new AbortController();
|
|
2550
|
+
pending.sinkController = controller;
|
|
2551
|
+
try {
|
|
2552
|
+
await this._runSink(
|
|
2553
|
+
pending.onResponseObserved,
|
|
2554
|
+
{
|
|
2555
|
+
id: pending.id,
|
|
2556
|
+
method: pending.method,
|
|
2557
|
+
outcome: hasResult ? 'result' : 'error',
|
|
2558
|
+
},
|
|
2559
|
+
'response checkpoint',
|
|
2560
|
+
controller,
|
|
2561
|
+
);
|
|
2562
|
+
} finally {
|
|
2563
|
+
if (pending.sinkController === controller) {
|
|
2564
|
+
pending.sinkController = null;
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
} catch (error) {
|
|
2569
|
+
if (this.pending.get(message.id) === pending) {
|
|
2570
|
+
this.pending.delete(message.id);
|
|
2571
|
+
const checkpointError = new CodexAppServerError(
|
|
2572
|
+
'app-server response checkpoint failed',
|
|
2573
|
+
'CODEX_RPC_CHECKPOINT_FAILED',
|
|
2574
|
+
{ cause: error },
|
|
2575
|
+
);
|
|
2576
|
+
pending.reject(checkpointError);
|
|
2577
|
+
this._fault(checkpointError);
|
|
2578
|
+
}
|
|
2579
|
+
return;
|
|
2580
|
+
}
|
|
2581
|
+
if (this.pending.get(message.id) !== pending) return;
|
|
2582
|
+
this.pending.delete(message.id);
|
|
2583
|
+
if (hasError) {
|
|
2584
|
+
const error = new CodexAppServerError(
|
|
2585
|
+
`app-server ${pending.method} failed`,
|
|
2586
|
+
'CODEX_RPC_ERROR',
|
|
2587
|
+
);
|
|
2588
|
+
error.rpcCode = projectedError.code;
|
|
2589
|
+
if (
|
|
2590
|
+
RECOGNIZED_RPC_ERRORS.get(pending.method)
|
|
2591
|
+
?.has(projectedError.message)
|
|
2592
|
+
) {
|
|
2593
|
+
error.rpcMessage = projectedError.message;
|
|
2594
|
+
}
|
|
2595
|
+
pending.reject(error);
|
|
2596
|
+
} else {
|
|
2597
|
+
pending.resolve(projectedResult);
|
|
2598
|
+
}
|
|
2599
|
+
return;
|
|
2600
|
+
}
|
|
2601
|
+
|
|
2602
|
+
if (
|
|
2603
|
+
!hasMethod
|
|
2604
|
+
|| hasResult
|
|
2605
|
+
|| hasError
|
|
2606
|
+
|| !keysAllowed(['method', 'params'])
|
|
2607
|
+
) {
|
|
2608
|
+
throw new CodexAppServerError(
|
|
2609
|
+
'app-server emitted a malformed notification',
|
|
2610
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2611
|
+
);
|
|
2612
|
+
}
|
|
2613
|
+
if (DROPPED_NOTIFICATIONS.has(message.method)) return;
|
|
2614
|
+
if (!DELIVERED_NOTIFICATIONS.has(message.method)) {
|
|
2615
|
+
throw new CodexAppServerError(
|
|
2616
|
+
'app-server sent an unexpected server notification',
|
|
2617
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2618
|
+
);
|
|
2619
|
+
}
|
|
2620
|
+
await this._runSink(
|
|
2621
|
+
this.onNotification,
|
|
2622
|
+
projectNotification(message, this.cwd),
|
|
2623
|
+
'notification sink',
|
|
2624
|
+
);
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
_handleMalformedResponse(id) {
|
|
2628
|
+
const pending = this.pending.get(id);
|
|
2629
|
+
if (!pending) {
|
|
2630
|
+
throw new CodexAppServerError(
|
|
2631
|
+
'app-server returned an unexpected response ID',
|
|
2632
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2633
|
+
);
|
|
2634
|
+
}
|
|
2635
|
+
this.clearTimer(pending.timer);
|
|
2636
|
+
const malformed = new CodexAppServerError(
|
|
2637
|
+
`app-server ${pending.method} returned a malformed response`,
|
|
2638
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2639
|
+
);
|
|
2640
|
+
this._fault(malformed);
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2643
|
+
_fault(error) {
|
|
2644
|
+
if (this.protocolError || this.state === 'closed') return;
|
|
2645
|
+
const fault = error instanceof Error
|
|
2646
|
+
? error
|
|
2647
|
+
: new CodexAppServerError(
|
|
2648
|
+
'app-server protocol failed',
|
|
2649
|
+
'CODEX_PROTOCOL_ERROR',
|
|
2650
|
+
);
|
|
2651
|
+
const ambiguousMutation = this._rejectAll(fault);
|
|
2652
|
+
this.protocolError = ambiguousMutation ?? fault;
|
|
2653
|
+
this._invalidateSinks();
|
|
2654
|
+
try { this.emit('protocol-error', this.protocolError); } catch {}
|
|
2655
|
+
if (this.state !== 'closing') this.state = 'faulted';
|
|
2656
|
+
const postSpawn = Boolean(this.child);
|
|
2657
|
+
this.faultPromise = this._settleFault(postSpawn);
|
|
2658
|
+
this.faultPromise.then(this.resolveFaultWait, this.rejectFaultWait);
|
|
2659
|
+
this.faultPromise.catch(() => {});
|
|
2660
|
+
}
|
|
2661
|
+
|
|
2662
|
+
async _settleFault(postSpawn) {
|
|
2663
|
+
let cleanupError = null;
|
|
2664
|
+
try {
|
|
2665
|
+
await this.close();
|
|
2666
|
+
} catch (error) {
|
|
2667
|
+
cleanupError = error;
|
|
2668
|
+
}
|
|
2669
|
+
const outcome = Object.freeze({
|
|
2670
|
+
kind: 'codex-app-server-fault',
|
|
2671
|
+
boundary: postSpawn ? 'post-spawn' : 'pre-spawn',
|
|
2672
|
+
containment: postSpawn ? 'unverified' : 'safe',
|
|
2673
|
+
cleanup: cleanupError ? 'failed' : 'completed',
|
|
2674
|
+
errorCode: this.protocolError?.code ?? 'CODEX_PROTOCOL_ERROR',
|
|
2675
|
+
cleanupErrorCode: cleanupError?.code ?? null,
|
|
2676
|
+
mutationOutcomeUnknown:
|
|
2677
|
+
this.protocolError?.code === 'CODEX_RPC_OUTCOME_UNKNOWN',
|
|
2678
|
+
});
|
|
2679
|
+
try {
|
|
2680
|
+
await this._runSink(this.onFault, outcome, 'fault checkpoint');
|
|
2681
|
+
} catch (error) {
|
|
2682
|
+
const handoffError = new CodexAppServerError(
|
|
2683
|
+
'app-server fault checkpoint failed',
|
|
2684
|
+
'CODEX_FAULT_CHECKPOINT_FAILED',
|
|
2685
|
+
{ cause: error },
|
|
2686
|
+
);
|
|
2687
|
+
try { this.emit('fault-checkpoint-error', handoffError); } catch {}
|
|
2688
|
+
throw handoffError;
|
|
2689
|
+
}
|
|
2690
|
+
this.faultOutcome = outcome;
|
|
2691
|
+
try { this.emit('fault-outcome', outcome); } catch {}
|
|
2692
|
+
return outcome;
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2695
|
+
waitForFault() {
|
|
2696
|
+
return this.faultWaitPromise;
|
|
2697
|
+
}
|
|
2698
|
+
|
|
2699
|
+
_rejectAll(cause) {
|
|
2700
|
+
let ambiguousMutation = null;
|
|
2701
|
+
for (const pending of this.pending.values()) {
|
|
2702
|
+
this.clearTimer(pending.timer);
|
|
2703
|
+
pending.sinkController?.abort(cause);
|
|
2704
|
+
const requestError = pending.stateChanging
|
|
2705
|
+
? mutationDeliveryError(pending, cause)
|
|
2706
|
+
: cause;
|
|
2707
|
+
if (
|
|
2708
|
+
requestError.code === 'CODEX_RPC_OUTCOME_UNKNOWN'
|
|
2709
|
+
&& ambiguousMutation === null
|
|
2710
|
+
) ambiguousMutation = requestError;
|
|
2711
|
+
pending.reject(requestError);
|
|
2712
|
+
}
|
|
2713
|
+
this.pending.clear();
|
|
2714
|
+
return ambiguousMutation;
|
|
2715
|
+
}
|
|
2716
|
+
|
|
2717
|
+
assertHealthy() {
|
|
2718
|
+
if (this.protocolError) throw this.protocolError;
|
|
2719
|
+
if (this.state !== 'ready') {
|
|
2720
|
+
throw new CodexAppServerError(
|
|
2721
|
+
'app-server client is not ready',
|
|
2722
|
+
'CODEX_CLIENT_STATE',
|
|
2723
|
+
);
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2727
|
+
_childAlive() {
|
|
2728
|
+
return Boolean(
|
|
2729
|
+
this.child
|
|
2730
|
+
&& !this.exitInfo
|
|
2731
|
+
&& this.child.exitCode == null
|
|
2732
|
+
&& this.child.signalCode == null,
|
|
2733
|
+
);
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
_signalOwnedTree(signal) {
|
|
2737
|
+
if (!this._childAlive()) return false;
|
|
2738
|
+
if (
|
|
2739
|
+
Number.isSafeInteger(this.child.pid)
|
|
2740
|
+
&& this.child.pid >= 2
|
|
2741
|
+
) {
|
|
2742
|
+
try {
|
|
2743
|
+
this.killFn(-this.child.pid, signal);
|
|
2744
|
+
return true;
|
|
2745
|
+
} catch (error) {
|
|
2746
|
+
if (error?.code === 'ESRCH') return false;
|
|
2747
|
+
throw error;
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
return this.child.kill(signal);
|
|
2751
|
+
}
|
|
2752
|
+
|
|
2753
|
+
_waitForExit(timeoutMs) {
|
|
2754
|
+
let timer;
|
|
2755
|
+
return Promise.race([
|
|
2756
|
+
this.exitPromise,
|
|
2757
|
+
new Promise((resolve) => {
|
|
2758
|
+
timer = this.setTimer(() => resolve(null), timeoutMs);
|
|
2759
|
+
}),
|
|
2760
|
+
]).finally(() => {
|
|
2761
|
+
if (timer !== undefined) this.clearTimer(timer);
|
|
2762
|
+
});
|
|
2763
|
+
}
|
|
2764
|
+
|
|
2765
|
+
_delay(timeoutMs) {
|
|
2766
|
+
return new Promise((resolve) => {
|
|
2767
|
+
this.setTimer(resolve, timeoutMs);
|
|
2768
|
+
});
|
|
2769
|
+
}
|
|
2770
|
+
|
|
2771
|
+
async _ownedGroupMembers() {
|
|
2772
|
+
if (!Number.isSafeInteger(this.child?.pid)) return [];
|
|
2773
|
+
let stdout;
|
|
2774
|
+
try {
|
|
2775
|
+
({ stdout } = await execFileAsync('/bin/ps', ['-axo', 'pid=,pgid='], {
|
|
2776
|
+
encoding: 'utf8',
|
|
2777
|
+
timeout: Math.max(100, this.closeGraceMs),
|
|
2778
|
+
maxBuffer: 1024 * 1024,
|
|
2779
|
+
env: { PATH: CONTROLLED_PATH },
|
|
2780
|
+
}));
|
|
2781
|
+
} catch (error) {
|
|
2782
|
+
throw new CodexAppServerError(
|
|
2783
|
+
'could not inspect the owned app-server process group',
|
|
2784
|
+
'CODEX_PROCESS_CLEANUP_UNVERIFIED',
|
|
2785
|
+
{ cause: error },
|
|
2786
|
+
);
|
|
2787
|
+
}
|
|
2788
|
+
return stdout
|
|
2789
|
+
.split('\n')
|
|
2790
|
+
.map((line) => line.trim().split(/\s+/).map(Number))
|
|
2791
|
+
.filter(([pid, pgid]) => (
|
|
2792
|
+
Number.isSafeInteger(pid)
|
|
2793
|
+
&& Number.isSafeInteger(pgid)
|
|
2794
|
+
&& pgid === this.child.pid
|
|
2795
|
+
))
|
|
2796
|
+
.map(([pid]) => pid);
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
async _waitForOnlySupervisor(timeoutMs) {
|
|
2800
|
+
const deadline = Date.now() + timeoutMs;
|
|
2801
|
+
while (this._childAlive() && Date.now() < deadline) {
|
|
2802
|
+
const members = await this._ownedGroupMembers();
|
|
2803
|
+
if (members.length === 1 && members[0] === this.child.pid) return true;
|
|
2804
|
+
await this._delay(Math.min(20, Math.max(1, deadline - Date.now())));
|
|
2805
|
+
}
|
|
2806
|
+
return false;
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
close() {
|
|
2810
|
+
if (this.closePromise) return this.closePromise;
|
|
2811
|
+
this.closePromise = this._close();
|
|
2812
|
+
return this.closePromise;
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
async _close() {
|
|
2816
|
+
if (this.state === 'closed') return;
|
|
2817
|
+
this.state = 'closing';
|
|
2818
|
+
this._invalidateSinks();
|
|
2819
|
+
this._rejectAll(new CodexAppServerError(
|
|
2820
|
+
'app-server client closed',
|
|
2821
|
+
'CODEX_CLIENT_CLOSED',
|
|
2822
|
+
));
|
|
2823
|
+
let cleanupError = null;
|
|
2824
|
+
if (this._childAlive()) {
|
|
2825
|
+
try { this.child.stdin.end(); } catch {}
|
|
2826
|
+
this._signalOwnedTree('SIGTERM');
|
|
2827
|
+
let onlySupervisor = false;
|
|
2828
|
+
try {
|
|
2829
|
+
onlySupervisor = await this._waitForOnlySupervisor(this.closeGraceMs);
|
|
2830
|
+
} catch (error) {
|
|
2831
|
+
cleanupError = error;
|
|
2832
|
+
}
|
|
2833
|
+
if (onlySupervisor && this._childAlive()) {
|
|
2834
|
+
try {
|
|
2835
|
+
this.killFn(this.child.pid, 'SIGUSR1');
|
|
2836
|
+
} catch (error) {
|
|
2837
|
+
if (error?.code !== 'ESRCH') cleanupError ??= error;
|
|
2838
|
+
}
|
|
2839
|
+
await this._waitForExit(this.closeKillMs);
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
if (this._childAlive()) {
|
|
2843
|
+
this._signalOwnedTree('SIGKILL');
|
|
2844
|
+
await this._waitForExit(this.closeKillMs);
|
|
2845
|
+
}
|
|
2846
|
+
if (this._childAlive()) {
|
|
2847
|
+
throw new CodexAppServerError(
|
|
2848
|
+
'app-server child survived kill escalation',
|
|
2849
|
+
'CODEX_PROCESS_CLOSE_TIMEOUT',
|
|
2850
|
+
);
|
|
2851
|
+
}
|
|
2852
|
+
this.stdoutBuffer = '';
|
|
2853
|
+
this.state = 'closed';
|
|
2854
|
+
if (!this.protocolError) this.resolveFaultWait(null);
|
|
2855
|
+
if (cleanupError) throw cleanupError;
|
|
2856
|
+
}
|
|
2857
|
+
}
|
|
2858
|
+
|
|
2859
|
+
module.exports = {
|
|
2860
|
+
CodexAppServerClient,
|
|
2861
|
+
CodexAppServerError,
|
|
2862
|
+
attestPinnedCodexBinary,
|
|
2863
|
+
attestPinnedCodexHome,
|
|
2864
|
+
buildCodexAppServerEnv,
|
|
2865
|
+
protocolSchema,
|
|
2866
|
+
};
|