vibekit-agent 1.5.3 → 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.
@@ -427,6 +482,10 @@ class AgentClient {
427
482
  // "agent offline" until the laptop wakes. Lid-close sleep is still
428
483
  // unstoppable from userspace — this only blocks idle sleep.
429
484
  this.startCaffeinate();
485
+ // Our MCP children call back on this port, and runClaude() bakes it into
486
+ // the argv synchronously — so it has to be bound before the first message
487
+ // can arrive, not on demand.
488
+ await this.ensureControlServer();
430
489
  // Connect to VibeKit WebSocket
431
490
  this.connect();
432
491
  // Handle process signals
@@ -441,19 +500,7 @@ class AgentClient {
441
500
  runClaude(prompt) {
442
501
  // Find the claude binary
443
502
  const claudeBinary = findClaudeBinary();
444
- // Kill any existing process. If one is in flight, handleUserMessage already
445
- // sent a "canceled" reply to its chatId — the suppression flag below stops
446
- // the close handler from re-sending a misattributed fallback to the new
447
- // chat.
448
- if (this.claudeProcess) {
449
- this.canceledProcs.add(this.claudeProcess);
450
- this.claudeProcess.kill();
451
- this.denyAllPendingApprovals('Superseded by a new message.');
452
- }
453
- // Clear streaming state
454
- this.stopStreaming();
455
- this.clearStreamingFlush();
456
- this.currentMessageId = null;
503
+ this.supersedeActiveRun();
457
504
  // Build command arguments
458
505
  const allowedTools = this.config.getAllowedTools();
459
506
  // --include-partial-messages: emit assistant message chunks as they arrive
@@ -508,10 +555,13 @@ class AgentClient {
508
555
  else {
509
556
  // A missing or broken config-mcp.js must never take down an ordinary
510
557
  // run, so this degrades to "no self-config this turn" rather than throw.
558
+ // It SAYS so, though: swallowing the reason is what let a bind that
559
+ // failed on every run look like a feature nobody had asked for.
511
560
  try {
512
561
  mcpConfigPath = this.ensureMcpPlumbing(false);
513
562
  }
514
- catch {
563
+ catch (e) {
564
+ console.error(`[Self-config] Not attached this run (${e?.message || e}).`);
515
565
  mcpConfigPath = null;
516
566
  }
517
567
  }
@@ -581,55 +631,25 @@ class AgentClient {
581
631
  // Log the invocation without echoing the user prompt.
582
632
  const redacted = spawnArgs.map((a, i, arr) => (arr[i - 1] === '-p' ? '"..."' : a)).join(' ');
583
633
  console.log(`\nRunning: ${command} ${redacted}`);
584
- // Every handler below closes over `proc` and gates on
585
- // `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
586
636
  // its close event) fire AFTER the next run has been assigned — without
587
637
  // the gates, the old run's tail text leaked into the new run's buffer and
588
- // the old close handler nulled the NEW process ref, which disarmed Stop,
638
+ // the old close handler nulled the NEW run, which disarmed Stop,
589
639
  // the 5-min kill timer, and the idle check that gates self-update.
590
640
  const proc = (0, child_process_1.spawn)(command, spawnArgs, {
591
641
  cwd: this.workingDirectory,
592
642
  env: process.env,
593
643
  stdio: ['ignore', 'pipe', 'pipe'],
594
644
  });
595
- this.claudeProcess = proc;
596
- // Hard 5-min kill timer. Mirrors the server's SSE inactivity ceiling so
597
- // a wedged Claude (infinite bash loop, stuck API call, --continue session
598
- // corruption) doesn't block every subsequent message indefinitely. Power
599
- // users on multi-hour bash can disable with VIBEKIT_AGENT_NO_TIMEOUT=1.
600
- if (this.claudeRunTimeout)
601
- clearTimeout(this.claudeRunTimeout);
602
- if (!process.env.VIBEKIT_AGENT_NO_TIMEOUT) {
603
- const chatIdAtStart = this.currentChatId;
604
- this.claudeRunTimeout = setTimeout(() => {
605
- // Only act if THIS process is still the current one — a new message
606
- // may have replaced it, in which case the cancellation handler runs.
607
- if (this.claudeProcess !== proc)
608
- return;
609
- console.log(`[Agent] Claude run exceeded ${AgentClient.CLAUDE_RUN_TIMEOUT_MS / 1000}s — killing`);
610
- if (chatIdAtStart) {
611
- this.sendResponse(chatIdAtStart, "_Run exceeded 5 minutes and was stopped. Try a smaller task or split it up._", 'complete');
612
- }
613
- // Mark canceled so the close handler doesn't double-send.
614
- this.canceledProcs.add(proc);
615
- try {
616
- proc.kill('SIGKILL');
617
- }
618
- catch { }
619
- }, AgentClient.CLAUDE_RUN_TIMEOUT_MS);
620
- }
621
- // Track the final result text from stream-json
622
- this.streamJsonResult = '';
623
- this.lastRunResultError = '';
624
- this.lastRunStderr = '';
625
- this.receivedPartialDeltas = false;
626
- this.streamJsonLineBuffer = '';
627
- this.lastStreamedLength = 0;
628
- this.activeToolCalls.clear();
629
- this.toolUseCountThisRun = 0;
630
- // Heartbeat statuses fire if Claude is slow to produce anything visible.
631
- // Real activity (tool/delta) cancels them in their handlers below.
632
- 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);
633
653
  // Per-run UTF-8 decoder: a multibyte character (emoji, CJK, curly quote)
634
654
  // split across two stdout chunks decodes to U+FFFD with a plain
635
655
  // data.toString() — the corruption lands inside the JSON string, parses
@@ -637,7 +657,7 @@ class AgentClient {
637
657
  // sequence across chunks.
638
658
  const stdoutDecoder = new string_decoder_1.StringDecoder('utf8');
639
659
  proc.stdout?.on('data', (data) => {
640
- if (this.claudeProcess !== proc)
660
+ if (this.activeRun !== run)
641
661
  return; // superseded — not our buffer anymore
642
662
  const text = stdoutDecoder.write(data);
643
663
  // stream-json outputs one JSON object per line
@@ -654,34 +674,16 @@ class AgentClient {
654
674
  proc.stderr?.on('data', (data) => {
655
675
  const text = data.toString();
656
676
  process.stderr.write(text);
657
- if (this.claudeProcess !== proc)
677
+ if (this.activeRun !== run)
658
678
  return;
659
679
  // Keep the tail so the close handler can classify auth failures.
660
680
  this.lastRunStderr = (this.lastRunStderr + text).slice(-8192);
661
681
  });
662
682
  proc.on('close', (code) => {
663
- this.denyAllPendingApprovals('The run ended before this was answered.');
683
+ const settled = this.settleRun(run);
664
684
  console.log(`\nClaude exited with code ${code}`);
665
- const isCurrent = this.claudeProcess === proc;
666
- const wasCanceled = this.canceledProcs.has(proc);
667
- this.canceledProcs.delete(proc);
668
- // Timers belong to the CURRENT run — a superseded run's close must not
669
- // clear the timers runClaude just armed for its replacement.
670
- if (isCurrent) {
671
- if (this.claudeRunTimeout) {
672
- clearTimeout(this.claudeRunTimeout);
673
- this.claudeRunTimeout = null;
674
- }
675
- this.cancelHeartbeats();
676
- }
677
- // Killed on purpose (supersede / Stop / timeout): the kill site already
678
- // messaged the chat. Superseded-but-not-flagged (shouldn't happen, but
679
- // belt): also nothing to do — the new run owns all shared state.
680
- if (wasCanceled || !isCurrent) {
681
- if (isCurrent)
682
- this.claudeProcess = null;
685
+ if (!settled)
683
686
  return;
684
- }
685
687
  // Process any remaining buffered line
686
688
  const tail = stdoutDecoder.end();
687
689
  if (tail)
@@ -732,21 +734,11 @@ class AgentClient {
732
734
  else {
733
735
  // Claude exited without producing text. Don't claim success — be honest
734
736
  // so the user doesn't think we completed something we didn't.
735
- let fallback;
736
- if (code !== 0) {
737
- fallback = `Agent exited without a response (code ${code}). Please try again.`;
738
- }
739
- else if (toolCount > 0) {
740
- 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.`;
741
- }
742
- else {
743
- fallback = `Agent finished without producing a response. Try rephrasing or resending.`;
744
- }
745
737
  console.log(`[Agent] No result text collected, sending honest fallback (code=${code}, tools=${toolCount})`);
746
- this.sendResponse(this.currentChatId, fallback, 'complete');
738
+ this.sendResponse(this.currentChatId, this.noReplyFallback(code, toolCount), 'complete');
747
739
  }
748
740
  }
749
- this.claudeProcess = null;
741
+ this.activeRun = null;
750
742
  // Mark that we now have an active conversation for --continue on next message
751
743
  if (code === 0) {
752
744
  this.hasActiveConversation = true;
@@ -768,11 +760,11 @@ class AgentClient {
768
760
  });
769
761
  proc.on('error', (err) => {
770
762
  console.error('Failed to start claude:', err.message);
771
- if (this.claudeProcess !== proc)
763
+ if (this.activeRun !== run)
772
764
  return;
773
- if (this.claudeRunTimeout) {
774
- clearTimeout(this.claudeRunTimeout);
775
- this.claudeRunTimeout = null;
765
+ if (this.runTimeout) {
766
+ clearTimeout(this.runTimeout);
767
+ this.runTimeout = null;
776
768
  }
777
769
  this.cancelHeartbeats();
778
770
  this.stopStreaming();
@@ -780,8 +772,114 @@ class AgentClient {
780
772
  if (this.currentChatId && this.currentTelegramId) {
781
773
  this.sendResponse(this.currentChatId, `Error: Could not start Claude Code.\n\nPath: ${claudeBinary}\nError: ${err.message}`, 'complete');
782
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;
783
781
  });
784
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
+ }
785
883
  /**
786
884
  * Process a single line of stream-json output from Claude
787
885
  * Events include: system, assistant, tool_use, tool_result, result
@@ -1315,7 +1413,10 @@ class AgentClient {
1315
1413
  // `supervised` — that one is the server's, and reporting our copy
1316
1414
  // on every reconnect would fight the iOS toggle.
1317
1415
  model: this.config.getModel() || null,
1318
- 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,
1319
1420
  },
1320
1421
  timestamp: Date.now(),
1321
1422
  messageId: this.generateId(),
@@ -1334,6 +1435,7 @@ class AgentClient {
1334
1435
  clearHandshakeTimer();
1335
1436
  console.log('Disconnected from VibeKit');
1336
1437
  this.isConnected = false;
1438
+ this.denyAllPendingApprovals('The phone disconnected.');
1337
1439
  this.stopHeartbeatWatchdog();
1338
1440
  this.stopWakeWatchdog();
1339
1441
  this.scheduleReconnect();
@@ -1341,6 +1443,7 @@ class AgentClient {
1341
1443
  this.ws.on('error', (error) => {
1342
1444
  clearHandshakeTimer();
1343
1445
  this.isConnected = false;
1446
+ this.denyAllPendingApprovals('The phone connection failed.');
1344
1447
  if (handshakeAborted) {
1345
1448
  // Our own 10s watchdog aborted this handshake and already logged why.
1346
1449
  // ws emits 'close' straight after, which schedules the reconnect, so
@@ -1607,7 +1710,7 @@ class AgentClient {
1607
1710
  return;
1608
1711
  if (this.updateAttempted)
1609
1712
  return;
1610
- if (this.claudeProcess) {
1713
+ if (this.activeRun) {
1611
1714
  // Busy — don't interrupt a run. Leave updateAttempted unset so the next
1612
1715
  // reconnect (or the next idle auth) tries again.
1613
1716
  console.log(`[Auto-update] v${latest} available but a task is running — will update when idle.`);
@@ -1681,13 +1784,15 @@ class AgentClient {
1681
1784
  // runClaude) — the user's first message bubble + spinner just hung
1682
1785
  // forever with no signal. Now they see an explicit cancellation in
1683
1786
  // the original chat and the new message proceeds normally.
1684
- if (this.claudeProcess && this.currentChatId && this.currentChatId !== chatId) {
1787
+ if (this.activeRun && this.currentChatId && this.currentChatId !== chatId) {
1685
1788
  this.sendResponse(this.currentChatId, "_Canceled — you sent a new message before this one finished._", 'complete');
1686
1789
  }
1687
1790
  this.currentChatId = chatId;
1688
1791
  this.currentTelegramId = telegramId;
1689
1792
  this.currentReplyToMessageId = messageId;
1690
1793
  let prompt = text || '';
1794
+ // Codex gets images as real inputs (localImage), on top of the path in the prompt.
1795
+ const imagePaths = [];
1691
1796
  const attachmentInfo = attachments?.length ? ` with ${attachments.length} attachment(s)` : '';
1692
1797
  const source = chatId < 0 ? 'iOS' : 'Telegram';
1693
1798
  console.log(`\nReceived from ${source}: ${text || '(no text)'}${attachmentInfo}`);
@@ -1704,6 +1809,7 @@ class AgentClient {
1704
1809
  else if (file.type === 'image') {
1705
1810
  // For images, ask Claude to analyze
1706
1811
  prompt = `[Image saved to: ${file.path}]\n\nPlease analyze this image.\n\n${prompt}`.trim();
1812
+ imagePaths.push(file.path);
1707
1813
  }
1708
1814
  else {
1709
1815
  // For documents, mention the file
@@ -1724,8 +1830,137 @@ class AgentClient {
1724
1830
  // (handleSSE replaces streamingText on each `text` event). Without it,
1725
1831
  // a slow spawn looks identical to a hung agent.
1726
1832
  this.sendStreaming(chatId, 'Starting…');
1727
- // Run claude with the prompt (stream-json will send status updates)
1728
- 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;
1729
1964
  }
1730
1965
  /**
1731
1966
  * Save attachments to temp directory and return file paths
@@ -1765,6 +2000,7 @@ class AgentClient {
1765
2000
  handleNewConversation() {
1766
2001
  this.hasActiveConversation = false;
1767
2002
  this.currentSessionId = null;
2003
+ this.codex?.resetThread();
1768
2004
  console.log('Conversation reset - next message will start fresh');
1769
2005
  }
1770
2006
  /**
@@ -1776,13 +2012,47 @@ class AgentClient {
1776
2012
  */
1777
2013
  // ── Supervised-mode approval plumbing ──────────────────────────────
1778
2014
  /**
1779
- * Start (once) the localhost HTTP server our MCP children call, and write
1780
- * the --mcp-config file pointing claude at them. Returns the config path,
1781
- * or null when there is no MCP server worth attaching.
2015
+ * Bind (once) the localhost HTTP server our MCP children call back on.
1782
2016
  *
1783
- * `withApproval` adds the supervised-mode permission-prompt server and is
1784
- * the only thing that can throw: a missing approval-mcp.js must fail
1785
- * CLOSED (runClaude falls back to tool restrictions), while a missing
2017
+ * Awaited at startup rather than done inline where it is needed, because
2018
+ * binding is ASYNCHRONOUS: `listen(0, '127.0.0.1')` resolves the host
2019
+ * through dns.lookup first, so `server.address()` on the next line is null.
2020
+ * The inline version read it there and threw "control server failed to
2021
+ * bind" on every single run — which the caller swallowed, so self-config
2022
+ * (and supervised mode's approval prompts) silently never attached from the
2023
+ * day they shipped. runClaude() is synchronous and cannot await, so the
2024
+ * port has to already exist by the time it builds the argv.
2025
+ *
2026
+ * Resolves either way: a box that cannot bind loopback still gets a working
2027
+ * agent, minus self-config, and is told so rather than failing to start.
2028
+ */
2029
+ ensureControlServer() {
2030
+ if (this.controlServer)
2031
+ return Promise.resolve();
2032
+ return new Promise((resolve) => {
2033
+ const server = http.createServer((req, res) => this.handleControlHttpRequest(req, res));
2034
+ server.once('error', (e) => {
2035
+ console.error(`Self-config and supervised mode are unavailable: control server could not bind (${e?.message || e}).`);
2036
+ resolve();
2037
+ });
2038
+ server.listen(0, '127.0.0.1', () => {
2039
+ const addr = server.address();
2040
+ if (addr && typeof addr !== 'string') {
2041
+ this.controlPort = addr.port;
2042
+ this.controlServer = server;
2043
+ }
2044
+ server.unref(); // never keep the process alive on its own
2045
+ resolve();
2046
+ });
2047
+ });
2048
+ }
2049
+ /**
2050
+ * Write the --mcp-config file pointing claude at our MCP children. Returns
2051
+ * the config path, or null when there is no MCP server worth attaching.
2052
+ *
2053
+ * `withApproval` adds the supervised-mode permission-prompt server. Throws
2054
+ * when the plumbing it needs is missing: a missing approval-mcp.js must
2055
+ * fail CLOSED (runClaude falls back to tool restrictions), while a missing
1786
2056
  * config-mcp.js just means no self-config this run.
1787
2057
  */
1788
2058
  ensureMcpPlumbing(withApproval) {
@@ -1793,16 +2063,8 @@ class AgentClient {
1793
2063
  const withConfig = fs.existsSync(configScript);
1794
2064
  if (!withApproval && !withConfig)
1795
2065
  return null;
1796
- if (!this.controlServer) {
1797
- const server = http.createServer((req, res) => this.handleControlHttpRequest(req, res));
1798
- server.listen(0, '127.0.0.1');
1799
- const addr = server.address();
1800
- if (!addr || typeof addr === 'string')
1801
- throw new Error('control server failed to bind');
1802
- this.controlPort = addr.port;
1803
- server.unref(); // never keep the process alive on its own
1804
- this.controlServer = server;
1805
- }
2066
+ if (!this.controlPort)
2067
+ throw new Error('control server is not listening');
1806
2068
  // Port is baked into the config env, so rewrite whenever it changes
1807
2069
  // (fresh process = fresh ephemeral port). Rewritten per run rather than
1808
2070
  // once, because which servers belong in it depends on supervised mode:
@@ -1916,6 +2178,15 @@ class AgentClient {
1916
2178
  describeConfig() {
1917
2179
  const model = this.config.getModel();
1918
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
+ }
1919
2190
  return [
1920
2191
  `Model: ${model || 'default (whatever your claude install picks)'}`,
1921
2192
  `Allowed tools: ${tools.length === 0 ? 'all (no restrictions)' : tools.join(', ')}`,
@@ -1957,8 +2228,17 @@ class AgentClient {
1957
2228
  const m = raw.model;
1958
2229
  if (m !== null && typeof m !== 'string')
1959
2230
  return { ok: false, text: 'model must be a string, or null to clear it.' };
1960
- if (typeof m === 'string' && !(0, config_1.isValidModel)(m)) {
1961
- 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(', ')}.` };
1962
2242
  }
1963
2243
  next.model = m;
1964
2244
  }
@@ -1968,6 +2248,11 @@ class AgentClient {
1968
2248
  return { ok: false, text: 'allowedTools must be an array of tool names.' };
1969
2249
  }
1970
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.` };
1971
2256
  }
1972
2257
  if ('cwd' in raw) {
1973
2258
  if (typeof raw.cwd !== 'string' || !raw.cwd.trim())
@@ -2038,6 +2323,12 @@ class AgentClient {
2038
2323
  if (next.supervised !== undefined) {
2039
2324
  applied.push(`supervised mode ${next.supervised ? 'on' : 'off'}`);
2040
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
+ }
2041
2332
  // Tell the server, so the phone shows the same thing and `supervised`
2042
2333
  // (which is server-owned, on the remote_agents row) actually persists.
2043
2334
  this.sendConfigState(next.supervised);
@@ -2057,7 +2348,7 @@ class AgentClient {
2057
2348
  type: 'config_state',
2058
2349
  payload: {
2059
2350
  model: this.config.getModel() || null,
2060
- allowedTools: this.config.getAllowedTools(),
2351
+ allowedTools: this.reportedAllowedTools(),
2061
2352
  workingDirectory: this.workingDirectory,
2062
2353
  ...(supervised === undefined ? {} : { supervised }),
2063
2354
  },
@@ -2072,23 +2363,21 @@ class AgentClient {
2072
2363
  }
2073
2364
  }
2074
2365
  handleCancel() {
2075
- if (!this.claudeProcess) {
2366
+ const run = this.activeRun;
2367
+ if (!run) {
2076
2368
  console.log('[Agent] Cancel received — no run in flight (no-op)');
2077
2369
  this.sendStatus('idle');
2078
2370
  return;
2079
2371
  }
2080
- console.log('[Agent] Cancel received — stopping current Claude run');
2372
+ console.log(`[Agent] Cancel received, stopping the current ${run.engine} run`);
2081
2373
  this.denyAllPendingApprovals('Task was stopped from the app.');
2082
- this.canceledProcs.add(this.claudeProcess);
2374
+ this.canceledRuns.add(run);
2083
2375
  this.cancelHeartbeats();
2084
2376
  this.stopStreaming();
2085
2377
  // Kill the pending debounced frame so no streaming text lands after the
2086
2378
  // "⏹ Stopped." message below.
2087
2379
  this.clearStreamingFlush();
2088
- try {
2089
- this.claudeProcess.kill();
2090
- }
2091
- catch { /* already gone */ }
2380
+ run.stop();
2092
2381
  if (this.currentChatId) {
2093
2382
  this.sendResponse(this.currentChatId, '⏹ Stopped.', 'complete');
2094
2383
  }
@@ -2144,6 +2433,9 @@ class AgentClient {
2144
2433
  }
2145
2434
  this.workingDirectory = resolved;
2146
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();
2147
2439
  this.send({
2148
2440
  type: 'cd_result',
2149
2441
  payload: { success: true, path: resolved },
@@ -2348,9 +2640,11 @@ class AgentClient {
2348
2640
  this.denyAllPendingApprovals('Agent is shutting down.');
2349
2641
  console.log('\nShutting down...');
2350
2642
  this.stopStreaming();
2351
- if (this.claudeProcess) {
2352
- this.claudeProcess.kill();
2643
+ if (this.activeRun) {
2644
+ this.activeRun.stop();
2353
2645
  }
2646
+ // app-server outlives each turn, so it is ended here even when idle.
2647
+ this.codex?.dispose();
2354
2648
  if (this.caffeinateProcess) {
2355
2649
  this.caffeinateProcess.kill();
2356
2650
  }