vibekit-agent 1.5.4 → 1.6.1

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'
@@ -316,7 +324,8 @@ class AgentClient {
316
324
  /**
317
325
  * Link this computer to an iOS or Telegram account
318
326
  */
319
- async link() {
327
+ async link(requestedEngine) {
328
+ let startNow = false;
320
329
  console.log('Connecting to VibeKit...\n');
321
330
  // Request a link from the server
322
331
  const serverUrl = process.env.VIBEKIT_SERVER || 'https://vibekit.bot';
@@ -373,21 +382,64 @@ class AgentClient {
373
382
  result = (await response.json());
374
383
  }
375
384
  rl.close();
385
+ const wasLinked = this.config.hasToken();
376
386
  this.config.setCredentials(result.token, result.wsUrl);
387
+ // The engine is decided HERE, not at `start`. By the time `start` runs
388
+ // every machine has a token, so it cannot tell a new link from a machine
389
+ // linked before Codex support, which must stay on Claude (start() pins
390
+ // those). A re-link keeps whatever engine was already chosen, and a
391
+ // re-link of a machine linked before Codex support stays on Claude.
392
+ // `link --engine` (the command the app shows for Codex) wins over both.
393
+ const engine = requestedEngine
394
+ ?? this.config.getEngine()
395
+ ?? (wasLinked ? 'claude' : findClaudeBinary() ? 'claude' : (0, codex_engine_1.findCodexBinary)(() => { }) ? 'codex' : 'claude');
396
+ const clearedModel = this.config.setEngine(engine);
377
397
  console.log('\nLinked successfully!');
378
398
  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.');
381
- console.log('');
382
- console.log('Start the agent with:');
383
- console.log(' npx vibekit-agent start');
399
+ if (engine === 'codex') {
400
+ console.log(requestedEngine ? 'This computer will run Codex.' : 'This computer will run Codex (Claude Code was not found here).');
401
+ console.log('Make sure Codex is logged in on this computer: codex login');
402
+ }
403
+ else {
404
+ console.log('Tip: connect Claude in the VibeKit app (Profile → Connect Claude)');
405
+ console.log('and the agent signs Claude in automatically — no setup-token needed.');
406
+ }
407
+ if (clearedModel)
408
+ console.log(`Cleared the model setting "${clearedModel}": it was for the other coding agent.`);
384
409
  console.log('');
410
+ // One command instead of two. Pairing and then separately starting is
411
+ // where most people who generated a code never connected a computer
412
+ // (51 codes, 4 linked, 2026-08-01). Asked only at a terminal; Enter
413
+ // alone means yes, and "n" leaves the old two-step path intact.
414
+ if (process.stdin.isTTY && await this.askYesNo(`Start the agent now in ${process.cwd()}? (Y/n) `)) {
415
+ startNow = true;
416
+ }
417
+ else {
418
+ console.log('Start the agent with:');
419
+ console.log(' npx vibekit-agent start');
420
+ console.log('To switch coding agents later: npx vibekit-agent start --engine claude (or codex)');
421
+ console.log('');
422
+ }
385
423
  }
386
424
  catch (error) {
387
425
  const message = error instanceof Error ? error.message : String(error);
388
426
  console.error('Link failed:', message);
389
427
  process.exit(1);
390
428
  }
429
+ // Outside the try: a start failure is not a link failure, and start()
430
+ // never returns while the agent runs.
431
+ if (startNow) {
432
+ console.log('');
433
+ await this.start(process.cwd());
434
+ }
435
+ }
436
+ /** One yes/no question at the terminal. Enter alone means yes. */
437
+ async askYesNo(question) {
438
+ const readline = await Promise.resolve().then(() => __importStar(require('readline')));
439
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
440
+ const answer = await new Promise((resolve) => rl.question(question, resolve));
441
+ rl.close();
442
+ return !/^n/i.test(answer.trim());
391
443
  }
392
444
  /**
393
445
  * Start the agent and connect to VibeKit
@@ -399,26 +451,57 @@ class AgentClient {
399
451
  if (!autoMode) {
400
452
  this.config.setLastDirectory(this.workingDirectory);
401
453
  }
454
+ // No stored engine means this machine was linked before Codex support, so
455
+ // it runs Claude, and is pinned to it now. Detecting here instead would
456
+ // silently switch a user who relies on the npx Claude download and happens
457
+ // to have Codex installed. Auto mode (Docker) is Claude-only and never
458
+ // writes the config file.
459
+ if (!autoMode && !this.config.getEngine())
460
+ this.config.setEngine('claude');
461
+ this.engine = autoMode ? 'claude' : (this.config.getEngine() ?? 'claude');
402
462
  console.log(`Starting VibeKit Remote Agent...`);
403
463
  console.log(`Working directory: ${this.workingDirectory}`);
464
+ console.log(`Engine: ${this.engine === 'codex' ? 'Codex' : 'Claude Code'}`);
404
465
  // In auto mode, set up Claude credentials from the credentials file.
405
466
  // Otherwise, sign Claude in from the user's VibeKit account if they've
406
467
  // connected it there — so they don't need a separate `claude setup-token`.
407
468
  if (autoMode) {
408
469
  await this.setupAutoModeCredentials();
409
470
  }
410
- else {
471
+ else if (this.engine === 'claude') {
411
472
  await this.ensureAccountClaudeAuth();
412
473
  }
413
- // Check for claude binary at startup
414
- const claudePath = findClaudeBinary();
415
- if (claudePath) {
416
- console.log(`Claude Code found: ${claudePath}`);
474
+ if (this.engine === 'codex') {
475
+ // A candidate only counts if `codex --version` runs, so a broken install
476
+ // reads as not installed instead of failing every message.
477
+ this.codexBinary = (0, codex_engine_1.findCodexBinary)();
478
+ if (this.codexBinary) {
479
+ console.log(`Codex found: ${this.codexBinary.path} (v${this.codexBinary.version})`);
480
+ if ((0, codex_engine_1.isOlderVersion)(this.codexBinary.version, codex_engine_1.CODEX_TESTED_VERSION)) {
481
+ 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`);
482
+ }
483
+ // Said here so a user at the terminal can fix it before the first
484
+ // message. The engine re-checks on each message, so logging in later
485
+ // needs no restart.
486
+ if ((0, codex_engine_1.codexLoggedIn)(this.codexBinary.path) === false) {
487
+ console.log('Codex is not logged in on this computer. Run `codex login`; messages work as soon as you do.');
488
+ }
489
+ }
490
+ else {
491
+ console.log('\nCodex not found. Install it with `npm i -g @openai/codex`, then run `codex login`.');
492
+ }
417
493
  }
418
494
  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');
495
+ // Check for claude binary at startup
496
+ const claudePath = findClaudeBinary();
497
+ if (claudePath) {
498
+ console.log(`Claude Code found: ${claudePath}`);
499
+ }
500
+ else {
501
+ console.log('\nClaude Code not found locally — will auto-run via `npx @anthropic-ai/claude-code` on first message.');
502
+ console.log('(First invocation downloads ~50MB and takes ~30s; cached thereafter.)');
503
+ console.log('For a faster first message, install ahead of time: `claude install` or `npm install -g @anthropic-ai/claude-code`.\n');
504
+ }
422
505
  }
423
506
  console.log('');
424
507
  // Prevent the laptop from idle-sleeping while the agent is running.
@@ -445,19 +528,7 @@ class AgentClient {
445
528
  runClaude(prompt) {
446
529
  // Find the claude binary
447
530
  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;
531
+ this.supersedeActiveRun();
461
532
  // Build command arguments
462
533
  const allowedTools = this.config.getAllowedTools();
463
534
  // --include-partial-messages: emit assistant message chunks as they arrive
@@ -588,55 +659,25 @@ class AgentClient {
588
659
  // Log the invocation without echoing the user prompt.
589
660
  const redacted = spawnArgs.map((a, i, arr) => (arr[i - 1] === '-p' ? '"..."' : a)).join(' ');
590
661
  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
662
+ // Every handler below closes over `run` and gates on
663
+ // `this.activeRun === run`. A killed process's buffered stdout (and
593
664
  // its close event) fire AFTER the next run has been assigned — without
594
665
  // 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,
666
+ // the old close handler nulled the NEW run, which disarmed Stop,
596
667
  // the 5-min kill timer, and the idle check that gates self-update.
597
668
  const proc = (0, child_process_1.spawn)(command, spawnArgs, {
598
669
  cwd: this.workingDirectory,
599
670
  env: process.env,
600
671
  stdio: ['ignore', 'pipe', 'pipe'],
601
672
  });
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();
673
+ const run = {
674
+ engine: 'claude',
675
+ stop: (force) => { try {
676
+ proc.kill(force ? 'SIGKILL' : 'SIGTERM');
677
+ }
678
+ catch { /* already gone */ } },
679
+ };
680
+ this.beginRun(run);
640
681
  // Per-run UTF-8 decoder: a multibyte character (emoji, CJK, curly quote)
641
682
  // split across two stdout chunks decodes to U+FFFD with a plain
642
683
  // data.toString() — the corruption lands inside the JSON string, parses
@@ -644,7 +685,7 @@ class AgentClient {
644
685
  // sequence across chunks.
645
686
  const stdoutDecoder = new string_decoder_1.StringDecoder('utf8');
646
687
  proc.stdout?.on('data', (data) => {
647
- if (this.claudeProcess !== proc)
688
+ if (this.activeRun !== run)
648
689
  return; // superseded — not our buffer anymore
649
690
  const text = stdoutDecoder.write(data);
650
691
  // stream-json outputs one JSON object per line
@@ -661,34 +702,16 @@ class AgentClient {
661
702
  proc.stderr?.on('data', (data) => {
662
703
  const text = data.toString();
663
704
  process.stderr.write(text);
664
- if (this.claudeProcess !== proc)
705
+ if (this.activeRun !== run)
665
706
  return;
666
707
  // Keep the tail so the close handler can classify auth failures.
667
708
  this.lastRunStderr = (this.lastRunStderr + text).slice(-8192);
668
709
  });
669
710
  proc.on('close', (code) => {
670
- this.denyAllPendingApprovals('The run ended before this was answered.');
711
+ const settled = this.settleRun(run);
671
712
  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;
713
+ if (!settled)
690
714
  return;
691
- }
692
715
  // Process any remaining buffered line
693
716
  const tail = stdoutDecoder.end();
694
717
  if (tail)
@@ -739,21 +762,11 @@ class AgentClient {
739
762
  else {
740
763
  // Claude exited without producing text. Don't claim success — be honest
741
764
  // 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
765
  console.log(`[Agent] No result text collected, sending honest fallback (code=${code}, tools=${toolCount})`);
753
- this.sendResponse(this.currentChatId, fallback, 'complete');
766
+ this.sendResponse(this.currentChatId, this.noReplyFallback(code, toolCount), 'complete');
754
767
  }
755
768
  }
756
- this.claudeProcess = null;
769
+ this.activeRun = null;
757
770
  // Mark that we now have an active conversation for --continue on next message
758
771
  if (code === 0) {
759
772
  this.hasActiveConversation = true;
@@ -775,11 +788,11 @@ class AgentClient {
775
788
  });
776
789
  proc.on('error', (err) => {
777
790
  console.error('Failed to start claude:', err.message);
778
- if (this.claudeProcess !== proc)
791
+ if (this.activeRun !== run)
779
792
  return;
780
- if (this.claudeRunTimeout) {
781
- clearTimeout(this.claudeRunTimeout);
782
- this.claudeRunTimeout = null;
793
+ if (this.runTimeout) {
794
+ clearTimeout(this.runTimeout);
795
+ this.runTimeout = null;
783
796
  }
784
797
  this.cancelHeartbeats();
785
798
  this.stopStreaming();
@@ -787,8 +800,114 @@ class AgentClient {
787
800
  if (this.currentChatId && this.currentTelegramId) {
788
801
  this.sendResponse(this.currentChatId, `Error: Could not start Claude Code.\n\nPath: ${claudeBinary}\nError: ${err.message}`, 'complete');
789
802
  }
803
+ // This run is over and has replied. Node may or may not emit 'close'
804
+ // after a spawn 'error': marking it canceled stops a close from sending
805
+ // a second, fallback reply, and releasing it here stops a missing close
806
+ // from blocking every later message.
807
+ this.canceledRuns.add(run);
808
+ this.activeRun = null;
790
809
  });
791
810
  }
811
+ /**
812
+ * Stop whatever run is in flight because a new message is starting one.
813
+ * handleUserMessage already sent a "canceled" reply to the old chat, and
814
+ * marking the run canceled stops its end handler from sending a
815
+ * misattributed fallback to the new chat.
816
+ */
817
+ supersedeActiveRun() {
818
+ if (this.activeRun) {
819
+ this.canceledRuns.add(this.activeRun);
820
+ this.activeRun.stop();
821
+ this.denyAllPendingApprovals('Superseded by a new message.');
822
+ }
823
+ this.stopStreaming();
824
+ this.clearStreamingFlush();
825
+ this.currentMessageId = null;
826
+ }
827
+ /**
828
+ * Bookkeeping every run shares, whichever engine runs it: it becomes the
829
+ * active run, gets the hard kill timer, starts from clean per-run state and
830
+ * gets the heartbeat statuses.
831
+ */
832
+ beginRun(run) {
833
+ this.activeRun = run;
834
+ // Hard 5-min kill timer. Mirrors the server's SSE inactivity ceiling so
835
+ // a wedged run (infinite bash loop, stuck API call, --continue session
836
+ // corruption) doesn't block every subsequent message indefinitely. Power
837
+ // users on multi-hour bash can disable with VIBEKIT_AGENT_NO_TIMEOUT=1.
838
+ if (this.runTimeout)
839
+ clearTimeout(this.runTimeout);
840
+ if (!process.env.VIBEKIT_AGENT_NO_TIMEOUT) {
841
+ const chatIdAtStart = this.currentChatId;
842
+ this.runTimeout = setTimeout(() => {
843
+ // Only act if THIS run is still the current one. A new message
844
+ // may have replaced it, in which case the cancellation handler runs.
845
+ if (this.activeRun !== run)
846
+ return;
847
+ console.log(`[Agent] ${run.engine} run exceeded ${AgentClient.RUN_TIMEOUT_MS / 1000}s, stopping`);
848
+ if (chatIdAtStart) {
849
+ this.sendResponse(chatIdAtStart, "_Run exceeded 5 minutes and was stopped. Try a smaller task or split it up._", 'complete');
850
+ }
851
+ // Mark canceled so the end handler doesn't double-send.
852
+ this.canceledRuns.add(run);
853
+ run.stop(true);
854
+ }, AgentClient.RUN_TIMEOUT_MS);
855
+ }
856
+ // Per-run state. The names come from the Claude stream-json parser, but
857
+ // the streaming flush and the no-reply fallback read them for every engine.
858
+ this.streamJsonResult = '';
859
+ this.lastRunResultError = '';
860
+ this.lastRunStderr = '';
861
+ this.receivedPartialDeltas = false;
862
+ this.streamJsonLineBuffer = '';
863
+ this.lastStreamedLength = 0;
864
+ this.activeToolCalls.clear();
865
+ this.toolUseCountThisRun = 0;
866
+ // Heartbeat statuses fire if the engine is slow to produce anything
867
+ // visible. Real activity (tool/delta) cancels them.
868
+ this.scheduleHeartbeats();
869
+ }
870
+ /**
871
+ * The shared start of a run's end. Returns false when there is nothing left
872
+ * to send: the run was stopped on purpose (Stop, supersede, timeout), whose
873
+ * stopper already messaged the chat, or it is no longer the active run.
874
+ */
875
+ settleRun(run) {
876
+ const isCurrent = this.activeRun === run;
877
+ const wasCanceled = this.canceledRuns.has(run);
878
+ this.canceledRuns.delete(run);
879
+ // Timers and pending approvals belong to the CURRENT run — a superseded
880
+ // run's slow exit must not clear the timers beginRun just armed for its
881
+ // replacement, or deny the replacement's approval cards. The superseded
882
+ // run's own approvals were denied when it was stopped.
883
+ if (isCurrent) {
884
+ this.denyAllPendingApprovals('The run ended before this was answered.');
885
+ if (this.runTimeout) {
886
+ clearTimeout(this.runTimeout);
887
+ this.runTimeout = null;
888
+ }
889
+ this.cancelHeartbeats();
890
+ }
891
+ // Stopped on purpose: the stop site already messaged the chat.
892
+ // Superseded-but-not-flagged: also nothing to do, the new run owns all
893
+ // shared state.
894
+ if (wasCanceled || !isCurrent) {
895
+ if (isCurrent)
896
+ this.activeRun = null;
897
+ return false;
898
+ }
899
+ return true;
900
+ }
901
+ /** The honest reply for a run that produced no text, so it never reads as a success. */
902
+ noReplyFallback(exitCode, toolCount) {
903
+ if (exitCode !== 0) {
904
+ return `Agent exited without a response (code ${exitCode}). Please try again.`;
905
+ }
906
+ if (toolCount > 0) {
907
+ 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.`;
908
+ }
909
+ return `Agent finished without producing a response. Try rephrasing or resending.`;
910
+ }
792
911
  /**
793
912
  * Process a single line of stream-json output from Claude
794
913
  * Events include: system, assistant, tool_use, tool_result, result
@@ -1322,7 +1441,10 @@ class AgentClient {
1322
1441
  // `supervised` — that one is the server's, and reporting our copy
1323
1442
  // on every reconnect would fight the iOS toggle.
1324
1443
  model: this.config.getModel() || null,
1325
- allowedTools: this.config.getAllowedTools(),
1444
+ allowedTools: this.reportedAllowedTools(),
1445
+ // Additive (2026-09-14): lets the phone label the machine. Servers
1446
+ // older than Codex support ignore it.
1447
+ engine: this.engine,
1326
1448
  },
1327
1449
  timestamp: Date.now(),
1328
1450
  messageId: this.generateId(),
@@ -1341,6 +1463,7 @@ class AgentClient {
1341
1463
  clearHandshakeTimer();
1342
1464
  console.log('Disconnected from VibeKit');
1343
1465
  this.isConnected = false;
1466
+ this.denyAllPendingApprovals('The phone disconnected.');
1344
1467
  this.stopHeartbeatWatchdog();
1345
1468
  this.stopWakeWatchdog();
1346
1469
  this.scheduleReconnect();
@@ -1348,6 +1471,7 @@ class AgentClient {
1348
1471
  this.ws.on('error', (error) => {
1349
1472
  clearHandshakeTimer();
1350
1473
  this.isConnected = false;
1474
+ this.denyAllPendingApprovals('The phone connection failed.');
1351
1475
  if (handshakeAborted) {
1352
1476
  // Our own 10s watchdog aborted this handshake and already logged why.
1353
1477
  // ws emits 'close' straight after, which schedules the reconnect, so
@@ -1506,12 +1630,18 @@ class AgentClient {
1506
1630
  // DB blip during auth wiped the token and pm2 crash-looped
1507
1631
  // "No token found" 43k times (2026-08-01).
1508
1632
  const payload = message.payload || { message: 'unknown' };
1509
- console.error('Authentication failed:', payload.message);
1510
1633
  if (payload.code === 'invalid_token') {
1511
- console.error('This machine\'s pairing is no longer valid. Run "vibekit-agent link" with a fresh code from the app.');
1634
+ // The designed revocation path, not a failure: the machine was
1635
+ // unlinked in the app (the only way a pairing ends), or its row
1636
+ // was replaced. Said on stdout. Supervisors treat stderr as
1637
+ // errors, and our own box's pm2 error log feeds the admin Remote
1638
+ // Errors panel, where a deliberate unlink showed up as a server
1639
+ // error (2026-09-15).
1640
+ console.log('This machine was unlinked from VibeKit, so its pairing is no longer valid. Run "vibekit-agent link" with a fresh code from the app.');
1512
1641
  this.config.clear();
1513
1642
  }
1514
1643
  else {
1644
+ console.error('Authentication failed:', payload.message);
1515
1645
  console.error('Keeping the stored pairing — this looks like a temporary server problem. Retrying shortly...');
1516
1646
  // Don't exit: schedule a normal reconnect like a dropped socket.
1517
1647
  this.scheduleReconnect();
@@ -1614,7 +1744,7 @@ class AgentClient {
1614
1744
  return;
1615
1745
  if (this.updateAttempted)
1616
1746
  return;
1617
- if (this.claudeProcess) {
1747
+ if (this.activeRun) {
1618
1748
  // Busy — don't interrupt a run. Leave updateAttempted unset so the next
1619
1749
  // reconnect (or the next idle auth) tries again.
1620
1750
  console.log(`[Auto-update] v${latest} available but a task is running — will update when idle.`);
@@ -1688,13 +1818,15 @@ class AgentClient {
1688
1818
  // runClaude) — the user's first message bubble + spinner just hung
1689
1819
  // forever with no signal. Now they see an explicit cancellation in
1690
1820
  // the original chat and the new message proceeds normally.
1691
- if (this.claudeProcess && this.currentChatId && this.currentChatId !== chatId) {
1821
+ if (this.activeRun && this.currentChatId && this.currentChatId !== chatId) {
1692
1822
  this.sendResponse(this.currentChatId, "_Canceled — you sent a new message before this one finished._", 'complete');
1693
1823
  }
1694
1824
  this.currentChatId = chatId;
1695
1825
  this.currentTelegramId = telegramId;
1696
1826
  this.currentReplyToMessageId = messageId;
1697
1827
  let prompt = text || '';
1828
+ // Codex gets images as real inputs (localImage), on top of the path in the prompt.
1829
+ const imagePaths = [];
1698
1830
  const attachmentInfo = attachments?.length ? ` with ${attachments.length} attachment(s)` : '';
1699
1831
  const source = chatId < 0 ? 'iOS' : 'Telegram';
1700
1832
  console.log(`\nReceived from ${source}: ${text || '(no text)'}${attachmentInfo}`);
@@ -1711,6 +1843,7 @@ class AgentClient {
1711
1843
  else if (file.type === 'image') {
1712
1844
  // For images, ask Claude to analyze
1713
1845
  prompt = `[Image saved to: ${file.path}]\n\nPlease analyze this image.\n\n${prompt}`.trim();
1846
+ imagePaths.push(file.path);
1714
1847
  }
1715
1848
  else {
1716
1849
  // For documents, mention the file
@@ -1731,8 +1864,137 @@ class AgentClient {
1731
1864
  // (handleSSE replaces streamingText on each `text` event). Without it,
1732
1865
  // a slow spawn looks identical to a hung agent.
1733
1866
  this.sendStreaming(chatId, 'Starting…');
1734
- // Run claude with the prompt (stream-json will send status updates)
1735
- this.runClaude(prompt);
1867
+ // Run the engine (its events send status updates)
1868
+ if (this.engine === 'codex') {
1869
+ this.runCodex(prompt, imagePaths);
1870
+ }
1871
+ else {
1872
+ this.runClaude(prompt);
1873
+ }
1874
+ }
1875
+ /**
1876
+ * Run one Codex turn through app-server. Shares the run bookkeeping with
1877
+ * runClaude (supersedeActiveRun, beginRun, settleRun), so Stop, supersede,
1878
+ * the run timeout and the self-update idle check behave the same. Every
1879
+ * event mapping is in codex-translate.ts.
1880
+ */
1881
+ runCodex(prompt, imagePaths) {
1882
+ this.supersedeActiveRun();
1883
+ const chatId = this.currentChatId;
1884
+ // Looked up again while missing, so installing Codex works from the next message.
1885
+ if (!this.codexBinary)
1886
+ this.codexBinary = (0, codex_engine_1.findCodexBinary)();
1887
+ const binary = this.codexBinary;
1888
+ if (!binary) {
1889
+ if (chatId)
1890
+ this.sendResponse(chatId, codex_translate_1.CODEX_NOT_INSTALLED, 'complete');
1891
+ return;
1892
+ }
1893
+ if (!this.codex || this.codex.binary !== binary.path) {
1894
+ this.codex?.dispose();
1895
+ this.codex = new codex_engine_1.CodexEngine(binary.path, AGENT_VERSION);
1896
+ }
1897
+ const codex = this.codex;
1898
+ let stopTurn = null;
1899
+ const run = { engine: 'codex', stop: () => stopTurn?.() };
1900
+ this.beginRun(run);
1901
+ const access = (0, config_1.codexAccessFor)(this.config.getAllowedTools(), this.currentSupervised);
1902
+ const cwd = this.workingDirectory;
1903
+ const turn = codex.startTurn({
1904
+ prompt,
1905
+ imagePaths,
1906
+ cwd,
1907
+ model: this.config.getModel(),
1908
+ access,
1909
+ mcpServers: () => this.codexMcpServers(codex, access, cwd),
1910
+ }, {
1911
+ output: (o) => {
1912
+ if (this.activeRun !== run || this.canceledRuns.has(run))
1913
+ return;
1914
+ this.cancelHeartbeats();
1915
+ if (o.kind === 'text') {
1916
+ this.streamJsonResult = o.text;
1917
+ this.scheduleStreamingFlush();
1918
+ }
1919
+ else if (o.kind === 'status') {
1920
+ this.sendStatusUpdate(o.text);
1921
+ }
1922
+ else if (this.currentChatId) {
1923
+ this.send({
1924
+ type: 'tool_invocation',
1925
+ payload: { chatId: this.currentChatId, ...o.tool },
1926
+ timestamp: Date.now(),
1927
+ messageId: this.generateId(),
1928
+ });
1929
+ }
1930
+ },
1931
+ approve: async (toolName, input) => {
1932
+ if (this.activeRun !== run || this.canceledRuns.has(run))
1933
+ return false;
1934
+ return (await this.askPhone(toolName, input)).behavior === 'allow';
1935
+ },
1936
+ });
1937
+ stopTurn = turn.stop;
1938
+ void turn.done.then((end) => this.endCodexRun(run, end, codex));
1939
+ }
1940
+ endCodexRun(run, end, codex) {
1941
+ const settled = this.settleRun(run);
1942
+ console.log(`\nCodex turn ended: ${end.status}${end.error ? ` (${end.error.info})` : ''}`);
1943
+ if (!settled)
1944
+ return;
1945
+ this.stopStreaming();
1946
+ this.clearStreamingFlush();
1947
+ if (this.currentChatId && this.currentTelegramId) {
1948
+ const narration = end.text.trim();
1949
+ if (end.status === 'completed') {
1950
+ this.sendResponse(this.currentChatId, narration || this.noReplyFallback(0, end.toolCount), 'complete');
1951
+ }
1952
+ else {
1953
+ // A normal `complete` reply, never `status: 'error'`: iOS rewrites the
1954
+ // text of SSE error events with Claude-specific help, on every build
1955
+ // in the wild. Narration the user watched stays above the error.
1956
+ const errLine = end.error
1957
+ ? (0, codex_translate_1.codexErrorReply)(end.error, { resetsAtSec: codex.rateLimitResetsAtSec, testedVersion: codex_engine_1.CODEX_TESTED_VERSION })
1958
+ : 'Codex ended this run before it finished. Send your message again.';
1959
+ this.sendResponse(this.currentChatId, narration ? `${narration}\n\n_${errLine}_` : errLine, 'complete');
1960
+ }
1961
+ }
1962
+ this.activeRun = null;
1963
+ }
1964
+ /** Per-thread MCP tools. Read-only mode gets filesystem readers because its native shell is disabled. */
1965
+ codexMcpServers(codex, access, cwd) {
1966
+ const configScript = path.join(__dirname, 'config-mcp.js');
1967
+ const servers = {};
1968
+ if (this.controlPort && fs.existsSync(configScript)) {
1969
+ servers[codex_engine_1.VKCONFIG_SERVER] = {
1970
+ command: process.execPath,
1971
+ args: [configScript],
1972
+ env: { VK_CONFIG_PORT: String(this.controlPort), VK_ENGINE: 'codex', VK_MODELS: codex.models.join(',') },
1973
+ // The config tools never need a tap, the same as CONFIG_TOOL_NAMES on
1974
+ // Claude; a loosening already asks the phone inside the tool itself.
1975
+ // 'approve', not 'auto': measured live on Codex 0.154.0, 'auto' still
1976
+ // requires approval (an elicitation when supervised, a hard failure
1977
+ // under approvalPolicy never), 'approve' runs the tool.
1978
+ approvalMode: 'approve',
1979
+ };
1980
+ }
1981
+ const readScript = path.join(__dirname, 'codex-read-mcp.js');
1982
+ if (access === 'read-only' && fs.existsSync(readScript)) {
1983
+ servers.vkread = {
1984
+ command: process.execPath,
1985
+ args: [readScript],
1986
+ env: { VK_READ_ROOT: cwd },
1987
+ // Read-only runs under approvalPolicy never, where a tool that needs
1988
+ // approval simply fails: with 'auto' every read failed in the live test.
1989
+ approvalMode: 'approve',
1990
+ };
1991
+ }
1992
+ return servers;
1993
+ }
1994
+ /** The tool list the phone is shown: the raw list for Claude, and for Codex the access actually in force. */
1995
+ reportedAllowedTools() {
1996
+ const tools = this.config.getAllowedTools();
1997
+ return this.engine === 'codex' ? (0, config_1.codexReportedTools)(tools) : tools;
1736
1998
  }
1737
1999
  /**
1738
2000
  * Save attachments to temp directory and return file paths
@@ -1772,6 +2034,7 @@ class AgentClient {
1772
2034
  handleNewConversation() {
1773
2035
  this.hasActiveConversation = false;
1774
2036
  this.currentSessionId = null;
2037
+ this.codex?.resetThread();
1775
2038
  console.log('Conversation reset - next message will start fresh');
1776
2039
  }
1777
2040
  /**
@@ -1949,6 +2212,15 @@ class AgentClient {
1949
2212
  describeConfig() {
1950
2213
  const model = this.config.getModel();
1951
2214
  const tools = this.config.getAllowedTools();
2215
+ if (this.engine === 'codex') {
2216
+ return [
2217
+ 'Engine: Codex',
2218
+ `Model: ${model || 'Codex default'}`,
2219
+ `Tool access: ${(0, config_1.codexAccessFor)(tools, false) === 'full' ? 'full (edits and commands allowed)' : 'read-only (no edits, no commands)'}`,
2220
+ `Working directory: ${this.workingDirectory}`,
2221
+ `Supervised mode: ${this.currentSupervised ? 'on' : 'off'}`,
2222
+ ].join('\n');
2223
+ }
1952
2224
  return [
1953
2225
  `Model: ${model || 'default (whatever your claude install picks)'}`,
1954
2226
  `Allowed tools: ${tools.length === 0 ? 'all (no restrictions)' : tools.join(', ')}`,
@@ -1990,8 +2262,17 @@ class AgentClient {
1990
2262
  const m = raw.model;
1991
2263
  if (m !== null && typeof m !== 'string')
1992
2264
  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.` };
2265
+ if (typeof m === 'string' && !(0, config_1.isValidModel)(m, this.engine)) {
2266
+ return {
2267
+ ok: false,
2268
+ text: this.engine === 'codex'
2269
+ ? `"${m}" is not a Codex model name.`
2270
+ : `"${m}" is not a model name claude accepts. Use opus, sonnet, haiku, or a full claude model id.`,
2271
+ };
2272
+ }
2273
+ const codexModels = this.engine === 'codex' ? (this.codex?.models ?? []) : [];
2274
+ if (typeof m === 'string' && codexModels.length > 0 && !codexModels.includes(m.trim())) {
2275
+ return { ok: false, text: `"${m}" is not a model this Codex offers. Available: ${codexModels.join(', ')}.` };
1995
2276
  }
1996
2277
  next.model = m;
1997
2278
  }
@@ -2001,6 +2282,11 @@ class AgentClient {
2001
2282
  return { ok: false, text: 'allowedTools must be an array of tool names.' };
2002
2283
  }
2003
2284
  next.allowedTools = t.map((x) => x.trim());
2285
+ // Codex cannot honor a list allowing edits but not commands (or the
2286
+ // reverse). Refuse it by name rather than store a setting not in force.
2287
+ const problem = this.engine === 'codex' ? (0, config_1.codexToolListProblem)(next.allowedTools) : null;
2288
+ if (problem)
2289
+ return { ok: false, text: `${problem} Nothing changed.` };
2004
2290
  }
2005
2291
  if ('cwd' in raw) {
2006
2292
  if (typeof raw.cwd !== 'string' || !raw.cwd.trim())
@@ -2071,6 +2357,12 @@ class AgentClient {
2071
2357
  if (next.supervised !== undefined) {
2072
2358
  applied.push(`supervised mode ${next.supervised ? 'on' : 'off'}`);
2073
2359
  }
2360
+ if (this.engine === 'codex'
2361
+ && (next.model !== undefined || next.allowedTools !== undefined || next.supervised !== undefined)) {
2362
+ // These are thread-scoped in Codex. Retire the old subscription now,
2363
+ // even if the user never sends the "next message" mentioned below.
2364
+ this.codex?.resetThread();
2365
+ }
2074
2366
  // Tell the server, so the phone shows the same thing and `supervised`
2075
2367
  // (which is server-owned, on the remote_agents row) actually persists.
2076
2368
  this.sendConfigState(next.supervised);
@@ -2090,7 +2382,7 @@ class AgentClient {
2090
2382
  type: 'config_state',
2091
2383
  payload: {
2092
2384
  model: this.config.getModel() || null,
2093
- allowedTools: this.config.getAllowedTools(),
2385
+ allowedTools: this.reportedAllowedTools(),
2094
2386
  workingDirectory: this.workingDirectory,
2095
2387
  ...(supervised === undefined ? {} : { supervised }),
2096
2388
  },
@@ -2105,23 +2397,21 @@ class AgentClient {
2105
2397
  }
2106
2398
  }
2107
2399
  handleCancel() {
2108
- if (!this.claudeProcess) {
2400
+ const run = this.activeRun;
2401
+ if (!run) {
2109
2402
  console.log('[Agent] Cancel received — no run in flight (no-op)');
2110
2403
  this.sendStatus('idle');
2111
2404
  return;
2112
2405
  }
2113
- console.log('[Agent] Cancel received — stopping current Claude run');
2406
+ console.log(`[Agent] Cancel received, stopping the current ${run.engine} run`);
2114
2407
  this.denyAllPendingApprovals('Task was stopped from the app.');
2115
- this.canceledProcs.add(this.claudeProcess);
2408
+ this.canceledRuns.add(run);
2116
2409
  this.cancelHeartbeats();
2117
2410
  this.stopStreaming();
2118
2411
  // Kill the pending debounced frame so no streaming text lands after the
2119
2412
  // "⏹ Stopped." message below.
2120
2413
  this.clearStreamingFlush();
2121
- try {
2122
- this.claudeProcess.kill();
2123
- }
2124
- catch { /* already gone */ }
2414
+ run.stop();
2125
2415
  if (this.currentChatId) {
2126
2416
  this.sendResponse(this.currentChatId, '⏹ Stopped.', 'complete');
2127
2417
  }
@@ -2177,6 +2467,9 @@ class AgentClient {
2177
2467
  }
2178
2468
  this.workingDirectory = resolved;
2179
2469
  this.config.setLastDirectory(resolved);
2470
+ // A Codex thread owns its cwd and per-thread read server. Release it
2471
+ // immediately instead of retaining both until another message arrives.
2472
+ this.codex?.resetThread();
2180
2473
  this.send({
2181
2474
  type: 'cd_result',
2182
2475
  payload: { success: true, path: resolved },
@@ -2381,9 +2674,11 @@ class AgentClient {
2381
2674
  this.denyAllPendingApprovals('Agent is shutting down.');
2382
2675
  console.log('\nShutting down...');
2383
2676
  this.stopStreaming();
2384
- if (this.claudeProcess) {
2385
- this.claudeProcess.kill();
2677
+ if (this.activeRun) {
2678
+ this.activeRun.stop();
2386
2679
  }
2680
+ // app-server outlives each turn, so it is ended here even when idle.
2681
+ this.codex?.dispose();
2387
2682
  if (this.caffeinateProcess) {
2388
2683
  this.caffeinateProcess.kill();
2389
2684
  }