vibekit-agent 1.5.4 → 1.6.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.
@@ -0,0 +1,708 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CodexEngine = exports.VKCONFIG_SERVER = exports.CODEX_TESTED_VERSION = void 0;
37
+ exports.findCodexBinary = findCodexBinary;
38
+ exports.codexLoggedIn = codexLoggedIn;
39
+ exports.isOlderVersion = isOlderVersion;
40
+ exports.mcpConfig = mcpConfig;
41
+ /**
42
+ * codex-engine.ts: drives OpenAI's Codex CLI through `codex app-server`
43
+ * (newline-delimited JSON-RPC over stdio, no `jsonrpc` field) for Remote mode.
44
+ * Design and the protocol facts it relies on: docs/remote-codex-plan.md.
45
+ *
46
+ * WHY app-server AND NOT `codex exec --json`: exec has no approval channel, so
47
+ * "Ask before actions" could not exist. app-server sends approval requests to
48
+ * the client and waits for the answer.
49
+ *
50
+ * One app-server child lives for the life of the agent process, started on the
51
+ * first Codex message. Unlike a Claude run it outlives each turn, so it is
52
+ * killed on every exit path, including the self-update restart that calls
53
+ * process.exit directly.
54
+ *
55
+ * Only stable protocol methods are used: `initialize` declares no
56
+ * experimentalApi. Every mapping from Codex events to VibeKit frames is in the
57
+ * pure codex-translate.ts.
58
+ */
59
+ const child_process_1 = require("child_process");
60
+ const string_decoder_1 = require("string_decoder");
61
+ const fs = __importStar(require("fs"));
62
+ const os = __importStar(require("os"));
63
+ const path = __importStar(require("path"));
64
+ const codex_translate_1 = require("./codex-translate");
65
+ /** The newest Codex CLI this engine was checked against. Older versions still run, with a warning. */
66
+ exports.CODEX_TESTED_VERSION = '0.154.0';
67
+ /** How long an interrupted turn gets to report `interrupted` before the app-server is killed. */
68
+ const INTERRUPT_GRACE_MS = 5_000;
69
+ /** Control requests (initialize, account/read, thread/start) that take longer than this count as a failed start. */
70
+ const REQUEST_TIMEOUT_MS = 60_000;
71
+ /** Avoid a tight respawn loop when an installed app-server cannot initialize. */
72
+ const START_RETRY_BACKOFF_MS = 1_000;
73
+ /** The self-config MCP server's name. Its tool calls never need a phone tap, the same as on Claude. */
74
+ exports.VKCONFIG_SERVER = 'vkconfig';
75
+ function searchPath() {
76
+ const home = os.homedir();
77
+ return [
78
+ path.dirname(process.execPath), // the npm `codex` shim is a node script
79
+ path.join(home, '.local', 'bin'),
80
+ '/opt/homebrew/bin',
81
+ '/usr/local/bin',
82
+ path.join(home, '.npm-global', 'bin'),
83
+ process.env.PATH || '',
84
+ ].join(':');
85
+ }
86
+ /** `codex --version` for one candidate, or null when it does not run (a broken install counts as absent). */
87
+ function codexVersion(binary) {
88
+ try {
89
+ const out = (0, child_process_1.execFileSync)(binary, ['--version'], {
90
+ encoding: 'utf8',
91
+ timeout: 15_000,
92
+ stdio: ['ignore', 'pipe', 'pipe'],
93
+ env: { ...process.env, PATH: searchPath() },
94
+ });
95
+ return /(\d+\.\d+\.\d+)/.exec(out)?.[1] ?? null;
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
101
+ /**
102
+ * Find a Codex CLI that actually runs. Existence is not enough: an npm install
103
+ * that lost its platform binary still leaves a `codex` shim that fails with
104
+ * ENOENT on every call, which would otherwise surface as a failure on every
105
+ * message instead of a clear "not installed".
106
+ */
107
+ function findCodexBinary(log = console.log) {
108
+ const home = os.homedir();
109
+ const candidates = [];
110
+ if (process.env.CODEX_PATH)
111
+ candidates.push(process.env.CODEX_PATH);
112
+ try {
113
+ const found = (0, child_process_1.execFileSync)('which', ['-a', 'codex'], {
114
+ encoding: 'utf8',
115
+ env: { ...process.env, PATH: searchPath() },
116
+ stdio: ['ignore', 'pipe', 'ignore'],
117
+ });
118
+ candidates.push(...found.split('\n').map((s) => s.trim()).filter(Boolean));
119
+ }
120
+ catch { /* not on PATH */ }
121
+ try {
122
+ const prefix = (0, child_process_1.execFileSync)('npm', ['prefix', '-g'], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
123
+ if (prefix)
124
+ candidates.push(path.join(prefix, 'bin', 'codex'));
125
+ }
126
+ catch { /* no npm */ }
127
+ candidates.push('/opt/homebrew/bin/codex', '/usr/local/bin/codex', path.join(home, '.npm-global', 'bin', 'codex'));
128
+ const seen = new Set();
129
+ for (const candidate of candidates) {
130
+ if (seen.has(candidate) || !fs.existsSync(candidate))
131
+ continue;
132
+ seen.add(candidate);
133
+ const version = codexVersion(candidate);
134
+ if (version)
135
+ return { path: candidate, version };
136
+ log(`Skipping ${candidate}: \`codex --version\` fails there, so that install looks broken.`);
137
+ }
138
+ return null;
139
+ }
140
+ /** Whether this Codex is logged in, from `codex login status` (exits 1 with "Not logged in"). Null when that cannot be told. */
141
+ function codexLoggedIn(binary) {
142
+ try {
143
+ (0, child_process_1.execFileSync)(binary, ['login', 'status'], { encoding: 'utf8', timeout: 15_000, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PATH: searchPath() } });
144
+ return true;
145
+ }
146
+ catch (e) {
147
+ return e?.status === 1 && /not logged in/i.test(`${e?.stdout || ''}${e?.stderr || ''}`) ? false : null;
148
+ }
149
+ }
150
+ /** True when `version` is a lower release than `floor`. Unparseable counts as not older. */
151
+ function isOlderVersion(version, floor) {
152
+ const parse = (v) => /^(\d+)\.(\d+)\.(\d+)/.exec(v)?.slice(1).map(Number);
153
+ const a = parse(version);
154
+ const b = parse(floor);
155
+ if (!a || !b)
156
+ return false;
157
+ for (let i = 0; i < 3; i++)
158
+ if (a[i] !== b[i])
159
+ return a[i] < b[i];
160
+ return false;
161
+ }
162
+ class CodexRpcError extends Error {
163
+ code;
164
+ constructor(message, code) {
165
+ super(message);
166
+ this.code = code;
167
+ }
168
+ }
169
+ /** mcp_servers.* dotted keys for thread/start's `config`. */
170
+ function mcpConfig(servers) {
171
+ const config = {};
172
+ for (const [name, spec] of Object.entries(servers)) {
173
+ config[`mcp_servers.${name}.command`] = spec.command;
174
+ config[`mcp_servers.${name}.args`] = spec.args;
175
+ config[`mcp_servers.${name}.env`] = spec.env;
176
+ if (spec.approvalMode)
177
+ config[`mcp_servers.${name}.default_tools_approval_mode`] = spec.approvalMode;
178
+ }
179
+ return config;
180
+ }
181
+ class CodexEngine {
182
+ binary;
183
+ clientVersion;
184
+ static liveEngines = new Set();
185
+ static exitHookInstalled = false;
186
+ child = null;
187
+ starting = null;
188
+ ready = false;
189
+ nextStartAt = 0;
190
+ nextId = 1;
191
+ pending = new Map();
192
+ stderrTail = '';
193
+ loggedIn = false;
194
+ threadId = null;
195
+ threadCwd = null;
196
+ threadAccess = null;
197
+ conversationGeneration = 0;
198
+ retiredThreads = new Set();
199
+ /** The app-server restarted since the thread was created, so it must be resumed before its next turn. */
200
+ threadNeedsResume = false;
201
+ /** The thread carries a model override. turn/start's `model` persists, so clearing it needs a new thread. */
202
+ threadHasModelOverride = false;
203
+ turn = null;
204
+ lastTurnDone = Promise.resolve();
205
+ /** Turns run one at a time, so only the last finished one can still send late events. */
206
+ lastFinishedTurnId = null;
207
+ /** Model ids from model/list, for validating a model change from chat. Empty until the first turn. */
208
+ models = [];
209
+ /** When the plan's exhausted rate-limit window resets (epoch seconds), for the usage-limit reply. */
210
+ rateLimitResetsAtSec = null;
211
+ /** A clean policy home shares authentication but cannot load personal/project allow rules. */
212
+ policyHome;
213
+ constructor(binary, clientVersion) {
214
+ this.binary = binary;
215
+ this.clientVersion = clientVersion;
216
+ this.policyHome = fs.mkdtempSync(path.join(os.tmpdir(), 'vibekit-codex-policy-'));
217
+ const sourceHome = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
218
+ try {
219
+ fs.symlinkSync(path.join(sourceHome, 'auth.json'), path.join(this.policyHome, 'auth.json'));
220
+ }
221
+ catch { /* a read-only/keychain login needs no file link */ }
222
+ }
223
+ /** Start a turn. `stop()` interrupts it; `done` always resolves, never rejects. */
224
+ startTurn(req, hooks) {
225
+ let resolve;
226
+ const done = new Promise((r) => { resolve = r; });
227
+ const turn = {
228
+ translator: new codex_translate_1.CodexTurnTranslator(), hooks, threadId: null, id: null,
229
+ conversationGeneration: this.conversationGeneration, retireThreadAfterFinish: false,
230
+ stopRequested: false, finished: false, killTimer: null, resolve,
231
+ };
232
+ const previous = this.lastTurnDone;
233
+ this.lastTurnDone = done;
234
+ void this.drive(turn, req, previous);
235
+ return { done, stop: () => this.stopTurn(turn) };
236
+ }
237
+ /** Forget the conversation: the next turn starts a new thread. */
238
+ resetThread() {
239
+ this.conversationGeneration++;
240
+ const retired = this.threadId;
241
+ this.threadId = null;
242
+ this.threadCwd = null;
243
+ this.threadAccess = null;
244
+ this.threadNeedsResume = false;
245
+ this.threadHasModelOverride = false;
246
+ if (retired)
247
+ this.retireThread(retired);
248
+ }
249
+ /**
250
+ * Kill app-server now. The bookkeeping onExit would do happens here,
251
+ * synchronously: once `child` is null onExit ignores this process, and the
252
+ * next message must not wait for the exit event to learn the thread needs
253
+ * resuming or that pending requests are dead.
254
+ */
255
+ dispose() {
256
+ // A start in progress belongs to the process being killed. Without this,
257
+ // the next turn awaits that doomed start and fails with it.
258
+ this.starting = null;
259
+ this.ready = false;
260
+ const child = this.child;
261
+ CodexEngine.liveEngines.delete(this);
262
+ if (!child)
263
+ return;
264
+ this.child = null;
265
+ for (const [id, p] of this.pending) {
266
+ if (p.timer)
267
+ clearTimeout(p.timer);
268
+ p.reject(new Error('app-server was stopped'));
269
+ this.pending.delete(id);
270
+ }
271
+ if (this.threadId)
272
+ this.threadNeedsResume = true;
273
+ this.retiredThreads.clear();
274
+ try {
275
+ child.kill();
276
+ }
277
+ catch { /* already gone */ }
278
+ }
279
+ async drive(turn, req, previous) {
280
+ // An interrupted turn has to finish (or be killed) before the next one starts:
281
+ // app-server runs one turn per thread.
282
+ await previous;
283
+ if (turn.stopRequested)
284
+ return this.finishTurn(turn, { status: 'interrupted', text: '', toolCount: 0, error: null });
285
+ this.turn = turn;
286
+ try {
287
+ await this.ensureStarted();
288
+ if (!this.loggedIn) {
289
+ const account = await this.request('account/read', {});
290
+ this.loggedIn = !!account?.account;
291
+ if (!this.loggedIn) {
292
+ // `codex login` runs in another process. A running app-server caches
293
+ // its signed-out state, so force the resend path through a fresh one.
294
+ this.dispose();
295
+ return this.finishTurn(turn, { status: 'failed', text: '', toolCount: 0, error: { info: 'unauthorized', message: 'not logged in' } });
296
+ }
297
+ }
298
+ if (this.models.length === 0) {
299
+ try {
300
+ const list = await this.request('model/list', {});
301
+ const data = Array.isArray(list?.data) ? list.data : [];
302
+ this.models = [...new Set(data.flatMap((m) => [m?.model, m?.id]).filter((s) => typeof s === 'string' && !!s))];
303
+ }
304
+ catch { /* validation falls back to a shape check */ }
305
+ }
306
+ if (turn.stopRequested)
307
+ return this.finishTurn(turn, turn.translator.end({ status: 'interrupted' }));
308
+ turn.threadId = await this.ensureThread(req, turn);
309
+ if (turn.stopRequested)
310
+ return this.finishTurn(turn, turn.translator.end({ status: 'interrupted' }));
311
+ const policy = (0, codex_translate_1.codexPolicy)(req.access);
312
+ const input = [{ type: 'text', text: req.prompt, text_elements: [] }];
313
+ for (const p of req.imagePaths)
314
+ input.push({ type: 'localImage', path: p });
315
+ const started = await this.request('turn/start', {
316
+ threadId: turn.threadId,
317
+ input,
318
+ cwd: req.cwd,
319
+ approvalPolicy: policy.approvalPolicy,
320
+ sandboxPolicy: policy.sandboxPolicy,
321
+ ...(req.model ? { model: req.model } : {}),
322
+ });
323
+ if (req.model && this.threadId === turn.threadId && turn.conversationGeneration === this.conversationGeneration) {
324
+ this.threadHasModelOverride = true;
325
+ }
326
+ if (!turn.id && typeof started?.turn?.id === 'string')
327
+ turn.id = started.turn.id;
328
+ if (turn.stopRequested)
329
+ this.sendInterrupt(turn);
330
+ }
331
+ catch (e) {
332
+ const message = String(e?.message || e);
333
+ const info = /unknown (variant|field)/i.test(message)
334
+ ? 'unsupported'
335
+ : /initialize|initialization/i.test(message) ? 'startFailed' : this.child ? 'startFailed' : 'crashed';
336
+ this.finishTurn(turn, { status: 'failed', text: turn.translator.text, toolCount: turn.translator.toolCount, error: { info, message } });
337
+ }
338
+ }
339
+ stopTurn(turn) {
340
+ if (turn.finished || turn.stopRequested)
341
+ return;
342
+ turn.stopRequested = true;
343
+ if (this.turn === turn && turn.id)
344
+ this.sendInterrupt(turn);
345
+ // A turn that will not report `interrupted` is ended by killing app-server.
346
+ // The thread survives on disk and is resumed by the next turn. A turn still
347
+ // queued behind another never reached app-server, so it only finishes.
348
+ turn.killTimer = setTimeout(() => {
349
+ if (turn.finished)
350
+ return;
351
+ const holdsAppServer = this.turn === turn;
352
+ this.finishTurn(turn, turn.translator.end({ status: 'interrupted' }));
353
+ if (holdsAppServer)
354
+ this.dispose();
355
+ }, INTERRUPT_GRACE_MS);
356
+ }
357
+ sendInterrupt(turn) {
358
+ if (!turn.threadId || !turn.id)
359
+ return;
360
+ this.request('turn/interrupt', { threadId: turn.threadId, turnId: turn.id }).catch(() => { });
361
+ }
362
+ finishTurn(turn, end) {
363
+ if (turn.finished)
364
+ return;
365
+ turn.finished = true;
366
+ if (turn.killTimer)
367
+ clearTimeout(turn.killTimer);
368
+ if (this.turn === turn)
369
+ this.turn = null;
370
+ if (turn.id)
371
+ this.lastFinishedTurnId = turn.id;
372
+ if (end.error?.info === 'unauthorized') {
373
+ this.loggedIn = false;
374
+ this.dispose();
375
+ }
376
+ turn.resolve(end);
377
+ if (turn.threadId) {
378
+ if (turn.retireThreadAfterFinish)
379
+ this.retiredThreads.add(turn.threadId);
380
+ if (this.retiredThreads.has(turn.threadId))
381
+ this.unsubscribeThread(turn.threadId);
382
+ }
383
+ }
384
+ async ensureThread(req, turn) {
385
+ if (this.threadId && (this.threadCwd !== req.cwd || this.threadAccess !== req.access)) {
386
+ this.resetThread();
387
+ turn.conversationGeneration = this.conversationGeneration;
388
+ }
389
+ // Clearing the model from chat: the old override would stay on this thread,
390
+ // and a new thread picks up the user's own Codex default.
391
+ if (this.threadId && this.threadHasModelOverride && !req.model) {
392
+ this.resetThread();
393
+ turn.conversationGeneration = this.conversationGeneration;
394
+ }
395
+ const generation = turn.conversationGeneration;
396
+ const policy = (0, codex_translate_1.codexPolicy)(req.access);
397
+ const shared = {
398
+ cwd: req.cwd,
399
+ approvalPolicy: policy.approvalPolicy,
400
+ sandbox: policy.sandbox,
401
+ config: {
402
+ ...mcpConfig(req.mcpServers()),
403
+ // A read-only sandbox prevents writes, but it still exposes and runs
404
+ // shell commands. Remove the shell entirely; vkread supplies reads.
405
+ ...(req.access === 'read-only' ? { 'features.shell_tool': false } : {}),
406
+ },
407
+ ...(req.model ? { model: req.model } : {}),
408
+ };
409
+ const existingThread = generation === this.conversationGeneration ? this.threadId : null;
410
+ if (existingThread && this.threadNeedsResume) {
411
+ try {
412
+ await this.request('thread/resume', { threadId: existingThread, excludeTurns: true, ...shared });
413
+ if (generation === this.conversationGeneration && this.threadId === existingThread) {
414
+ this.threadNeedsResume = false;
415
+ this.threadAccess = req.access;
416
+ }
417
+ else {
418
+ turn.retireThreadAfterFinish = true;
419
+ }
420
+ return existingThread;
421
+ }
422
+ catch (e) {
423
+ // A thread whose first turn never completed was never saved.
424
+ if (!/no rollout/i.test(String(e?.message || e)))
425
+ throw e;
426
+ if (generation === this.conversationGeneration && this.threadId === existingThread) {
427
+ this.threadId = null;
428
+ this.threadCwd = null;
429
+ this.threadAccess = null;
430
+ this.threadNeedsResume = false;
431
+ this.threadHasModelOverride = false;
432
+ }
433
+ }
434
+ }
435
+ if (generation === this.conversationGeneration && this.threadId)
436
+ return this.threadId;
437
+ const res = await this.request('thread/start', shared);
438
+ if (typeof res?.thread?.id !== 'string')
439
+ throw new Error('thread/start returned no thread id');
440
+ const startedThread = res.thread.id;
441
+ if (generation === this.conversationGeneration && !this.threadId) {
442
+ this.threadId = startedThread;
443
+ this.threadCwd = req.cwd;
444
+ this.threadAccess = req.access;
445
+ this.threadNeedsResume = false;
446
+ }
447
+ else if (this.threadId !== startedThread) {
448
+ turn.retireThreadAfterFinish = true;
449
+ }
450
+ return startedThread;
451
+ }
452
+ retireThread(threadId) {
453
+ this.retiredThreads.add(threadId);
454
+ if (!this.turn || this.turn.threadId !== threadId)
455
+ this.unsubscribeThread(threadId);
456
+ }
457
+ /** Release app-server's subscription after the owning turn has consumed its final events. */
458
+ unsubscribeThread(threadId) {
459
+ if (!this.retiredThreads.delete(threadId) || !this.child || !this.ready)
460
+ return;
461
+ void this.request('thread/unsubscribe', { threadId }).catch(() => { });
462
+ }
463
+ async ensureStarted() {
464
+ if (this.starting)
465
+ return this.starting;
466
+ if (this.child && this.ready)
467
+ return;
468
+ if (this.child)
469
+ this.dispose();
470
+ const delay = this.nextStartAt - Date.now();
471
+ if (delay > 0)
472
+ await new Promise((resolve) => setTimeout(resolve, delay));
473
+ if (this.starting)
474
+ return this.starting;
475
+ if (this.child && this.ready)
476
+ return;
477
+ const start = this.spawnAndInitialize();
478
+ this.starting = start;
479
+ // Only clear it if it is still ours: dispose() may have dropped it and a
480
+ // newer start may already be in flight. The caller handles the rejection.
481
+ start.then(() => { }, () => { }).then(() => { if (this.starting === start)
482
+ this.starting = null; });
483
+ return start;
484
+ }
485
+ async spawnAndInitialize() {
486
+ this.stderrTail = '';
487
+ const child = (0, child_process_1.spawn)(this.binary, ['app-server'], {
488
+ stdio: ['pipe', 'pipe', 'pipe'],
489
+ // A clean config/rules directory is the enforcement boundary for
490
+ // supervised mode. auth.json is linked from the user's real Codex home.
491
+ env: { ...process.env, PATH: searchPath(), CODEX_HOME: this.policyHome },
492
+ });
493
+ this.child = child;
494
+ this.ready = false;
495
+ this.installExitHook();
496
+ const decoder = new string_decoder_1.StringDecoder('utf8');
497
+ let buffer = '';
498
+ child.stdout?.on('data', (chunk) => {
499
+ buffer += decoder.write(chunk);
500
+ let newline;
501
+ while ((newline = buffer.indexOf('\n')) >= 0) {
502
+ const line = buffer.slice(0, newline).trim();
503
+ buffer = buffer.slice(newline + 1);
504
+ if (line)
505
+ this.onLine(child, line);
506
+ }
507
+ });
508
+ child.stderr?.on('data', (chunk) => {
509
+ this.stderrTail = (this.stderrTail + chunk.toString()).slice(-8192);
510
+ });
511
+ child.stdin?.on('error', () => { });
512
+ child.on('error', (e) => this.onExit(child, `could not start ${this.binary} (${e.message})`));
513
+ child.on('exit', (code, signal) => this.onExit(child, `app-server exited (${signal || `code ${code}`})`));
514
+ try {
515
+ await this.request('initialize', {
516
+ clientInfo: { name: 'vibekit-agent', title: 'VibeKit Remote', version: this.clientVersion },
517
+ capabilities: { experimentalApi: false, requestAttestation: false },
518
+ });
519
+ if (this.child !== child)
520
+ throw new Error('app-server was replaced during initialization');
521
+ this.write(child, { method: 'initialized' });
522
+ this.ready = true;
523
+ this.nextStartAt = 0;
524
+ }
525
+ catch (error) {
526
+ if (this.child === child) {
527
+ this.nextStartAt = Date.now() + START_RETRY_BACKOFF_MS;
528
+ this.dispose();
529
+ }
530
+ throw error;
531
+ }
532
+ }
533
+ installExitHook() {
534
+ CodexEngine.liveEngines.add(this);
535
+ if (CodexEngine.exitHookInstalled)
536
+ return;
537
+ CodexEngine.exitHookInstalled = true;
538
+ // 'exit' listeners run synchronously on every exit, including
539
+ // process.exit() from the self-update restart, which skips shutdown().
540
+ process.on('exit', () => {
541
+ for (const engine of CodexEngine.liveEngines) {
542
+ try {
543
+ engine.child?.kill();
544
+ }
545
+ catch { /* already gone */ }
546
+ }
547
+ });
548
+ }
549
+ onExit(child, reason) {
550
+ if (this.child !== child)
551
+ return;
552
+ this.child = null;
553
+ this.ready = false;
554
+ CodexEngine.liveEngines.delete(this);
555
+ const lastLine = this.stderrTail.trim().split('\n').pop() || '';
556
+ const detail = lastLine ? `${reason}: ${lastLine.slice(0, 200)}` : reason;
557
+ for (const [id, p] of this.pending) {
558
+ if (p.timer)
559
+ clearTimeout(p.timer);
560
+ p.reject(new Error(detail));
561
+ this.pending.delete(id);
562
+ }
563
+ if (this.threadId)
564
+ this.threadNeedsResume = true;
565
+ this.retiredThreads.clear();
566
+ const turn = this.turn;
567
+ if (turn)
568
+ this.finishTurn(turn, { status: 'failed', text: turn.translator.text, toolCount: turn.translator.toolCount, error: { info: 'crashed', message: detail } });
569
+ }
570
+ write(child, message) {
571
+ try {
572
+ child.stdin?.write(JSON.stringify(message) + '\n');
573
+ }
574
+ catch { /* the exit handler reports a dead child */ }
575
+ }
576
+ request(method, params) {
577
+ const child = this.child;
578
+ if (!child)
579
+ return Promise.reject(new Error('Codex is not running'));
580
+ const id = this.nextId++;
581
+ return new Promise((resolve, reject) => {
582
+ // turn/start returns as soon as the turn is accepted; the turn itself is
583
+ // bounded by the agent's run timeout, not by this.
584
+ const timer = setTimeout(() => {
585
+ if (!this.pending.has(id))
586
+ return;
587
+ this.pending.delete(id);
588
+ reject(new Error(`${method} did not answer within ${REQUEST_TIMEOUT_MS / 1000}s`));
589
+ }, REQUEST_TIMEOUT_MS);
590
+ this.pending.set(id, { resolve, reject, timer });
591
+ this.write(child, { id, method, params });
592
+ });
593
+ }
594
+ onLine(child, line) {
595
+ // Output a killed app-server had already buffered must not reach the next turn.
596
+ if (child !== this.child)
597
+ return;
598
+ let msg;
599
+ try {
600
+ msg = JSON.parse(line);
601
+ }
602
+ catch {
603
+ return;
604
+ }
605
+ if (!msg || typeof msg !== 'object')
606
+ return;
607
+ if (msg.id !== undefined && msg.method === undefined) {
608
+ const p = this.pending.get(msg.id);
609
+ if (!p)
610
+ return;
611
+ this.pending.delete(msg.id);
612
+ if (p.timer)
613
+ clearTimeout(p.timer);
614
+ if (msg.error)
615
+ p.reject(new CodexRpcError(String(msg.error.message || 'request failed'), msg.error.code));
616
+ else
617
+ p.resolve(msg.result);
618
+ return;
619
+ }
620
+ if (msg.id !== undefined && typeof msg.method === 'string') {
621
+ void this.onServerRequest(child, msg.id, msg.method, msg.params || {});
622
+ return;
623
+ }
624
+ if (typeof msg.method === 'string')
625
+ this.onNotification(msg.method, msg.params || {});
626
+ }
627
+ onNotification(method, params) {
628
+ if (method === 'account/rateLimits/updated') {
629
+ const limits = params?.rateLimits;
630
+ const windows = [limits?.primary, limits?.secondary].filter(Boolean);
631
+ const exhausted = windows.find((w) => typeof w?.usedPercent === 'number' && w.usedPercent >= 100) || windows[0];
632
+ if (typeof exhausted?.resetsAt === 'number')
633
+ this.rateLimitResetsAtSec = exhausted.resetsAt;
634
+ return;
635
+ }
636
+ const turn = this.turn;
637
+ if (!turn)
638
+ return;
639
+ if (params?.threadId && params.threadId !== (turn.threadId ?? this.threadId))
640
+ return;
641
+ // Late events from a turn that already ended (an interrupt racing its tail).
642
+ const eventTurnId = typeof params?.turnId === 'string' ? params.turnId : (typeof params?.turn?.id === 'string' ? params.turn.id : null);
643
+ if (eventTurnId && eventTurnId === this.lastFinishedTurnId)
644
+ return;
645
+ if (turn.id && eventTurnId && eventTurnId !== turn.id)
646
+ return;
647
+ if (method === 'turn/started') {
648
+ if (!turn.id && eventTurnId)
649
+ turn.id = eventTurnId;
650
+ if (turn.stopRequested)
651
+ this.sendInterrupt(turn);
652
+ return;
653
+ }
654
+ if (method === 'turn/completed') {
655
+ this.finishTurn(turn, turn.translator.end(params?.turn));
656
+ return;
657
+ }
658
+ // Stop/timeout has already produced its user-facing result. Consume only
659
+ // the completion notification so late text and tool cards cannot follow it.
660
+ if (turn.stopRequested)
661
+ return;
662
+ for (const output of turn.translator.handle(method, params))
663
+ turn.hooks.output(output);
664
+ }
665
+ ownsApproval(child, turn, params) {
666
+ if (!turn || child !== this.child || this.turn !== turn || turn.finished || turn.stopRequested)
667
+ return false;
668
+ if (!turn.threadId || !turn.id)
669
+ return false;
670
+ return params?.threadId === turn.threadId && params?.turnId === turn.id;
671
+ }
672
+ /**
673
+ * Every server request gets an answer. They never time out on the server
674
+ * side, so one left unanswered hangs the turn until the run timeout.
675
+ */
676
+ async onServerRequest(child, id, method, params) {
677
+ const reply = (result) => this.write(child, { id, result });
678
+ const turn = this.turn;
679
+ switch (method) {
680
+ case 'item/commandExecution/requestApproval': {
681
+ if (!this.ownsApproval(child, turn, params))
682
+ return reply({ decision: 'decline' });
683
+ const { toolName, input } = turn.translator.commandApproval(params);
684
+ const allowed = await turn.hooks.approve(toolName, input).catch(() => false);
685
+ return reply({ decision: allowed && this.ownsApproval(child, turn, params) ? 'accept' : 'decline' });
686
+ }
687
+ case 'item/fileChange/requestApproval': {
688
+ if (!this.ownsApproval(child, turn, params))
689
+ return reply({ decision: 'decline' });
690
+ const { toolName, input } = turn.translator.fileChangeApproval(params);
691
+ const allowed = await turn.hooks.approve(toolName, input).catch(() => false);
692
+ return reply({ decision: allowed && this.ownsApproval(child, turn, params) ? 'accept' : 'decline' });
693
+ }
694
+ case 'mcpServer/elicitation/request':
695
+ // The self-config tools are always allowed on Claude (CONFIG_TOOL_NAMES
696
+ // in agent.ts). Declining here would break settings-by-chat exactly in
697
+ // supervised mode, where a loosening already gets its own phone tap.
698
+ if (params?.serverName === exports.VKCONFIG_SERVER && this.ownsApproval(child, turn, params)) {
699
+ return reply({ action: 'accept', content: {}, _meta: null });
700
+ }
701
+ return reply({ action: 'decline', content: null, _meta: null });
702
+ default:
703
+ this.write(child, { id, error: { code: -32601, message: `${method} is not supported by VibeKit Remote` } });
704
+ }
705
+ }
706
+ }
707
+ exports.CodexEngine = CodexEngine;
708
+ //# sourceMappingURL=codex-engine.js.map