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.
package/dist/agent.js CHANGED
@@ -47,6 +47,8 @@ const os = __importStar(require("os"));
47
47
  const path = __importStar(require("path"));
48
48
  const dns = __importStar(require("dns"));
49
49
  const config_1 = require("./config");
50
+ const codex_engine_1 = require("./codex-engine");
51
+ const codex_translate_1 = require("./codex-translate");
50
52
  /**
51
53
  * The self-config tools, by the names claude allowlists them under.
52
54
  *
@@ -172,7 +174,13 @@ function findClaudeBinary() {
172
174
  class AgentClient {
173
175
  config;
174
176
  ws = null;
175
- claudeProcess = null;
177
+ activeRun = null;
178
+ /** Which coding agent this machine runs. Decided at `link`; see start(). */
179
+ engine = 'claude';
180
+ /** The Codex app-server driver, created on the first Codex message and kept for the process. */
181
+ codex = null;
182
+ /** The Codex CLI that runs here; looked up again on each message while missing. */
183
+ codexBinary = null;
176
184
  caffeinateProcess = null;
177
185
  reconnectTimeout = null;
178
186
  reconnectDelay = 1000;
@@ -286,23 +294,23 @@ class AgentClient {
286
294
  // Used in the close handler to clear a stale currentSessionId if the
287
295
  // resume failed, instead of looping forever on the same dead id.
288
296
  resumedSessionThisRun = false;
289
- // Hard kill timer for a wedged Claude run. Mirrors the server's 5-min SSE
297
+ // Hard kill timer for a wedged run. Mirrors the server's 5-min SSE
290
298
  // ceiling at src/routes/remote-app.ts so client + server agree on "this
291
- // run is dead". Without this the agent's claudeProcess can sit forever on
299
+ // run is dead". Without this the active run can sit forever on
292
300
  // an infinite bash loop / stuck API call, blocking every subsequent
293
301
  // message and leaving the user staring at a spinner.
294
- claudeRunTimeout = null;
295
- static CLAUDE_RUN_TIMEOUT_MS = 5 * 60_000;
302
+ runTimeout = null;
303
+ static RUN_TIMEOUT_MS = 5 * 60_000;
296
304
  // Set when handleUserMessage acknowledged the cancellation of a previous
297
305
  // in-flight run before overwriting currentChatId. Stops the killed run's
298
306
  // 'close' handler from sending a "no response" fallback to the NEW chatId
299
307
  // (currentChatId has already moved on to the new message). Without this
300
308
  // flag, the new message's chat would receive a confusing "Agent exited
301
309
  // without a response (code -15)" before its real reply.
302
- /// Processes killed on purpose (supersede / Stop / run-timeout). Keyed by
303
- /// the process itself so a slow-dying old run can never consume a flag
310
+ /// Runs stopped on purpose (supersede / Stop / run-timeout). Keyed by
311
+ /// the run itself so a slow-dying old run can never consume a flag
304
312
  /// meant for the new one — the old shared boolean did exactly that.
305
- canceledProcs = new WeakSet();
313
+ canceledRuns = new WeakSet();
306
314
  // After a network change (Wi-Fi flap, sleep/wake), macOS's DNS resolver can
307
315
  // take 60-90s to come back. Without this flag we burn 1+2+4+8+16=31s on
308
316
  // attempts that are guaranteed to fail with ENOTFOUND. Set by the 'error'
@@ -373,14 +381,30 @@ class AgentClient {
373
381
  result = (await response.json());
374
382
  }
375
383
  rl.close();
384
+ const wasLinked = this.config.hasToken();
376
385
  this.config.setCredentials(result.token, result.wsUrl);
386
+ // The engine is decided HERE, not at `start`. By the time `start` runs
387
+ // every machine has a token, so it cannot tell a new link from a machine
388
+ // linked before Codex support, which must stay on Claude (start() pins
389
+ // those). A re-link keeps whatever engine was already chosen, and a
390
+ // re-link of a machine linked before Codex support stays on Claude.
391
+ const engine = this.config.getEngine()
392
+ ?? (wasLinked ? 'claude' : findClaudeBinary() ? 'claude' : (0, codex_engine_1.findCodexBinary)(() => { }) ? 'codex' : 'claude');
393
+ this.config.setEngine(engine);
377
394
  console.log('\nLinked successfully!');
378
395
  console.log('');
379
- console.log('Tip: connect Claude in the VibeKit app (Profile → Connect Claude)');
380
- console.log('and the agent signs Claude in automatically — no setup-token needed.');
396
+ if (engine === 'codex') {
397
+ console.log('This computer will run Codex (Claude Code was not found here).');
398
+ console.log('Make sure Codex is logged in on this computer: codex login');
399
+ }
400
+ else {
401
+ console.log('Tip: connect Claude in the VibeKit app (Profile → Connect Claude)');
402
+ console.log('and the agent signs Claude in automatically — no setup-token needed.');
403
+ }
381
404
  console.log('');
382
405
  console.log('Start the agent with:');
383
406
  console.log(' npx vibekit-agent start');
407
+ console.log('To switch coding agents later: npx vibekit-agent start --engine claude (or codex)');
384
408
  console.log('');
385
409
  }
386
410
  catch (error) {
@@ -399,26 +423,57 @@ class AgentClient {
399
423
  if (!autoMode) {
400
424
  this.config.setLastDirectory(this.workingDirectory);
401
425
  }
426
+ // No stored engine means this machine was linked before Codex support, so
427
+ // it runs Claude, and is pinned to it now. Detecting here instead would
428
+ // silently switch a user who relies on the npx Claude download and happens
429
+ // to have Codex installed. Auto mode (Docker) is Claude-only and never
430
+ // writes the config file.
431
+ if (!autoMode && !this.config.getEngine())
432
+ this.config.setEngine('claude');
433
+ this.engine = autoMode ? 'claude' : (this.config.getEngine() ?? 'claude');
402
434
  console.log(`Starting VibeKit Remote Agent...`);
403
435
  console.log(`Working directory: ${this.workingDirectory}`);
436
+ console.log(`Engine: ${this.engine === 'codex' ? 'Codex' : 'Claude Code'}`);
404
437
  // In auto mode, set up Claude credentials from the credentials file.
405
438
  // Otherwise, sign Claude in from the user's VibeKit account if they've
406
439
  // connected it there — so they don't need a separate `claude setup-token`.
407
440
  if (autoMode) {
408
441
  await this.setupAutoModeCredentials();
409
442
  }
410
- else {
443
+ else if (this.engine === 'claude') {
411
444
  await this.ensureAccountClaudeAuth();
412
445
  }
413
- // Check for claude binary at startup
414
- const claudePath = findClaudeBinary();
415
- if (claudePath) {
416
- console.log(`Claude Code found: ${claudePath}`);
446
+ if (this.engine === 'codex') {
447
+ // A candidate only counts if `codex --version` runs, so a broken install
448
+ // reads as not installed instead of failing every message.
449
+ this.codexBinary = (0, codex_engine_1.findCodexBinary)();
450
+ if (this.codexBinary) {
451
+ console.log(`Codex found: ${this.codexBinary.path} (v${this.codexBinary.version})`);
452
+ if ((0, codex_engine_1.isOlderVersion)(this.codexBinary.version, codex_engine_1.CODEX_TESTED_VERSION)) {
453
+ console.log(`This Codex is older than v${codex_engine_1.CODEX_TESTED_VERSION}, the version VibeKit Remote was tested with. If messages fail, run: npm i -g @openai/codex@latest`);
454
+ }
455
+ // Said here so a user at the terminal can fix it before the first
456
+ // message. The engine re-checks on each message, so logging in later
457
+ // needs no restart.
458
+ if ((0, codex_engine_1.codexLoggedIn)(this.codexBinary.path) === false) {
459
+ console.log('Codex is not logged in on this computer. Run `codex login`; messages work as soon as you do.');
460
+ }
461
+ }
462
+ else {
463
+ console.log('\nCodex not found. Install it with `npm i -g @openai/codex`, then run `codex login`.');
464
+ }
417
465
  }
418
466
  else {
419
- console.log('\nClaude Code not found locally — will auto-run via `npx @anthropic-ai/claude-code` on first message.');
420
- console.log('(First invocation downloads ~50MB and takes ~30s; cached thereafter.)');
421
- console.log('For a faster first message, install ahead of time: `claude install` or `npm install -g @anthropic-ai/claude-code`.\n');
467
+ // Check for claude binary at startup
468
+ const claudePath = findClaudeBinary();
469
+ if (claudePath) {
470
+ console.log(`Claude Code found: ${claudePath}`);
471
+ }
472
+ else {
473
+ console.log('\nClaude Code not found locally — will auto-run via `npx @anthropic-ai/claude-code` on first message.');
474
+ console.log('(First invocation downloads ~50MB and takes ~30s; cached thereafter.)');
475
+ console.log('For a faster first message, install ahead of time: `claude install` or `npm install -g @anthropic-ai/claude-code`.\n');
476
+ }
422
477
  }
423
478
  console.log('');
424
479
  // Prevent the laptop from idle-sleeping while the agent is running.
@@ -445,19 +500,7 @@ class AgentClient {
445
500
  runClaude(prompt) {
446
501
  // Find the claude binary
447
502
  const claudeBinary = findClaudeBinary();
448
- // Kill any existing process. If one is in flight, handleUserMessage already
449
- // sent a "canceled" reply to its chatId — the suppression flag below stops
450
- // the close handler from re-sending a misattributed fallback to the new
451
- // chat.
452
- if (this.claudeProcess) {
453
- this.canceledProcs.add(this.claudeProcess);
454
- this.claudeProcess.kill();
455
- this.denyAllPendingApprovals('Superseded by a new message.');
456
- }
457
- // Clear streaming state
458
- this.stopStreaming();
459
- this.clearStreamingFlush();
460
- this.currentMessageId = null;
503
+ this.supersedeActiveRun();
461
504
  // Build command arguments
462
505
  const allowedTools = this.config.getAllowedTools();
463
506
  // --include-partial-messages: emit assistant message chunks as they arrive
@@ -588,55 +631,25 @@ class AgentClient {
588
631
  // Log the invocation without echoing the user prompt.
589
632
  const redacted = spawnArgs.map((a, i, arr) => (arr[i - 1] === '-p' ? '"..."' : a)).join(' ');
590
633
  console.log(`\nRunning: ${command} ${redacted}`);
591
- // Every handler below closes over `proc` and gates on
592
- // `this.claudeProcess === proc`. A killed process's buffered stdout (and
634
+ // Every handler below closes over `run` and gates on
635
+ // `this.activeRun === run`. A killed process's buffered stdout (and
593
636
  // its close event) fire AFTER the next run has been assigned — without
594
637
  // the gates, the old run's tail text leaked into the new run's buffer and
595
- // the old close handler nulled the NEW process ref, which disarmed Stop,
638
+ // the old close handler nulled the NEW run, which disarmed Stop,
596
639
  // the 5-min kill timer, and the idle check that gates self-update.
597
640
  const proc = (0, child_process_1.spawn)(command, spawnArgs, {
598
641
  cwd: this.workingDirectory,
599
642
  env: process.env,
600
643
  stdio: ['ignore', 'pipe', 'pipe'],
601
644
  });
602
- this.claudeProcess = proc;
603
- // Hard 5-min kill timer. Mirrors the server's SSE inactivity ceiling so
604
- // a wedged Claude (infinite bash loop, stuck API call, --continue session
605
- // corruption) doesn't block every subsequent message indefinitely. Power
606
- // users on multi-hour bash can disable with VIBEKIT_AGENT_NO_TIMEOUT=1.
607
- if (this.claudeRunTimeout)
608
- clearTimeout(this.claudeRunTimeout);
609
- if (!process.env.VIBEKIT_AGENT_NO_TIMEOUT) {
610
- const chatIdAtStart = this.currentChatId;
611
- this.claudeRunTimeout = setTimeout(() => {
612
- // Only act if THIS process is still the current one — a new message
613
- // may have replaced it, in which case the cancellation handler runs.
614
- if (this.claudeProcess !== proc)
615
- return;
616
- console.log(`[Agent] Claude run exceeded ${AgentClient.CLAUDE_RUN_TIMEOUT_MS / 1000}s — killing`);
617
- if (chatIdAtStart) {
618
- this.sendResponse(chatIdAtStart, "_Run exceeded 5 minutes and was stopped. Try a smaller task or split it up._", 'complete');
619
- }
620
- // Mark canceled so the close handler doesn't double-send.
621
- this.canceledProcs.add(proc);
622
- try {
623
- proc.kill('SIGKILL');
624
- }
625
- catch { }
626
- }, AgentClient.CLAUDE_RUN_TIMEOUT_MS);
627
- }
628
- // Track the final result text from stream-json
629
- this.streamJsonResult = '';
630
- this.lastRunResultError = '';
631
- this.lastRunStderr = '';
632
- this.receivedPartialDeltas = false;
633
- this.streamJsonLineBuffer = '';
634
- this.lastStreamedLength = 0;
635
- this.activeToolCalls.clear();
636
- this.toolUseCountThisRun = 0;
637
- // Heartbeat statuses fire if Claude is slow to produce anything visible.
638
- // Real activity (tool/delta) cancels them in their handlers below.
639
- this.scheduleHeartbeats();
645
+ const run = {
646
+ engine: 'claude',
647
+ stop: (force) => { try {
648
+ proc.kill(force ? 'SIGKILL' : 'SIGTERM');
649
+ }
650
+ catch { /* already gone */ } },
651
+ };
652
+ this.beginRun(run);
640
653
  // Per-run UTF-8 decoder: a multibyte character (emoji, CJK, curly quote)
641
654
  // split across two stdout chunks decodes to U+FFFD with a plain
642
655
  // data.toString() — the corruption lands inside the JSON string, parses
@@ -644,7 +657,7 @@ class AgentClient {
644
657
  // sequence across chunks.
645
658
  const stdoutDecoder = new string_decoder_1.StringDecoder('utf8');
646
659
  proc.stdout?.on('data', (data) => {
647
- if (this.claudeProcess !== proc)
660
+ if (this.activeRun !== run)
648
661
  return; // superseded — not our buffer anymore
649
662
  const text = stdoutDecoder.write(data);
650
663
  // stream-json outputs one JSON object per line
@@ -661,34 +674,16 @@ class AgentClient {
661
674
  proc.stderr?.on('data', (data) => {
662
675
  const text = data.toString();
663
676
  process.stderr.write(text);
664
- if (this.claudeProcess !== proc)
677
+ if (this.activeRun !== run)
665
678
  return;
666
679
  // Keep the tail so the close handler can classify auth failures.
667
680
  this.lastRunStderr = (this.lastRunStderr + text).slice(-8192);
668
681
  });
669
682
  proc.on('close', (code) => {
670
- this.denyAllPendingApprovals('The run ended before this was answered.');
683
+ const settled = this.settleRun(run);
671
684
  console.log(`\nClaude exited with code ${code}`);
672
- const isCurrent = this.claudeProcess === proc;
673
- const wasCanceled = this.canceledProcs.has(proc);
674
- this.canceledProcs.delete(proc);
675
- // Timers belong to the CURRENT run — a superseded run's close must not
676
- // clear the timers runClaude just armed for its replacement.
677
- if (isCurrent) {
678
- if (this.claudeRunTimeout) {
679
- clearTimeout(this.claudeRunTimeout);
680
- this.claudeRunTimeout = null;
681
- }
682
- this.cancelHeartbeats();
683
- }
684
- // Killed on purpose (supersede / Stop / timeout): the kill site already
685
- // messaged the chat. Superseded-but-not-flagged (shouldn't happen, but
686
- // belt): also nothing to do — the new run owns all shared state.
687
- if (wasCanceled || !isCurrent) {
688
- if (isCurrent)
689
- this.claudeProcess = null;
685
+ if (!settled)
690
686
  return;
691
- }
692
687
  // Process any remaining buffered line
693
688
  const tail = stdoutDecoder.end();
694
689
  if (tail)
@@ -739,21 +734,11 @@ class AgentClient {
739
734
  else {
740
735
  // Claude exited without producing text. Don't claim success — be honest
741
736
  // so the user doesn't think we completed something we didn't.
742
- let fallback;
743
- if (code !== 0) {
744
- fallback = `Agent exited without a response (code ${code}). Please try again.`;
745
- }
746
- else if (toolCount > 0) {
747
- fallback = `Agent finished after ${toolCount} tool call${toolCount === 1 ? '' : 's'} but didn't write a reply. Expand the tool calls above to see what was done, or send another message to continue.`;
748
- }
749
- else {
750
- fallback = `Agent finished without producing a response. Try rephrasing or resending.`;
751
- }
752
737
  console.log(`[Agent] No result text collected, sending honest fallback (code=${code}, tools=${toolCount})`);
753
- this.sendResponse(this.currentChatId, fallback, 'complete');
738
+ this.sendResponse(this.currentChatId, this.noReplyFallback(code, toolCount), 'complete');
754
739
  }
755
740
  }
756
- this.claudeProcess = null;
741
+ this.activeRun = null;
757
742
  // Mark that we now have an active conversation for --continue on next message
758
743
  if (code === 0) {
759
744
  this.hasActiveConversation = true;
@@ -775,11 +760,11 @@ class AgentClient {
775
760
  });
776
761
  proc.on('error', (err) => {
777
762
  console.error('Failed to start claude:', err.message);
778
- if (this.claudeProcess !== proc)
763
+ if (this.activeRun !== run)
779
764
  return;
780
- if (this.claudeRunTimeout) {
781
- clearTimeout(this.claudeRunTimeout);
782
- this.claudeRunTimeout = null;
765
+ if (this.runTimeout) {
766
+ clearTimeout(this.runTimeout);
767
+ this.runTimeout = null;
783
768
  }
784
769
  this.cancelHeartbeats();
785
770
  this.stopStreaming();
@@ -787,8 +772,114 @@ class AgentClient {
787
772
  if (this.currentChatId && this.currentTelegramId) {
788
773
  this.sendResponse(this.currentChatId, `Error: Could not start Claude Code.\n\nPath: ${claudeBinary}\nError: ${err.message}`, 'complete');
789
774
  }
775
+ // This run is over and has replied. Node may or may not emit 'close'
776
+ // after a spawn 'error': marking it canceled stops a close from sending
777
+ // a second, fallback reply, and releasing it here stops a missing close
778
+ // from blocking every later message.
779
+ this.canceledRuns.add(run);
780
+ this.activeRun = null;
790
781
  });
791
782
  }
783
+ /**
784
+ * Stop whatever run is in flight because a new message is starting one.
785
+ * handleUserMessage already sent a "canceled" reply to the old chat, and
786
+ * marking the run canceled stops its end handler from sending a
787
+ * misattributed fallback to the new chat.
788
+ */
789
+ supersedeActiveRun() {
790
+ if (this.activeRun) {
791
+ this.canceledRuns.add(this.activeRun);
792
+ this.activeRun.stop();
793
+ this.denyAllPendingApprovals('Superseded by a new message.');
794
+ }
795
+ this.stopStreaming();
796
+ this.clearStreamingFlush();
797
+ this.currentMessageId = null;
798
+ }
799
+ /**
800
+ * Bookkeeping every run shares, whichever engine runs it: it becomes the
801
+ * active run, gets the hard kill timer, starts from clean per-run state and
802
+ * gets the heartbeat statuses.
803
+ */
804
+ beginRun(run) {
805
+ this.activeRun = run;
806
+ // Hard 5-min kill timer. Mirrors the server's SSE inactivity ceiling so
807
+ // a wedged run (infinite bash loop, stuck API call, --continue session
808
+ // corruption) doesn't block every subsequent message indefinitely. Power
809
+ // users on multi-hour bash can disable with VIBEKIT_AGENT_NO_TIMEOUT=1.
810
+ if (this.runTimeout)
811
+ clearTimeout(this.runTimeout);
812
+ if (!process.env.VIBEKIT_AGENT_NO_TIMEOUT) {
813
+ const chatIdAtStart = this.currentChatId;
814
+ this.runTimeout = setTimeout(() => {
815
+ // Only act if THIS run is still the current one. A new message
816
+ // may have replaced it, in which case the cancellation handler runs.
817
+ if (this.activeRun !== run)
818
+ return;
819
+ console.log(`[Agent] ${run.engine} run exceeded ${AgentClient.RUN_TIMEOUT_MS / 1000}s, stopping`);
820
+ if (chatIdAtStart) {
821
+ this.sendResponse(chatIdAtStart, "_Run exceeded 5 minutes and was stopped. Try a smaller task or split it up._", 'complete');
822
+ }
823
+ // Mark canceled so the end handler doesn't double-send.
824
+ this.canceledRuns.add(run);
825
+ run.stop(true);
826
+ }, AgentClient.RUN_TIMEOUT_MS);
827
+ }
828
+ // Per-run state. The names come from the Claude stream-json parser, but
829
+ // the streaming flush and the no-reply fallback read them for every engine.
830
+ this.streamJsonResult = '';
831
+ this.lastRunResultError = '';
832
+ this.lastRunStderr = '';
833
+ this.receivedPartialDeltas = false;
834
+ this.streamJsonLineBuffer = '';
835
+ this.lastStreamedLength = 0;
836
+ this.activeToolCalls.clear();
837
+ this.toolUseCountThisRun = 0;
838
+ // Heartbeat statuses fire if the engine is slow to produce anything
839
+ // visible. Real activity (tool/delta) cancels them.
840
+ this.scheduleHeartbeats();
841
+ }
842
+ /**
843
+ * The shared start of a run's end. Returns false when there is nothing left
844
+ * to send: the run was stopped on purpose (Stop, supersede, timeout), whose
845
+ * stopper already messaged the chat, or it is no longer the active run.
846
+ */
847
+ settleRun(run) {
848
+ const isCurrent = this.activeRun === run;
849
+ const wasCanceled = this.canceledRuns.has(run);
850
+ this.canceledRuns.delete(run);
851
+ // Timers and pending approvals belong to the CURRENT run — a superseded
852
+ // run's slow exit must not clear the timers beginRun just armed for its
853
+ // replacement, or deny the replacement's approval cards. The superseded
854
+ // run's own approvals were denied when it was stopped.
855
+ if (isCurrent) {
856
+ this.denyAllPendingApprovals('The run ended before this was answered.');
857
+ if (this.runTimeout) {
858
+ clearTimeout(this.runTimeout);
859
+ this.runTimeout = null;
860
+ }
861
+ this.cancelHeartbeats();
862
+ }
863
+ // Stopped on purpose: the stop site already messaged the chat.
864
+ // Superseded-but-not-flagged: also nothing to do, the new run owns all
865
+ // shared state.
866
+ if (wasCanceled || !isCurrent) {
867
+ if (isCurrent)
868
+ this.activeRun = null;
869
+ return false;
870
+ }
871
+ return true;
872
+ }
873
+ /** The honest reply for a run that produced no text, so it never reads as a success. */
874
+ noReplyFallback(exitCode, toolCount) {
875
+ if (exitCode !== 0) {
876
+ return `Agent exited without a response (code ${exitCode}). Please try again.`;
877
+ }
878
+ if (toolCount > 0) {
879
+ return `Agent finished after ${toolCount} tool call${toolCount === 1 ? '' : 's'} but didn't write a reply. Expand the tool calls above to see what was done, or send another message to continue.`;
880
+ }
881
+ return `Agent finished without producing a response. Try rephrasing or resending.`;
882
+ }
792
883
  /**
793
884
  * Process a single line of stream-json output from Claude
794
885
  * Events include: system, assistant, tool_use, tool_result, result
@@ -1322,7 +1413,10 @@ class AgentClient {
1322
1413
  // `supervised` — that one is the server's, and reporting our copy
1323
1414
  // on every reconnect would fight the iOS toggle.
1324
1415
  model: this.config.getModel() || null,
1325
- allowedTools: this.config.getAllowedTools(),
1416
+ allowedTools: this.reportedAllowedTools(),
1417
+ // Additive (2026-09-14): lets the phone label the machine. Servers
1418
+ // older than Codex support ignore it.
1419
+ engine: this.engine,
1326
1420
  },
1327
1421
  timestamp: Date.now(),
1328
1422
  messageId: this.generateId(),
@@ -1341,6 +1435,7 @@ class AgentClient {
1341
1435
  clearHandshakeTimer();
1342
1436
  console.log('Disconnected from VibeKit');
1343
1437
  this.isConnected = false;
1438
+ this.denyAllPendingApprovals('The phone disconnected.');
1344
1439
  this.stopHeartbeatWatchdog();
1345
1440
  this.stopWakeWatchdog();
1346
1441
  this.scheduleReconnect();
@@ -1348,6 +1443,7 @@ class AgentClient {
1348
1443
  this.ws.on('error', (error) => {
1349
1444
  clearHandshakeTimer();
1350
1445
  this.isConnected = false;
1446
+ this.denyAllPendingApprovals('The phone connection failed.');
1351
1447
  if (handshakeAborted) {
1352
1448
  // Our own 10s watchdog aborted this handshake and already logged why.
1353
1449
  // ws emits 'close' straight after, which schedules the reconnect, so
@@ -1614,7 +1710,7 @@ class AgentClient {
1614
1710
  return;
1615
1711
  if (this.updateAttempted)
1616
1712
  return;
1617
- if (this.claudeProcess) {
1713
+ if (this.activeRun) {
1618
1714
  // Busy — don't interrupt a run. Leave updateAttempted unset so the next
1619
1715
  // reconnect (or the next idle auth) tries again.
1620
1716
  console.log(`[Auto-update] v${latest} available but a task is running — will update when idle.`);
@@ -1688,13 +1784,15 @@ class AgentClient {
1688
1784
  // runClaude) — the user's first message bubble + spinner just hung
1689
1785
  // forever with no signal. Now they see an explicit cancellation in
1690
1786
  // the original chat and the new message proceeds normally.
1691
- if (this.claudeProcess && this.currentChatId && this.currentChatId !== chatId) {
1787
+ if (this.activeRun && this.currentChatId && this.currentChatId !== chatId) {
1692
1788
  this.sendResponse(this.currentChatId, "_Canceled — you sent a new message before this one finished._", 'complete');
1693
1789
  }
1694
1790
  this.currentChatId = chatId;
1695
1791
  this.currentTelegramId = telegramId;
1696
1792
  this.currentReplyToMessageId = messageId;
1697
1793
  let prompt = text || '';
1794
+ // Codex gets images as real inputs (localImage), on top of the path in the prompt.
1795
+ const imagePaths = [];
1698
1796
  const attachmentInfo = attachments?.length ? ` with ${attachments.length} attachment(s)` : '';
1699
1797
  const source = chatId < 0 ? 'iOS' : 'Telegram';
1700
1798
  console.log(`\nReceived from ${source}: ${text || '(no text)'}${attachmentInfo}`);
@@ -1711,6 +1809,7 @@ class AgentClient {
1711
1809
  else if (file.type === 'image') {
1712
1810
  // For images, ask Claude to analyze
1713
1811
  prompt = `[Image saved to: ${file.path}]\n\nPlease analyze this image.\n\n${prompt}`.trim();
1812
+ imagePaths.push(file.path);
1714
1813
  }
1715
1814
  else {
1716
1815
  // For documents, mention the file
@@ -1731,8 +1830,137 @@ class AgentClient {
1731
1830
  // (handleSSE replaces streamingText on each `text` event). Without it,
1732
1831
  // a slow spawn looks identical to a hung agent.
1733
1832
  this.sendStreaming(chatId, 'Starting…');
1734
- // Run claude with the prompt (stream-json will send status updates)
1735
- this.runClaude(prompt);
1833
+ // Run the engine (its events send status updates)
1834
+ if (this.engine === 'codex') {
1835
+ this.runCodex(prompt, imagePaths);
1836
+ }
1837
+ else {
1838
+ this.runClaude(prompt);
1839
+ }
1840
+ }
1841
+ /**
1842
+ * Run one Codex turn through app-server. Shares the run bookkeeping with
1843
+ * runClaude (supersedeActiveRun, beginRun, settleRun), so Stop, supersede,
1844
+ * the run timeout and the self-update idle check behave the same. Every
1845
+ * event mapping is in codex-translate.ts.
1846
+ */
1847
+ runCodex(prompt, imagePaths) {
1848
+ this.supersedeActiveRun();
1849
+ const chatId = this.currentChatId;
1850
+ // Looked up again while missing, so installing Codex works from the next message.
1851
+ if (!this.codexBinary)
1852
+ this.codexBinary = (0, codex_engine_1.findCodexBinary)();
1853
+ const binary = this.codexBinary;
1854
+ if (!binary) {
1855
+ if (chatId)
1856
+ this.sendResponse(chatId, codex_translate_1.CODEX_NOT_INSTALLED, 'complete');
1857
+ return;
1858
+ }
1859
+ if (!this.codex || this.codex.binary !== binary.path) {
1860
+ this.codex?.dispose();
1861
+ this.codex = new codex_engine_1.CodexEngine(binary.path, AGENT_VERSION);
1862
+ }
1863
+ const codex = this.codex;
1864
+ let stopTurn = null;
1865
+ const run = { engine: 'codex', stop: () => stopTurn?.() };
1866
+ this.beginRun(run);
1867
+ const access = (0, config_1.codexAccessFor)(this.config.getAllowedTools(), this.currentSupervised);
1868
+ const cwd = this.workingDirectory;
1869
+ const turn = codex.startTurn({
1870
+ prompt,
1871
+ imagePaths,
1872
+ cwd,
1873
+ model: this.config.getModel(),
1874
+ access,
1875
+ mcpServers: () => this.codexMcpServers(codex, access, cwd),
1876
+ }, {
1877
+ output: (o) => {
1878
+ if (this.activeRun !== run || this.canceledRuns.has(run))
1879
+ return;
1880
+ this.cancelHeartbeats();
1881
+ if (o.kind === 'text') {
1882
+ this.streamJsonResult = o.text;
1883
+ this.scheduleStreamingFlush();
1884
+ }
1885
+ else if (o.kind === 'status') {
1886
+ this.sendStatusUpdate(o.text);
1887
+ }
1888
+ else if (this.currentChatId) {
1889
+ this.send({
1890
+ type: 'tool_invocation',
1891
+ payload: { chatId: this.currentChatId, ...o.tool },
1892
+ timestamp: Date.now(),
1893
+ messageId: this.generateId(),
1894
+ });
1895
+ }
1896
+ },
1897
+ approve: async (toolName, input) => {
1898
+ if (this.activeRun !== run || this.canceledRuns.has(run))
1899
+ return false;
1900
+ return (await this.askPhone(toolName, input)).behavior === 'allow';
1901
+ },
1902
+ });
1903
+ stopTurn = turn.stop;
1904
+ void turn.done.then((end) => this.endCodexRun(run, end, codex));
1905
+ }
1906
+ endCodexRun(run, end, codex) {
1907
+ const settled = this.settleRun(run);
1908
+ console.log(`\nCodex turn ended: ${end.status}${end.error ? ` (${end.error.info})` : ''}`);
1909
+ if (!settled)
1910
+ return;
1911
+ this.stopStreaming();
1912
+ this.clearStreamingFlush();
1913
+ if (this.currentChatId && this.currentTelegramId) {
1914
+ const narration = end.text.trim();
1915
+ if (end.status === 'completed') {
1916
+ this.sendResponse(this.currentChatId, narration || this.noReplyFallback(0, end.toolCount), 'complete');
1917
+ }
1918
+ else {
1919
+ // A normal `complete` reply, never `status: 'error'`: iOS rewrites the
1920
+ // text of SSE error events with Claude-specific help, on every build
1921
+ // in the wild. Narration the user watched stays above the error.
1922
+ const errLine = end.error
1923
+ ? (0, codex_translate_1.codexErrorReply)(end.error, { resetsAtSec: codex.rateLimitResetsAtSec, testedVersion: codex_engine_1.CODEX_TESTED_VERSION })
1924
+ : 'Codex ended this run before it finished. Send your message again.';
1925
+ this.sendResponse(this.currentChatId, narration ? `${narration}\n\n_${errLine}_` : errLine, 'complete');
1926
+ }
1927
+ }
1928
+ this.activeRun = null;
1929
+ }
1930
+ /** Per-thread MCP tools. Read-only mode gets filesystem readers because its native shell is disabled. */
1931
+ codexMcpServers(codex, access, cwd) {
1932
+ const configScript = path.join(__dirname, 'config-mcp.js');
1933
+ const servers = {};
1934
+ if (this.controlPort && fs.existsSync(configScript)) {
1935
+ servers[codex_engine_1.VKCONFIG_SERVER] = {
1936
+ command: process.execPath,
1937
+ args: [configScript],
1938
+ env: { VK_CONFIG_PORT: String(this.controlPort), VK_ENGINE: 'codex', VK_MODELS: codex.models.join(',') },
1939
+ // The config tools never need a tap, the same as CONFIG_TOOL_NAMES on
1940
+ // Claude; a loosening already asks the phone inside the tool itself.
1941
+ // 'approve', not 'auto': measured live on Codex 0.154.0, 'auto' still
1942
+ // requires approval (an elicitation when supervised, a hard failure
1943
+ // under approvalPolicy never), 'approve' runs the tool.
1944
+ approvalMode: 'approve',
1945
+ };
1946
+ }
1947
+ const readScript = path.join(__dirname, 'codex-read-mcp.js');
1948
+ if (access === 'read-only' && fs.existsSync(readScript)) {
1949
+ servers.vkread = {
1950
+ command: process.execPath,
1951
+ args: [readScript],
1952
+ env: { VK_READ_ROOT: cwd },
1953
+ // Read-only runs under approvalPolicy never, where a tool that needs
1954
+ // approval simply fails: with 'auto' every read failed in the live test.
1955
+ approvalMode: 'approve',
1956
+ };
1957
+ }
1958
+ return servers;
1959
+ }
1960
+ /** The tool list the phone is shown: the raw list for Claude, and for Codex the access actually in force. */
1961
+ reportedAllowedTools() {
1962
+ const tools = this.config.getAllowedTools();
1963
+ return this.engine === 'codex' ? (0, config_1.codexReportedTools)(tools) : tools;
1736
1964
  }
1737
1965
  /**
1738
1966
  * Save attachments to temp directory and return file paths
@@ -1772,6 +2000,7 @@ class AgentClient {
1772
2000
  handleNewConversation() {
1773
2001
  this.hasActiveConversation = false;
1774
2002
  this.currentSessionId = null;
2003
+ this.codex?.resetThread();
1775
2004
  console.log('Conversation reset - next message will start fresh');
1776
2005
  }
1777
2006
  /**
@@ -1949,6 +2178,15 @@ class AgentClient {
1949
2178
  describeConfig() {
1950
2179
  const model = this.config.getModel();
1951
2180
  const tools = this.config.getAllowedTools();
2181
+ if (this.engine === 'codex') {
2182
+ return [
2183
+ 'Engine: Codex',
2184
+ `Model: ${model || 'Codex default'}`,
2185
+ `Tool access: ${(0, config_1.codexAccessFor)(tools, false) === 'full' ? 'full (edits and commands allowed)' : 'read-only (no edits, no commands)'}`,
2186
+ `Working directory: ${this.workingDirectory}`,
2187
+ `Supervised mode: ${this.currentSupervised ? 'on' : 'off'}`,
2188
+ ].join('\n');
2189
+ }
1952
2190
  return [
1953
2191
  `Model: ${model || 'default (whatever your claude install picks)'}`,
1954
2192
  `Allowed tools: ${tools.length === 0 ? 'all (no restrictions)' : tools.join(', ')}`,
@@ -1990,8 +2228,17 @@ class AgentClient {
1990
2228
  const m = raw.model;
1991
2229
  if (m !== null && typeof m !== 'string')
1992
2230
  return { ok: false, text: 'model must be a string, or null to clear it.' };
1993
- if (typeof m === 'string' && !(0, config_1.isValidModel)(m)) {
1994
- return { ok: false, text: `"${m}" is not a model name claude accepts. Use opus, sonnet, haiku, or a full claude model id.` };
2231
+ if (typeof m === 'string' && !(0, config_1.isValidModel)(m, this.engine)) {
2232
+ return {
2233
+ ok: false,
2234
+ text: this.engine === 'codex'
2235
+ ? `"${m}" is not a Codex model name.`
2236
+ : `"${m}" is not a model name claude accepts. Use opus, sonnet, haiku, or a full claude model id.`,
2237
+ };
2238
+ }
2239
+ const codexModels = this.engine === 'codex' ? (this.codex?.models ?? []) : [];
2240
+ if (typeof m === 'string' && codexModels.length > 0 && !codexModels.includes(m.trim())) {
2241
+ return { ok: false, text: `"${m}" is not a model this Codex offers. Available: ${codexModels.join(', ')}.` };
1995
2242
  }
1996
2243
  next.model = m;
1997
2244
  }
@@ -2001,6 +2248,11 @@ class AgentClient {
2001
2248
  return { ok: false, text: 'allowedTools must be an array of tool names.' };
2002
2249
  }
2003
2250
  next.allowedTools = t.map((x) => x.trim());
2251
+ // Codex cannot honor a list allowing edits but not commands (or the
2252
+ // reverse). Refuse it by name rather than store a setting not in force.
2253
+ const problem = this.engine === 'codex' ? (0, config_1.codexToolListProblem)(next.allowedTools) : null;
2254
+ if (problem)
2255
+ return { ok: false, text: `${problem} Nothing changed.` };
2004
2256
  }
2005
2257
  if ('cwd' in raw) {
2006
2258
  if (typeof raw.cwd !== 'string' || !raw.cwd.trim())
@@ -2071,6 +2323,12 @@ class AgentClient {
2071
2323
  if (next.supervised !== undefined) {
2072
2324
  applied.push(`supervised mode ${next.supervised ? 'on' : 'off'}`);
2073
2325
  }
2326
+ if (this.engine === 'codex'
2327
+ && (next.model !== undefined || next.allowedTools !== undefined || next.supervised !== undefined)) {
2328
+ // These are thread-scoped in Codex. Retire the old subscription now,
2329
+ // even if the user never sends the "next message" mentioned below.
2330
+ this.codex?.resetThread();
2331
+ }
2074
2332
  // Tell the server, so the phone shows the same thing and `supervised`
2075
2333
  // (which is server-owned, on the remote_agents row) actually persists.
2076
2334
  this.sendConfigState(next.supervised);
@@ -2090,7 +2348,7 @@ class AgentClient {
2090
2348
  type: 'config_state',
2091
2349
  payload: {
2092
2350
  model: this.config.getModel() || null,
2093
- allowedTools: this.config.getAllowedTools(),
2351
+ allowedTools: this.reportedAllowedTools(),
2094
2352
  workingDirectory: this.workingDirectory,
2095
2353
  ...(supervised === undefined ? {} : { supervised }),
2096
2354
  },
@@ -2105,23 +2363,21 @@ class AgentClient {
2105
2363
  }
2106
2364
  }
2107
2365
  handleCancel() {
2108
- if (!this.claudeProcess) {
2366
+ const run = this.activeRun;
2367
+ if (!run) {
2109
2368
  console.log('[Agent] Cancel received — no run in flight (no-op)');
2110
2369
  this.sendStatus('idle');
2111
2370
  return;
2112
2371
  }
2113
- console.log('[Agent] Cancel received — stopping current Claude run');
2372
+ console.log(`[Agent] Cancel received, stopping the current ${run.engine} run`);
2114
2373
  this.denyAllPendingApprovals('Task was stopped from the app.');
2115
- this.canceledProcs.add(this.claudeProcess);
2374
+ this.canceledRuns.add(run);
2116
2375
  this.cancelHeartbeats();
2117
2376
  this.stopStreaming();
2118
2377
  // Kill the pending debounced frame so no streaming text lands after the
2119
2378
  // "⏹ Stopped." message below.
2120
2379
  this.clearStreamingFlush();
2121
- try {
2122
- this.claudeProcess.kill();
2123
- }
2124
- catch { /* already gone */ }
2380
+ run.stop();
2125
2381
  if (this.currentChatId) {
2126
2382
  this.sendResponse(this.currentChatId, '⏹ Stopped.', 'complete');
2127
2383
  }
@@ -2177,6 +2433,9 @@ class AgentClient {
2177
2433
  }
2178
2434
  this.workingDirectory = resolved;
2179
2435
  this.config.setLastDirectory(resolved);
2436
+ // A Codex thread owns its cwd and per-thread read server. Release it
2437
+ // immediately instead of retaining both until another message arrives.
2438
+ this.codex?.resetThread();
2180
2439
  this.send({
2181
2440
  type: 'cd_result',
2182
2441
  payload: { success: true, path: resolved },
@@ -2381,9 +2640,11 @@ class AgentClient {
2381
2640
  this.denyAllPendingApprovals('Agent is shutting down.');
2382
2641
  console.log('\nShutting down...');
2383
2642
  this.stopStreaming();
2384
- if (this.claudeProcess) {
2385
- this.claudeProcess.kill();
2643
+ if (this.activeRun) {
2644
+ this.activeRun.stop();
2386
2645
  }
2646
+ // app-server outlives each turn, so it is ended here even when idle.
2647
+ this.codex?.dispose();
2387
2648
  if (this.caffeinateProcess) {
2388
2649
  this.caffeinateProcess.kill();
2389
2650
  }