@bike4mind/cli 3.4.0 → 4.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.
Files changed (56) hide show
  1. package/README.md +223 -39
  2. package/bin/bike4mind-cli.mjs +301 -38
  3. package/bin/envFlags.d.mts +17 -0
  4. package/bin/envFlags.mjs +89 -0
  5. package/bin/hearth-hook.mjs +53 -7
  6. package/dist/{AgentHistoryStore-ClO2zOn6.mjs → AgentHistoryStore--J3sgO_-.mjs} +9011 -6699
  7. package/dist/ApiClient-CdO4Gamg.mjs +152 -0
  8. package/dist/BubblewrapRuntime-3jAbC60G.mjs +157 -0
  9. package/dist/ConfigStore-CausUCzY.mjs +2 -0
  10. package/dist/ConfigStore-Dusy6glb.mjs +3364 -0
  11. package/dist/{ConfigStore-CbVFLXMH.mjs → Logger-C1Wj6xla.mjs} +32880 -20779
  12. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  13. package/dist/RemoteSkillSource-qTvRkaNA.mjs +455 -0
  14. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-CQwYq_uy.mjs} +26 -7
  15. package/dist/SandboxRuntimeAdapter-BsT2iLky.mjs +190 -0
  16. package/dist/SandboxRuntimeAdapter-Zg_0th7V.mjs +2 -0
  17. package/dist/SeatbeltRuntime-C2DEkrjy.mjs +194 -0
  18. package/dist/{WorkItemsClient-SeNbzvEw.mjs → WorkItemsClient-CxNZaOmc.mjs} +1 -1
  19. package/dist/agents/defaults/review.md +8 -1
  20. package/dist/agents/defaults/test.md +8 -1
  21. package/dist/buildToolSearch-DOb7mx6F.mjs +417 -0
  22. package/dist/commands/acpCommand.mjs +33 -27
  23. package/dist/commands/apiCommand.mjs +3 -5
  24. package/dist/commands/doctorCommand.mjs +2 -2
  25. package/dist/commands/envCommand.mjs +1 -1
  26. package/dist/commands/headlessCommand.mjs +118 -36
  27. package/dist/commands/hostCommand.mjs +2344 -0
  28. package/dist/commands/mcpCommand.mjs +46 -30
  29. package/dist/commands/mirrorCommand.mjs +279 -0
  30. package/dist/commands/modelsCommand.mjs +1117 -0
  31. package/dist/commands/pluginCommand.mjs +9 -9
  32. package/dist/commands/skillsCommand.mjs +404 -0
  33. package/dist/commands/updateCommand.mjs +2 -2
  34. package/dist/curated-build.json +1 -0
  35. package/dist/dist-CbViwiS9.mjs +4739 -0
  36. package/dist/dist-Citbv0y0.mjs +7864 -0
  37. package/dist/fit-CVWDiavv.mjs +200 -0
  38. package/dist/index.mjs +1001 -442
  39. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  40. package/dist/modelServers-BaegigV-.mjs +2465 -0
  41. package/dist/{package-MoDZ9cGj.mjs → package-C9pfAdGF.mjs} +1 -1
  42. package/dist/{serve-zi-B2iUT.mjs → serve-8wyGb8of.mjs} +1243 -44
  43. package/dist/store-BYeE0shc.mjs +2 -0
  44. package/dist/{store-BxmPEI3v.mjs → store-BbvSi3KK.mjs} +26 -2
  45. package/dist/types-BFIvwByC.mjs +2 -0
  46. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  47. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-BAKb8KWP.mjs} +7 -29
  48. package/package.json +17 -13
  49. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  50. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  51. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  52. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  53. package/dist/buildAgent-BeaVbpzH.mjs +0 -1992
  54. package/dist/dist-DlBq3wHu.mjs +0 -739
  55. package/dist/store-BkMur6uk.mjs +0 -2
  56. package/dist/types-I45lMh7Q.mjs +0 -2
package/dist/index.mjs CHANGED
@@ -1,22 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import { $ as CustomCommandStore, A as createAgentDelegateTool, B as DEFAULT_THOROUGHNESS, C as createTodoStore, D as createCoordinateTaskTool, E as parseAgentConfig, G as setWebSocketToolExecutor, H as buildSkillsPromptSection, I as ALWAYS_DENIED_FOR_AGENTS, L as DEFAULT_AGENT_MODEL, M as substituteArguments, N as PermissionManager, O as createResumeAgentTool, P as buildCliToolList, Q as RemoteSkillSource, R as DEFAULT_MAX_ITERATIONS, S as createFindDefinitionTool, T as createSkillTool, V as buildSystemPrompt, W as getProcessHooks, X as createToolSearchTool, Z as findIterationBoundary, _ as createDecisionLogTool, at as mergeCommands, b as createGetFileStructureTool, ct as searchFiles, d as createReviewGateStore, dt as COMPACTION_SUMMARY_MARKER, et as processFileReferences, f as createReviewGateTool, g as formatBlockersOutput, h as createBlockerTools, it as searchCommands, j as FallbackLlmBackend, k as createBackgroundAgentTools, lt as warmFileCache, m as createBlockerStore, nt as CheckpointStore, ot as rewireReservedNames, p as formatReviewGatesOutput, pt as MAX_PASTE_SIZE, q as getPlanModeFilePath, rt as SessionStore, s as buildSandbox, st as formatFileSize, tt as hasFileReferences, u as isConnectionDrop, v as createDecisionStore, w as createWriteTodosTool, x as createWorkItemTools, y as formatDecisionsOutput, z as DEFAULT_RETRY_CONFIG } from "./AgentHistoryStore-ClO2zOn6.mjs";
3
- import { a as selectLiveSubagentTokens, i as selectLiveSubagentCredits, n as selectActiveBackgroundShells, o as useCliStore, r as selectCompletedBackgroundShells, t as selectActiveBackgroundAgents } from "./store-BxmPEI3v.mjs";
4
- import { Gt as actorKindSchema, Ht as DELEGATION_PAYLOAD_SCHEMA_NAME, It as tokenEstimateMultiplier, Kt as delegationPayloadSchema, L as CREDIT_DEDUCT_TRANSACTION_TYPES, R as ChatModels, S as isValidSessionId, St as isEarlyStop, Ut as actorColorIndex, Vt as ACTOR_COLOR_SLOTS, Wt as actorKindMarker, _ as LOCAL_DEV_URL, b as logger, d as getCreditsUrl, f as getEnvironmentName, i as ToolCatalog, m as resolveApiEndpoint, n as extractCompactInstructions, ot as SUBQUEST_STATUS_VALUES, p as requireApiUrl, qt as selfClaimedActorKindSchema, rt as REVIEW_GATE_STATUS_VALUES, t as ConfigStore, u as ApiEndpointUnconfiguredError, x as SESSION_ID_PATTERN, y as parseApiUrl } from "./ConfigStore-CbVFLXMH.mjs";
2
+ import { $ as SIGN_IN_DURING_TURN, A as createTodoStore, At as warmFileCache, B as substituteArguments, C as formatBlockersOutput, Ct as hasFileReferences, D as createGetFileStructureTool, Dt as searchCommands, E as formatDecisionsOutput, Et as SessionStore, F as createResumeAgentTool, G as DEFAULT_AGENT_MODEL, H as buildCliToolList, I as createBackgroundAgentTools, J as DEFAULT_THOROUGHNESS, K as DEFAULT_MAX_ITERATIONS, L as createAgentDelegateTool, M as createSkillTool, N as parseAgentConfig, Nt as MAX_PASTE_SIZE, O as createWorkItemTools, Ot as formatFileSize, P as createCoordinateTaskTool, Q as SIGNED_OUT_BANNER, R as FallbackLlmBackend, S as createBlockerTools, St as processFileReferences, T as createDecisionStore, Tt as CommandHistoryStore, V as PermissionManager, W as ALWAYS_DENIED_FOR_AGENTS, X as LOGGED_OUT_RESTART, Y as LOCAL_SESSION_CONTINUES, Z as NoLocalModelsError, _t as getProcessHooks, b as formatReviewGatesOutput, bt as getPlanModeFilePath, c as checkSavedSignIn, ct as signedOutCommandMessage, dt as buildSkillsPromptSection, et as SIGN_IN_EXPIRED, f as buildLlmBackend, ht as findIterationBoundary, it as loginBlocked, j as createWriteTodosTool, jt as COMPACTION_SUMMARY_MARKER, k as createFindDefinitionTool, kt as searchFiles, l as settleSignInRefresh, lt as signedOutNoMatchMessage, nt as SIGN_IN_HINT, ot as signInUncheckedLoginMessage, q as DEFAULT_RETRY_CONFIG, s as buildSandbox, st as signInUncheckedMessage, u as startupMode, ut as buildSystemPrompt, v as createReviewGateStore, vt as setWebSocketToolExecutor, w as createDecisionLogTool, wt as CheckpointStore, x as createBlockerStore, xt as CustomCommandStore, y as createReviewGateTool, z as isConnectionDrop } from "./AgentHistoryStore--J3sgO_-.mjs";
3
+ import { a as selectLiveSubagentTokens, i as selectLiveSubagentCredits, n as selectActiveBackgroundShells, o as useCliStore, r as selectCompletedBackgroundShells, t as selectActiveBackgroundAgents } from "./store-BbvSi3KK.mjs";
4
+ import { D as sanitizeTerminalText, E as escapeTerminalControlChars, S as LOCAL_DEV_URL, T as parseApiUrl, _ as getEnvironmentName, c as ToolCatalog, g as getDefaultApiUrl, h as getCreditsUrl, m as ApiEndpointUnconfiguredError, o as extractCompactInstructions, t as ConfigStore, v as requireApiUrl, y as resolveApiEndpoint } from "./ConfigStore-Dusy6glb.mjs";
5
+ import { a as extractErrorMessage$1 } from "./dist-CbViwiS9.mjs";
6
+ import { $t as selfClaimedActorKindSchema, Bt as tokenEstimateMultiplier, J as REVIEW_GATE_STATUS_VALUES, Jt as DELEGATION_PAYLOAD_SCHEMA_NAME, Qt as delegationPayloadSchema, S as CREDIT_DEDUCT_TRANSACTION_TYPES, Xt as actorKindMarker, Yt as actorColorIndex, Z as SUBQUEST_STATUS_VALUES, Zt as actorKindSchema, n as SESSION_ID_PATTERN, qt as ACTOR_COLOR_SLOTS, r as isValidSessionId, t as logger, vt as isEarlyStop, w as ChatModels } from "./Logger-C1Wj6xla.mjs";
7
+ import { a as rewireReservedNames, i as mergeCommands, t as RemoteSkillSource } from "./RemoteSkillSource-qTvRkaNA.mjs";
5
8
  import { r as isFeatureEnabled, t as PluginStore } from "./PluginStore-DwvOJ-G3.mjs";
6
- import { i as getTokenCounter, n as ConversationContext, r as reconstructTurnBlocks, t as WorkItemsClient } from "./WorkItemsClient-SeNbzvEw.mjs";
7
- import { a as NotifyingLlmBackend, i as deferredToolRegistry, n as buildSupportingStores, r as buildLlmBackend, t as buildAgent } from "./buildAgent-BeaVbpzH.mjs";
9
+ import { i as getTokenCounter, n as ConversationContext, r as reconstructTurnBlocks, t as WorkItemsClient } from "./WorkItemsClient-CxNZaOmc.mjs";
8
10
  import { t as getShellSessionManager } from "./ShellSessionManager-6o8KZzl1-vrbPAUTq.mjs";
9
- import { a as ApiClient, s as OAuthClient } from "./dist-DlBq3wHu.mjs";
10
- import { t as version } from "./package-MoDZ9cGj.mjs";
11
- import { s as getStartupUpdateStatus } from "./updateChecker-CCLVVdH0.mjs";
11
+ import { r as OAuthClient, t as ApiClient } from "./ApiClient-CdO4Gamg.mjs";
12
+ import { t as version } from "./package-C9pfAdGF.mjs";
13
+ import { a as NotifyingLlmBackend, i as deferredToolRegistry, n as buildAgent, r as buildSupportingStores, t as buildToolSearch } from "./buildToolSearch-DOb7mx6F.mjs";
14
+ import { s as getStartupUpdateStatus } from "./updateChecker-BAKb8KWP.mjs";
12
15
  import React, { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
13
- import { Box, Static, Text, measureElement, render, useApp, useInput, usePaste, useStdout } from "ink";
16
+ import { Box, Static, Text, measureElement, render, useApp, useInput, usePaste, useStdin, useStdout } from "ink";
14
17
  import { randomBytes } from "crypto";
15
18
  import { constants, existsSync, promises, readFileSync, statSync } from "fs";
16
19
  import { homedir } from "os";
17
20
  import path, { basename, extname, join } from "path";
18
21
  import { v4 } from "uuid";
19
- import * as path$1 from "node:path";
22
+ import * as path$2 from "node:path";
20
23
  import { z as z$1 } from "zod";
21
24
  import axios, { isAxiosError } from "axios";
22
25
  import Spinner from "ink-spinner";
@@ -335,14 +338,14 @@ function CommandAutocomplete({ commands, selectedIndex }) {
335
338
  }, /* @__PURE__ */ React.createElement(Text, {
336
339
  color: isSelected ? "cyan" : void 0,
337
340
  bold: isSelected
338
- }, isSelected ? "▸ " : " ", sourceIcon, "/", cmd.name, args, " - ", cmd.description));
341
+ }, isSelected ? "▸ " : " ", sourceIcon, "/", sanitizeTerminalText(cmd.name), sanitizeTerminalText(args), " - ", sanitizeTerminalText(cmd.description)));
339
342
  }));
340
343
  }
341
344
  //#endregion
342
345
  //#region src/components/FileAutocomplete.tsx
343
346
  function FileAutocomplete({ files, selectedIndex, query }) {
344
347
  if (files.length === 0) {
345
- if (path$1.isAbsolute(query)) return /* @__PURE__ */ React.createElement(Box, {
348
+ if (path$2.isAbsolute(query)) return /* @__PURE__ */ React.createElement(Box, {
346
349
  marginLeft: 2,
347
350
  marginTop: 1
348
351
  }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "No items in "), /* @__PURE__ */ React.createElement(Text, { color: "cyan" }, query), /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " (or path does not exist)"));
@@ -369,7 +372,7 @@ function FileAutocomplete({ files, selectedIndex, query }) {
369
372
  const isSelected = startIndex + viewportIndex === selectedIndex;
370
373
  const icon = file.isDirectory ? "[folder]" : "[file] ";
371
374
  const sizeDisplay = file.isDirectory ? "" : file.size !== void 0 ? ` (${formatFileSize(file.size)})` : "";
372
- const pathDisplay = file.isDirectory ? `${file.path}/` : file.path;
375
+ const pathDisplay = sanitizeTerminalText(file.isDirectory ? `${file.path}/` : file.path);
373
376
  return /* @__PURE__ */ React.createElement(Box, {
374
377
  key: file.path,
375
378
  marginLeft: 1
@@ -620,13 +623,14 @@ function findAtTrigger(value) {
620
623
  }
621
624
  return null;
622
625
  }
623
- function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = false, history = [], commands = [], prefillInput, onPrefillConsumed, onBashModeChange }) {
626
+ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = false, history = [], onHistoryEntry, commands = [], prefillInput, onPrefillConsumed, onBashModeChange }) {
624
627
  const value = useCliStore((state) => state.inputValue);
625
628
  const setValue = useCliStore((state) => state.setInputValue);
626
629
  const pastedContent = useCliStore((state) => state.pastedContent);
627
630
  const pastedLineCount = useCliStore((state) => state.pastedLineCount);
628
631
  const setPastedContent = useCliStore((state) => state.setPastedContent);
629
632
  const clearPaste = useCliStore((state) => state.clearPaste);
633
+ const turnBusy = useCliStore((state) => state.isThinking || state.turnInFlight);
630
634
  const [selectedIndex, setSelectedIndex] = useState(0);
631
635
  const [historyIndex, setHistoryIndex] = useState(-1);
632
636
  const [tempInput, setTempInput] = useState("");
@@ -644,7 +648,7 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
644
648
  onBashModeChange?.(isBashMode);
645
649
  }, [isBashMode, onBashModeChange]);
646
650
  const commandQuery = value.startsWith("/") ? value.slice(1) : "";
647
- const shouldShowCommandAutocomplete = value.startsWith("/") && !disabled && !fileAutocomplete?.active && !looksLikeFilePath(value) && !pastedContent && !commandQuery.includes(" ");
651
+ const shouldShowCommandAutocomplete = value.startsWith("/") && historyIndex === -1 && !disabled && !fileAutocomplete?.active && !looksLikeFilePath(value) && !pastedContent && !commandQuery.includes(" ");
648
652
  const filteredCommands = useMemo(() => {
649
653
  if (!shouldShowCommandAutocomplete) return [];
650
654
  return searchCommands(commandQuery, commands);
@@ -705,6 +709,16 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
705
709
  return;
706
710
  }
707
711
  }
712
+ if (key.tab && !key.shift && turnBusy && !isBashMode && !shouldShowCommandAutocomplete && !fileAutocomplete?.active) {
713
+ const content = pastedContent ?? value;
714
+ if (!content.trim()) return;
715
+ if (pastedContent) clearPaste();
716
+ onHistoryEntry?.(content);
717
+ onSubmit(content, { followUp: true });
718
+ setValue("");
719
+ setHistoryIndex(-1);
720
+ return;
721
+ }
708
722
  if (!shouldShowCommandAutocomplete && !fileAutocomplete?.active && history.length > 0) {
709
723
  if (key.upArrow) {
710
724
  if (historyIndex === -1) {
@@ -751,7 +765,9 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
751
765
  if (pastedContent) {
752
766
  const fullContent = pastedContent;
753
767
  clearPaste();
768
+ onHistoryEntry?.(fullContent);
754
769
  onSubmit(fullContent);
770
+ setHistoryIndex(-1);
755
771
  return;
756
772
  }
757
773
  if (!input.trim()) return;
@@ -770,12 +786,14 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
770
786
  }
771
787
  setValue("");
772
788
  setHistoryIndex(-1);
789
+ onHistoryEntry?.(commandText);
773
790
  onSubmit(commandText);
774
791
  return;
775
792
  }
776
793
  if (isBashMode && onBashCommand) {
777
794
  const command = input.slice(1).trim();
778
795
  if (command) {
796
+ onHistoryEntry?.(input);
779
797
  onBashCommand(command);
780
798
  setValue("");
781
799
  setHistoryIndex(-1);
@@ -783,6 +801,7 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
783
801
  }
784
802
  return;
785
803
  }
804
+ onHistoryEntry?.(input);
786
805
  onSubmit(input);
787
806
  setValue("");
788
807
  setHistoryIndex(-1);
@@ -905,9 +924,10 @@ const AgentThinking = React.memo(function AgentThinking() {
905
924
  const JobItem = React.memo(function JobItem({ job, indented = false }) {
906
925
  const elapsed = Math.round((Date.now() - job.startTime) / 1e3);
907
926
  const maxTaskLength = indented ? 50 : 60;
908
- const taskPreview = job.task.length > maxTaskLength ? job.task.slice(0, maxTaskLength - 3) + "..." : job.task;
927
+ const task = sanitizeTerminalText(job.task);
928
+ const taskPreview = task.length > maxTaskLength ? task.slice(0, maxTaskLength - 3) + "..." : task;
909
929
  const isQueued = job.status === "queued";
910
- return /* @__PURE__ */ React.createElement(Box, null, indented && /* @__PURE__ */ React.createElement(Text, null, " "), isQueued ? /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "⏳") : /* @__PURE__ */ React.createElement(Text, { color: "blue" }, /* @__PURE__ */ React.createElement(Spinner, { type: "dots" })), /* @__PURE__ */ React.createElement(Text, { color: isQueued ? "yellow" : "blue" }, " ", job.agentName), /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " ", "[", job.id, "] ", taskPreview, " ", isQueued ? "(queued)" : `(${elapsed}s)`));
930
+ return /* @__PURE__ */ React.createElement(Box, null, indented && /* @__PURE__ */ React.createElement(Text, null, " "), isQueued ? /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "⏳") : /* @__PURE__ */ React.createElement(Text, { color: "blue" }, /* @__PURE__ */ React.createElement(Spinner, { type: "dots" })), /* @__PURE__ */ React.createElement(Text, { color: isQueued ? "yellow" : "blue" }, " ", sanitizeTerminalText(job.agentName)), /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " ", "[", job.id, "] ", taskPreview, " ", isQueued ? "(queued)" : `(${elapsed}s)`));
911
931
  });
912
932
  /**
913
933
  * Counts running and queued jobs, returning a formatted status string
@@ -995,7 +1015,8 @@ const TERMINAL_ICON = {
995
1015
  function elapsedSeconds(session) {
996
1016
  return Math.round(((session.endTime ?? Date.now()) - session.startTime) / 1e3);
997
1017
  }
998
- function commandPreview(command) {
1018
+ function commandPreview(rawCommand) {
1019
+ const command = sanitizeTerminalText(rawCommand);
999
1020
  return command.length > MAX_COMMAND_LENGTH ? command.slice(0, 57) + "..." : command;
1000
1021
  }
1001
1022
  /** A running session: spinner + command + elapsed time. */
@@ -1079,35 +1100,13 @@ function CompletedGroupNotification() {
1079
1100
  }, "✔", " "), /* @__PURE__ */ React.createElement(Text, {
1080
1101
  color: "green",
1081
1102
  bold: true
1082
- }, item.groupDescription ? `Background tasks completed: "${item.groupDescription}"` : "Background tasks completed")), /* @__PURE__ */ React.createElement(Box, { paddingLeft: 2 }, /* @__PURE__ */ React.createElement(Text, {
1103
+ }, item.groupDescription ? `Background tasks completed: "${sanitizeTerminalText(item.groupDescription)}"` : "Background tasks completed")), /* @__PURE__ */ React.createElement(Box, { paddingLeft: 2 }, /* @__PURE__ */ React.createElement(Text, {
1083
1104
  dimColor: true,
1084
1105
  italic: true
1085
1106
  }, "Results will be incorporated in the next response.")))));
1086
1107
  }
1087
1108
  //#endregion
1088
1109
  //#region src/components/PermissionPrompt.tsx
1089
- /**
1090
- * Escape characters that let untrusted text render differently from what
1091
- * actually runs, into a visible escape form. Shared by every prompt that shows
1092
- * untrusted text for the user to decide on: tool previews/arguments here,
1093
- * repo-authored MCP definitions (McpApprovalPrompt), the folder-trust path
1094
- * (FolderTrustPrompt), and model-authored ReviewGatePrompt / UserQuestionPrompt text. Display only - never escape the
1095
- * value that is acted on or sent back.
1096
- * These ranges are covered, deliberately and no wider:
1097
- * - C0 controls (minus tab/newline), DEL and C1 controls -> `\xHH`: a raw
1098
- * `\r`, ESC or 8-bit CSI (U+009B) could rewrite the line being approved.
1099
- * - Unicode bidi overrides U+202A..U+202E and isolates U+2066..U+2069
1100
- * -> `\uXXXX`: these reorder displayed glyphs without changing the
1101
- * underlying code points, spoofing the same way.
1102
- * Tab and newline are left intact (newline is already the line delimiter).
1103
- * Widen the scope here, so both call sites gain it at once.
1104
- */
1105
- function escapeTerminalControlChars(text) {
1106
- return text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, (ch) => {
1107
- const code = ch.charCodeAt(0);
1108
- return code > 255 ? `\\u${code.toString(16).padStart(4, "0")}` : `\\x${code.toString(16).padStart(2, "0")}`;
1109
- });
1110
- }
1111
1110
  /** Render a diff/preview string, color-coding each line by its prefix (see per-branch comments below). */
1112
1111
  function renderDiffPreview(preview) {
1113
1112
  return escapeTerminalControlChars(preview).split("\n").map((line, index) => {
@@ -1139,16 +1138,25 @@ function renderDiffPreview(preview) {
1139
1138
  });
1140
1139
  }
1141
1140
  const TOOLS_WITH_HIDDEN_ARGS$1 = /* @__PURE__ */ new Set(["edit_local_file", "bash_execute"]);
1141
+ /** Name what the session option remembers, or drop it when nothing would be remembered. */
1142
+ function withSessionScope(items, scope) {
1143
+ if (scope === null) return items.filter((item) => item.value !== "allow-session");
1144
+ const label = `\u2713 Allow ${scope.map((entry) => `\`${entry}\``).join(", ")} commands for the session`;
1145
+ return items.map((item) => item.value === "allow-session" ? {
1146
+ ...item,
1147
+ label
1148
+ } : item);
1149
+ }
1142
1150
  /**
1143
1151
  * Permission prompt component
1144
1152
  *
1145
1153
  * Displays when a tool needs permission before execution.
1146
1154
  * Waits indefinitely for user response (like Claude Code).
1147
1155
  */
1148
- function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrusted, kind, onResponse }) {
1156
+ function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrusted, sessionScope, kind, onResponse }) {
1149
1157
  const isSandboxEscalation = kind === "sandbox-escalation";
1150
1158
  const hideArgs = TOOLS_WITH_HIDDEN_ARGS$1.has(toolName);
1151
- const items = isSandboxEscalation ? [
1159
+ const baseItems = isSandboxEscalation ? [
1152
1160
  {
1153
1161
  label: "✓ Retry once without sandbox",
1154
1162
  value: "allow-once"
@@ -1192,6 +1200,7 @@ function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrust
1192
1200
  value: "deny"
1193
1201
  }
1194
1202
  ];
1203
+ const items = isSandboxEscalation || sessionScope === void 0 ? baseItems : withSessionScope(baseItems, sessionScope);
1195
1204
  const [selectedIndex, setSelectedIndex] = useState(0);
1196
1205
  const [responded, setResponded] = useState(false);
1197
1206
  const handleSelect = useCallback(() => {
@@ -1427,7 +1436,7 @@ function UserQuestionPrompt({ payload, onResponse }) {
1427
1436
  }, /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Text, {
1428
1437
  bold: true,
1429
1438
  color: "cyan"
1430
- }, "? Question", totalQuestions > 1 ? ` ${questionIndex + 1}/${totalQuestions}` : "")), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { bold: true }, escapeTerminalControlChars(currentQuestion.question))), /* @__PURE__ */ React.createElement(Box, {
1439
+ }, "? Question", totalQuestions > 1 ? ` ${questionIndex + 1}/${totalQuestions}` : "")), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { bold: true }, escapeTerminalControlChars(currentQuestion.question, { keepBidiMarks: true }))), /* @__PURE__ */ React.createElement(Box, {
1431
1440
  marginTop: 1,
1432
1441
  flexDirection: "column"
1433
1442
  }, options.map((opt, idx) => {
@@ -1437,12 +1446,12 @@ function UserQuestionPrompt({ payload, onResponse }) {
1437
1446
  return /* @__PURE__ */ React.createElement(Box, { key: idx }, /* @__PURE__ */ React.createElement(Text, { color: "cyan" }, idx + 1, "."), /* @__PURE__ */ React.createElement(Text, {
1438
1447
  color: isHighlighted ? "cyan" : void 0,
1439
1448
  bold: isHighlighted
1440
- }, " ", prefix, " ", escapeTerminalControlChars(opt.label)), idx === otherIndex && isHighlighted ? /* @__PURE__ */ React.createElement(Box, { marginLeft: 1 }, /* @__PURE__ */ React.createElement(TextInput, {
1449
+ }, " ", prefix, " ", escapeTerminalControlChars(opt.label, { keepBidiMarks: true })), idx === otherIndex && isHighlighted ? /* @__PURE__ */ React.createElement(Box, { marginLeft: 1 }, /* @__PURE__ */ React.createElement(TextInput, {
1441
1450
  value: otherText,
1442
1451
  onChange: setOtherText,
1443
1452
  onSubmit: submitOther,
1444
1453
  placeholder: "Type your answer..."
1445
- })) : opt.description && idx !== otherIndex && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " - ", escapeTerminalControlChars(opt.description)));
1454
+ })) : opt.description && idx !== otherIndex && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " - ", escapeTerminalControlChars(opt.description, { keepBidiMarks: true })));
1446
1455
  })), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, isOnOther ? "Type your answer, Enter to submit, or arrow keys to go back" : isMulti ? "Press 1-" + options.length + ", Space to toggle, Enter to confirm" : "Press 1-" + options.length + ", or arrow keys + Enter")));
1447
1456
  }
1448
1457
  //#endregion
@@ -1545,10 +1554,10 @@ function ReviewGatePrompt({ description, options, recommendation, onResponse })
1545
1554
  }, /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Text, {
1546
1555
  bold: true,
1547
1556
  color: "magenta"
1548
- }, "🛑 Review Gate")), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, null, escapeTerminalControlChars(description))), recommendation && /* @__PURE__ */ React.createElement(Box, {
1557
+ }, "🛑 Review Gate")), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, null, escapeTerminalControlChars(description, { keepBidiMarks: true }))), recommendation && /* @__PURE__ */ React.createElement(Box, {
1549
1558
  marginTop: 1,
1550
1559
  flexDirection: "column"
1551
- }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "Recommendation:"), /* @__PURE__ */ React.createElement(Box, { paddingLeft: 2 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, escapeTerminalControlChars(recommendation)))), options && options.length > 0 && /* @__PURE__ */ React.createElement(Box, {
1560
+ }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "Recommendation:"), /* @__PURE__ */ React.createElement(Box, { paddingLeft: 2 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, escapeTerminalControlChars(recommendation, { keepBidiMarks: true })))), options && options.length > 0 && /* @__PURE__ */ React.createElement(Box, {
1552
1561
  marginTop: 1,
1553
1562
  flexDirection: "column"
1554
1563
  }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "Options:"), /* @__PURE__ */ React.createElement(Box, {
@@ -1557,7 +1566,7 @@ function ReviewGatePrompt({ description, options, recommendation, onResponse })
1557
1566
  }, options.map((opt, idx) => /* @__PURE__ */ React.createElement(Text, {
1558
1567
  key: idx,
1559
1568
  dimColor: true
1560
- }, "• ", escapeTerminalControlChars(opt))))), /* @__PURE__ */ React.createElement(Box, {
1569
+ }, "• ", escapeTerminalControlChars(opt, { keepBidiMarks: true }))))), /* @__PURE__ */ React.createElement(Box, {
1561
1570
  marginTop: 1,
1562
1571
  flexDirection: "column"
1563
1572
  }, ITEMS.map((item, index) => {
@@ -2061,13 +2070,13 @@ function McpViewer({ config, mcpManager, onClose }) {
2061
2070
  dimColor: true
2062
2071
  }, "Configured Servers:"), config.mcpServers.map((server) => {
2063
2072
  const status = server.enabled ? "✅ Enabled" : "⏸️ Disabled";
2064
- const commandInfo = server.command ? `${server.command} ${(server.args || []).join(" ")}` : "(internal)";
2073
+ const commandInfo = server.command ? sanitizeTerminalText(`${server.command} ${(server.args || []).join(" ")}`) : "(internal)";
2065
2074
  return /* @__PURE__ */ React.createElement(Box, {
2066
2075
  key: server.name,
2067
2076
  flexDirection: "column",
2068
2077
  marginTop: 1,
2069
2078
  marginLeft: 2
2070
- }, /* @__PURE__ */ React.createElement(Text, null, "• ", /* @__PURE__ */ React.createElement(Text, { bold: true }, server.name), " - ", /* @__PURE__ */ React.createElement(Text, { dimColor: true }, status)), /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " Command: ", commandInfo), Object.keys(server.env).length > 0 && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " Env vars: ", Object.keys(server.env).join(", ")));
2079
+ }, /* @__PURE__ */ React.createElement(Text, null, "•", " ", /* @__PURE__ */ React.createElement(Text, { bold: true }, sanitizeTerminalText(server.name)), " - ", /* @__PURE__ */ React.createElement(Text, { dimColor: true }, status)), /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " Command: ", commandInfo), Object.keys(server.env).length > 0 && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, " Env vars: ", sanitizeTerminalText(Object.keys(server.env).join(", "))));
2071
2080
  })), enabledServers.length > 0 && mcpManager && /* @__PURE__ */ React.createElement(Box, {
2072
2081
  flexDirection: "column",
2073
2082
  marginBottom: 2
@@ -2106,7 +2115,7 @@ function McpViewer({ config, mcpManager, onClose }) {
2106
2115
  key: server.name,
2107
2116
  marginTop: 1,
2108
2117
  marginLeft: 2
2109
- }, /* @__PURE__ */ React.createElement(Text, null, "• ", /* @__PURE__ */ React.createElement(Text, { bold: true }, server.name), " · ", /* @__PURE__ */ React.createElement(Text, { color }, icon), " ", /* @__PURE__ */ React.createElement(Text, { color }, statusText), toolInfo && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, toolInfo)));
2118
+ }, /* @__PURE__ */ React.createElement(Text, null, "•", " ", /* @__PURE__ */ React.createElement(Text, { bold: true }, sanitizeTerminalText(server.name)), " ", "·", " ", /* @__PURE__ */ React.createElement(Text, { color }, icon), " ", /* @__PURE__ */ React.createElement(Text, { color }, statusText), toolInfo && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, toolInfo)));
2110
2119
  }), /* @__PURE__ */ React.createElement(Box, {
2111
2120
  marginTop: 1,
2112
2121
  marginLeft: 2
@@ -2123,109 +2132,6 @@ function McpViewer({ config, mcpManager, onClose }) {
2123
2132
  }, "Press Esc or q to close")));
2124
2133
  }
2125
2134
  //#endregion
2126
- //#region src/storage/CommandHistoryStore.ts
2127
- /**
2128
- * Maximum number of history entries to keep
2129
- */
2130
- const MAX_HISTORY_ENTRIES = 1e3;
2131
- /**
2132
- * Manages command history stored in JSONL format
2133
- * Uses append-friendly JSONL for efficient writes
2134
- */
2135
- var CommandHistoryStore = class {
2136
- constructor(historyPath) {
2137
- this.history = null;
2138
- this.historyPath = historyPath || path.join(homedir(), ".bike4mind", "history.jsonl");
2139
- }
2140
- /**
2141
- * Initialize history directory
2142
- */
2143
- async init() {
2144
- const dir = path.dirname(this.historyPath);
2145
- try {
2146
- await promises.mkdir(dir, { recursive: true });
2147
- } catch (error) {
2148
- console.error("Failed to initialize history directory:", error);
2149
- throw error;
2150
- }
2151
- }
2152
- /**
2153
- * Load command history from disk
2154
- * Returns array of commands (newest first)
2155
- */
2156
- async load() {
2157
- if (this.history) return this.history;
2158
- try {
2159
- const entries = (await promises.readFile(this.historyPath, "utf-8")).trim().split("\n").filter((line) => line.length > 0).map((line) => {
2160
- try {
2161
- return JSON.parse(line);
2162
- } catch {
2163
- return null;
2164
- }
2165
- }).filter((entry) => entry !== null);
2166
- this.history = entries.sort((a, b) => b.timestamp - a.timestamp).map((entry) => entry.command);
2167
- return this.history;
2168
- } catch (error) {
2169
- if (error.code === "ENOENT") {
2170
- this.history = [];
2171
- return this.history;
2172
- }
2173
- throw error;
2174
- }
2175
- }
2176
- /**
2177
- * Add a command to history
2178
- * Skips if it's the same as the most recent command (deduplicate)
2179
- */
2180
- async add(command) {
2181
- await this.load();
2182
- if (!command || !command.trim()) return;
2183
- if (this.history && this.history.length > 0 && this.history[0] === command) return;
2184
- const entry = {
2185
- command,
2186
- timestamp: Date.now()
2187
- };
2188
- await this.init();
2189
- const line = JSON.stringify(entry) + "\n";
2190
- await promises.appendFile(this.historyPath, line, "utf-8");
2191
- this.history = [command, ...this.history || []];
2192
- if (this.history.length > MAX_HISTORY_ENTRIES) await this.trim();
2193
- }
2194
- /**
2195
- * Trim history to max entries
2196
- * Rewrites the entire file with the most recent entries
2197
- */
2198
- async trim() {
2199
- if (!this.history || this.history.length <= MAX_HISTORY_ENTRIES) return;
2200
- const trimmedCommands = this.history.slice(0, MAX_HISTORY_ENTRIES);
2201
- const lines = trimmedCommands.reverse().map((command) => {
2202
- return JSON.stringify({
2203
- command,
2204
- timestamp: Date.now()
2205
- });
2206
- }).join("\n");
2207
- await promises.writeFile(this.historyPath, lines + "\n", "utf-8");
2208
- this.history = trimmedCommands;
2209
- }
2210
- /**
2211
- * Clear all command history
2212
- */
2213
- async clear() {
2214
- try {
2215
- await promises.unlink(this.historyPath);
2216
- } catch (error) {
2217
- if (error.code !== "ENOENT") throw error;
2218
- }
2219
- this.history = [];
2220
- }
2221
- /**
2222
- * Get all commands (newest first)
2223
- */
2224
- async list() {
2225
- return this.load();
2226
- }
2227
- };
2228
- //#endregion
2229
2135
  //#region src/storage/buildGlobalConfigPatch.ts
2230
2136
  /**
2231
2137
  * Compute the minimal global-config patch for a /config editor save: only the
@@ -2258,7 +2164,7 @@ function buildGlobalConfigPatch(prev, next) {
2258
2164
  //#region src/components/MarkdownRenderer.tsx
2259
2165
  function MarkdownRenderer({ content, columns: columnsProp }) {
2260
2166
  const columns = columnsProp ?? process.stdout.columns ?? 80;
2261
- const tokens = marked.lexer(content);
2167
+ const tokens = marked.lexer(sanitizeTerminalText(content));
2262
2168
  return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, tokens.map((token, idx) => renderToken(token, idx, columns)));
2263
2169
  }
2264
2170
  function renderToken(token, idx, columns) {
@@ -2469,13 +2375,17 @@ function useStdoutDimensions() {
2469
2375
  */
2470
2376
  /** Rows the trace Box spends on the "N earlier steps" hint and its bottom margin. */
2471
2377
  const TRACE_BOX_CHROME_ROWS = 2;
2378
+ /** Raw chars scanned per output char in truncateValue; slack for escape bytes that sanitizing removes. */
2379
+ const SANITIZE_WINDOW_FACTOR = 4;
2472
2380
  /**
2473
2381
  * Truncates a value to maxLength, converting objects to JSON strings.
2474
2382
  * Appends '...' if truncated.
2475
2383
  */
2476
2384
  function truncateValue(value, maxLength) {
2477
- const str = typeof value === "string" ? value : JSON.stringify(value);
2478
- if (str.length <= maxLength) return str;
2385
+ const raw = typeof value === "string" ? value : JSON.stringify(value);
2386
+ const window = maxLength * SANITIZE_WINDOW_FACTOR;
2387
+ const str = sanitizeTerminalText(raw.length > window ? raw.slice(0, window) : raw);
2388
+ if (str.length <= maxLength && raw.length <= window) return str;
2479
2389
  return str.slice(0, maxLength) + "...";
2480
2390
  }
2481
2391
  const isRenderable = (step, showThoughts) => step.type === "action" || step.type === "thought" && showThoughts;
@@ -2593,10 +2503,11 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2593
2503
  const traceWrap = isLive ? "truncate-end" : "wrap";
2594
2504
  const oneLine = (text) => isLive ? text.replace(/\s+/g, " ") : text;
2595
2505
  const hasReply = !isUser && message.content !== "...";
2506
+ const content = React.useMemo(() => sanitizeTerminalText(message.content), [message.content]);
2596
2507
  const allSteps = message.metadata?.steps;
2597
2508
  const liveSplit = React.useMemo(() => {
2598
2509
  if (liveRows === void 0) return void 0;
2599
- const replyRows = hasReply ? wrapReplyRows(message.content, terminalCols - REPLY_INDENT) : [];
2510
+ const replyRows = hasReply ? wrapReplyRows(content, terminalCols - REPLY_INDENT) : [];
2600
2511
  return splitLiveRows(liveRows, {
2601
2512
  steps: allSteps ?? [],
2602
2513
  replyRows,
@@ -2605,7 +2516,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2605
2516
  }, [
2606
2517
  liveRows,
2607
2518
  hasReply,
2608
- message.content,
2519
+ content,
2609
2520
  terminalCols,
2610
2521
  allSteps,
2611
2522
  showThoughts
@@ -2629,7 +2540,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2629
2540
  showThoughts
2630
2541
  ]);
2631
2542
  const visibleTraceSteps = traceSteps.filter((s) => showThoughts && s.type === "thought" || s.type === "action").length;
2632
- const userPromptText = `❯ ${message.content}`;
2543
+ const userPromptText = `\u276F ${content}`;
2633
2544
  const paddedUserPromptText = userPromptText.length >= terminalCols ? userPromptText : userPromptText.padEnd(terminalCols);
2634
2545
  return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, isUser && message.content && /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, {
2635
2546
  backgroundColor: "whiteBright",
@@ -2651,7 +2562,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2651
2562
  }, /* @__PURE__ */ React.createElement(Text, {
2652
2563
  dimColor: true,
2653
2564
  wrap: traceWrap
2654
- }, `💭 ${oneLine(step.content)}`));
2565
+ }, `\u{1F4AD} ${oneLine(sanitizeTerminalText(step.content))}`));
2655
2566
  }
2656
2567
  if (step.type === "action") {
2657
2568
  const toolName = step.metadata?.toolName || "unknown";
@@ -2664,7 +2575,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2664
2575
  key: idx,
2665
2576
  marginTop: 1,
2666
2577
  flexDirection: "column"
2667
- }, /* @__PURE__ */ React.createElement(Text, { wrap: traceWrap }, /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, formattedToolName), !!toolInput && !hideArgs && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, ` • ${oneLine(truncateValue(toolInput, 100))}`)), result && /* @__PURE__ */ React.createElement(Box, { paddingLeft: 2 }, /* @__PURE__ */ React.createElement(Text, {
2578
+ }, /* @__PURE__ */ React.createElement(Text, { wrap: traceWrap }, /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, sanitizeTerminalText(formattedToolName)), !!toolInput && !hideArgs && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, ` • ${oneLine(truncateValue(toolInput, 100))}`)), result && /* @__PURE__ */ React.createElement(Box, { paddingLeft: 2 }, /* @__PURE__ */ React.createElement(Text, {
2668
2579
  dimColor: true,
2669
2580
  wrap: traceWrap
2670
2581
  }, `Result: ${oneLine(truncateValue(result, 200))}`)));
@@ -2680,8 +2591,8 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2680
2591
  }, row || " "))), !isLive && hasReply && /* @__PURE__ */ React.createElement(Box, {
2681
2592
  paddingLeft: REPLY_INDENT,
2682
2593
  marginBottom: 1
2683
- }, message.metadata?.permissionDenied ? /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "⚠️ ", message.content) : /* @__PURE__ */ React.createElement(MarkdownRenderer, {
2684
- content: message.content,
2594
+ }, message.metadata?.permissionDenied ? /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "⚠️", " ", content) : /* @__PURE__ */ React.createElement(MarkdownRenderer, {
2595
+ content,
2685
2596
  columns: terminalCols
2686
2597
  })), !isUser && message.metadata?.earlyStopReason && /* @__PURE__ */ React.createElement(Box, { paddingLeft: 2 }, /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, message.metadata.earlyStopReason === "degenerate_repetition" ? "⚠ Response stopped early: it began repeating itself. Try rephrasing the request." : "⚠ Response was cut off at the output-token limit. Type \"continue\" to resume, or raise Max Tokens in /config.")), !isLive && hasReply && message.metadata && /* @__PURE__ */ React.createElement(Box, {
2687
2598
  paddingLeft: 2,
@@ -2706,7 +2617,9 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2706
2617
  * agent/shell status blocks render nothing when idle.
2707
2618
  */
2708
2619
  const LIVE_CHROME_ROWS = 10;
2709
- function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPermissionResponse, onUserQuestionResponse, onReviewGateResponse, onImageDetected, commandHistory = [], commands = [], config, availableModels = [], pluginDescriptors = [], onSaveConfig, prefillInput, onPrefillConsumed, mcpManager }) {
2620
+ /** Shown under the queued-message rows; mirrors the routing in handleSubmit and the ESC handler in index.tsx. */
2621
+ const QUEUE_HINT = "Enter steers this turn · Tab queues for next turn · Esc cancels and restores to input";
2622
+ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPermissionResponse, onUserQuestionResponse, onReviewGateResponse, onImageDetected, commandHistory = [], onHistoryEntry, commands = [], config, availableModels = [], pluginDescriptors = [], onSaveConfig, prefillInput, onPrefillConsumed, mcpManager }) {
2710
2623
  const messages = useCliStore(useShallow((state) => state.session?.messages || []));
2711
2624
  const pendingMessages = useCliStore((state) => state.pendingMessages);
2712
2625
  const messageQueue = useCliStore((state) => state.messageQueue);
@@ -2729,15 +2642,17 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2729
2642
  const exitRequested = useCliStore((state) => state.exitRequested);
2730
2643
  const setIsThinking = useCliStore((state) => state.setIsThinking);
2731
2644
  const pendingBackgroundTrigger = useCliStore((state) => state.pendingBackgroundTrigger);
2645
+ const turnInFlight = useCliStore((state) => state.turnInFlight);
2732
2646
  const setPendingBackgroundTrigger = useCliStore((state) => state.setPendingBackgroundTrigger);
2733
2647
  useEffect(() => {
2734
- if (pendingBackgroundTrigger && !isThinking && onBackgroundCompletion) {
2648
+ if (pendingBackgroundTrigger && !isThinking && !turnInFlight && onBackgroundCompletion) {
2735
2649
  setPendingBackgroundTrigger(false);
2736
2650
  onBackgroundCompletion();
2737
2651
  }
2738
2652
  }, [
2739
2653
  pendingBackgroundTrigger,
2740
2654
  isThinking,
2655
+ turnInFlight,
2741
2656
  setPendingBackgroundTrigger,
2742
2657
  onBackgroundCompletion
2743
2658
  ]);
@@ -2767,8 +2682,9 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2767
2682
  useInput(() => setPromptInputTick((tick) => tick + 1), { isActive: promptKey !== "" });
2768
2683
  const promptRows = promptKey === "" ? 0 : measuredPrompt?.key === promptKey ? measuredPrompt.rows : Infinity;
2769
2684
  const [terminalCols, terminalRows] = useStdoutDimensions();
2770
- const liveRows = Math.max(0, terminalRows - LIVE_CHROME_ROWS - messageQueue.length - promptRows);
2771
- const handleSubmit = React.useCallback(async (input) => {
2685
+ const queueRows = messageQueue.length > 0 ? messageQueue.length + 1 : 0;
2686
+ const liveRows = Math.max(0, terminalRows - LIVE_CHROME_ROWS - queueRows - promptRows);
2687
+ const handleSubmit = React.useCallback(async (input, options) => {
2772
2688
  const trimmed = input.trim();
2773
2689
  if (!trimmed) return;
2774
2690
  if (trimmed.startsWith("/") && !trimmed.match(/^\/[A-Z]/)) {
@@ -2789,8 +2705,10 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2789
2705
  messageToSend = `${messageToSend}\n\n${errorBlock}`;
2790
2706
  }
2791
2707
  }
2792
- if (useCliStore.getState().isThinking) {
2793
- useCliStore.getState().enqueueMessage(messageToSend);
2708
+ const store = useCliStore.getState();
2709
+ if (store.isThinking || store.turnInFlight) {
2710
+ const kind = options?.followUp || !store.turnInFlight ? "followUp" : "steer";
2711
+ store.enqueueMessage(messageToSend, kind, trimmed);
2794
2712
  return;
2795
2713
  }
2796
2714
  setIsThinking(true);
@@ -2848,6 +2766,7 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2848
2766
  args: permissionPrompt.args,
2849
2767
  preview: permissionPrompt.preview,
2850
2768
  canBeTrusted: permissionPrompt.canBeTrusted,
2769
+ sessionScope: permissionPrompt.sessionScope,
2851
2770
  kind: permissionPrompt.kind,
2852
2771
  onResponse: (response) => onPermissionResponse(response, permissionPrompt.id)
2853
2772
  })), userQuestionPrompt && /* @__PURE__ */ React.createElement(Box, {
@@ -2888,7 +2807,9 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2888
2807
  paddingX: 1,
2889
2808
  marginBottom: 1
2890
2809
  }, messageQueue.map((queuedMessage, idx) => {
2891
- const rowText = `❯ ${queuedMessage}`;
2810
+ const label = queuedMessage.kind === "followUp" ? "[next turn] " : "";
2811
+ const [firstLine, ...moreLines] = (queuedMessage.typed ?? queuedMessage.text).split("\n");
2812
+ const rowText = `\u276F ${label}${firstLine}${moreLines.length > 0 ? " ..." : ""}`;
2892
2813
  const padded = rowText.length >= terminalCols - 2 ? rowText : rowText.padEnd(terminalCols - 2);
2893
2814
  return /* @__PURE__ */ React.createElement(Text, {
2894
2815
  key: idx,
@@ -2896,7 +2817,10 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2896
2817
  color: "white",
2897
2818
  wrap: "truncate-end"
2898
2819
  }, padded);
2899
- })), /* @__PURE__ */ React.createElement(Box, {
2820
+ }), /* @__PURE__ */ React.createElement(Text, {
2821
+ dimColor: true,
2822
+ wrap: "truncate-end"
2823
+ }, QUEUE_HINT)), /* @__PURE__ */ React.createElement(Box, {
2900
2824
  borderStyle: "single",
2901
2825
  borderColor: isBashMode ? "yellow" : "cyan",
2902
2826
  borderTop: true,
@@ -2909,6 +2833,7 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2909
2833
  onImageDetected,
2910
2834
  disabled: !!permissionPrompt || !!userQuestionPrompt || !!reviewGatePrompt || !!exitHandoffPrompt,
2911
2835
  history: commandHistory,
2836
+ onHistoryEntry,
2912
2837
  commands,
2913
2838
  prefillInput,
2914
2839
  onPrefillConsumed,
@@ -3049,8 +2974,9 @@ function RewindSelector({ messages, onSelect, onCancel }) {
3049
2974
  const items = messages.map((msg, idx) => ({
3050
2975
  msg,
3051
2976
  originalIndex: idx
3052
- })).filter(({ msg }) => msg.role === "user").map(({ msg, originalIndex }, index) => {
3053
- const preview = msg.content.length > 50 ? msg.content.substring(0, 50) + "..." : msg.content;
2977
+ })).filter(({ msg }) => msg.role === "user" && !msg.metadata?.steered).map(({ msg, originalIndex }, index) => {
2978
+ const content = sanitizeTerminalText(msg.content);
2979
+ const preview = content.length > 50 ? content.substring(0, 50) + "..." : content;
3054
2980
  const timestamp = new Date(msg.timestamp).toLocaleString();
3055
2981
  return {
3056
2982
  label: `[${index + 1}] ${timestamp} - ${preview}`,
@@ -3088,7 +3014,8 @@ function RewindSelector({ messages, onSelect, onCancel }) {
3088
3014
  value: "cancel"
3089
3015
  }];
3090
3016
  const selectedMessage = selectedMessageIndex !== null && selectedMessageIndex >= 0 && selectedMessageIndex < messages.length ? messages[selectedMessageIndex] : null;
3091
- const selectedPreview = selectedMessage ? selectedMessage.content.length > 50 ? selectedMessage.content.substring(0, 50) + "..." : selectedMessage.content : "";
3017
+ const selectedContent = selectedMessage ? sanitizeTerminalText(selectedMessage.content) : "";
3018
+ const selectedPreview = selectedContent.length > 50 ? selectedContent.substring(0, 50) + "..." : selectedContent;
3092
3019
  return /* @__PURE__ */ React.createElement(Box, {
3093
3020
  flexDirection: "column",
3094
3021
  marginY: 1
@@ -3129,7 +3056,8 @@ function SessionSelector({ sessions, currentSession, onSelect, onCancel }) {
3129
3056
  const items = sessions.map((session, index) => {
3130
3057
  const userMessages = session.messages.filter((msg) => msg.role === "user");
3131
3058
  const lastUserMessage = userMessages[userMessages.length - 1];
3132
- const preview = lastUserMessage ? lastUserMessage.content.slice(0, 50).replace(/\n/g, " ") + (lastUserMessage.content.length > 50 ? "..." : "") : "No messages";
3059
+ const lastContent = lastUserMessage ? sanitizeTerminalText(lastUserMessage.content) : "";
3060
+ const preview = lastUserMessage ? lastContent.slice(0, 50).replace(/\n/g, " ") + (lastContent.length > 50 ? "..." : "") : "No messages";
3133
3061
  const timeAgo = formatTimeAgo(session.updatedAt);
3134
3062
  return {
3135
3063
  key: session.id,
@@ -3162,7 +3090,7 @@ function SessionSelector({ sessions, currentSession, onSelect, onCancel }) {
3162
3090
  }, /* @__PURE__ */ React.createElement(Box, {
3163
3091
  marginBottom: 1,
3164
3092
  flexDirection: "column"
3165
- }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "Resume session: \"", selectedSession?.name, "\""), /* @__PURE__ */ React.createElement(Text, { dimColor: true }, selectedSession?.messages.length, " messages | ", selectedSession?.model, " |", " ", selectedSession?.metadata?.totalTokens?.toLocaleString() ?? 0, " tokens"), hasUnsavedWork && /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "Warning: Your current session has unsaved messages. Use /save first if needed.")), /* @__PURE__ */ React.createElement(SelectInput, {
3093
+ }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "Resume session: \"", sanitizeTerminalText(selectedSession?.name ?? ""), "\""), /* @__PURE__ */ React.createElement(Text, { dimColor: true }, selectedSession?.messages.length, " messages | ", selectedSession?.model, " |", " ", selectedSession?.metadata?.totalTokens?.toLocaleString() ?? 0, " tokens"), hasUnsavedWork && /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "Warning: Your current session has unsaved messages. Use /save first if needed.")), /* @__PURE__ */ React.createElement(SelectInput, {
3166
3094
  items: [{
3167
3095
  label: "Yes, resume this session",
3168
3096
  value: "confirm"
@@ -3215,18 +3143,41 @@ function ModelPicker({ models, currentModelId, onSelect, onCancel }) {
3215
3143
  }
3216
3144
  //#endregion
3217
3145
  //#region src/components/EnvironmentPicker.tsx
3218
- function EnvironmentPicker({ onSelect }) {
3146
+ const NoIndicator = () => null;
3147
+ function hostOf$1(url) {
3148
+ try {
3149
+ return new URL(url).host;
3150
+ } catch {
3151
+ return url;
3152
+ }
3153
+ }
3154
+ function EnvironmentPicker({ onSelect, onCancel, defaultUrl = getDefaultApiUrl() }) {
3219
3155
  const [phase, setPhase] = useState("menu");
3220
3156
  const [customValue, setCustomValue] = useState("");
3221
3157
  const [error, setError] = useState(null);
3222
- const items = [{
3223
- label: `Local dev server (${LOCAL_DEV_URL})`,
3224
- value: "dev"
3225
- }, {
3226
- label: "Custom / self-hosted URL…",
3227
- value: "custom"
3228
- }];
3158
+ const cancelHint = onCancel ? "Esc to cancel" : "Ctrl+C to cancel";
3159
+ useInput((_input, key) => {
3160
+ if (key.escape) onCancel?.();
3161
+ }, { isActive: onCancel !== void 0 });
3162
+ const items = [
3163
+ ...defaultUrl ? [{
3164
+ label: `Hosted (${hostOf$1(defaultUrl)})`,
3165
+ value: "prod"
3166
+ }] : [],
3167
+ {
3168
+ label: `Local dev server (${LOCAL_DEV_URL})`,
3169
+ value: "dev"
3170
+ },
3171
+ {
3172
+ label: "Custom / self-hosted URL…",
3173
+ value: "custom"
3174
+ }
3175
+ ];
3229
3176
  const handleMenuSelect = (item) => {
3177
+ if (item.value === "prod") {
3178
+ onSelect({ target: "prod" });
3179
+ return;
3180
+ }
3230
3181
  if (item.value === "dev") {
3231
3182
  onSelect({ target: "dev" });
3232
3183
  return;
@@ -3252,15 +3203,94 @@ function EnvironmentPicker({ onSelect }) {
3252
3203
  },
3253
3204
  onSubmit: handleCustomSubmit,
3254
3205
  placeholder: "https://app.example.com"
3255
- })), error && /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { color: "red" }, error)), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "Enter to confirm, Ctrl+C to cancel")));
3206
+ })), error && /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { color: "red" }, error)), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "Enter to confirm, ", cancelHint)));
3256
3207
  return /* @__PURE__ */ React.createElement(Box, {
3257
3208
  flexDirection: "column",
3258
3209
  marginY: 1
3259
3210
  }, /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "🌍 Where should b4m connect?")), /* @__PURE__ */ React.createElement(SelectInput, {
3260
3211
  items,
3261
3212
  onSelect: handleMenuSelect,
3213
+ indicatorComponent: NoIndicator,
3262
3214
  itemComponent: ({ isSelected, label }) => /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Text, { color: isSelected ? "cyan" : void 0 }, isSelected ? "❯ " : " ", label))
3263
- }), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "Use ↑↓ arrows to navigate, Enter to select, Ctrl+C to cancel")));
3215
+ }), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "Use ", String.fromCodePoint(8593, 8595), " arrows to navigate, Enter to select, ", cancelHint)));
3216
+ }
3217
+ //#endregion
3218
+ //#region src/utils/copyToClipboard.ts
3219
+ function osc52(text) {
3220
+ return `\x1b]52;c;${Buffer.from(text, "utf8").toString("base64")}\x07`;
3221
+ }
3222
+ function isSshSession(env) {
3223
+ return Boolean(env.SSH_CONNECTION || env.SSH_TTY);
3224
+ }
3225
+ const X_TOOLS = [["xclip", ["-selection", "clipboard"]], ["xsel", ["--clipboard", "--input"]]];
3226
+ /**
3227
+ * Clipboard commands to try, in order. Over SSH only a DISPLAY with a host part (`ssh -X` sets
3228
+ * `localhost:10.0`) can reach the user's own screen; any other tool would fill the remote host's clipboard.
3229
+ */
3230
+ function clipboardCommands(platform, env) {
3231
+ if (isSshSession(env)) {
3232
+ const display = env.DISPLAY ?? "";
3233
+ return display.indexOf(":") > 0 && !display.startsWith("unix:") ? X_TOOLS : [];
3234
+ }
3235
+ if (platform === "darwin") return [["pbcopy", []]];
3236
+ if (platform === "win32") return [["clip", []]];
3237
+ const display = [];
3238
+ if (env.WAYLAND_DISPLAY) display.push(["wl-copy", []]);
3239
+ if (env.DISPLAY) display.push(...X_TOOLS);
3240
+ if (env.WSL_DISTRO_NAME) display.push(["clip.exe", []]);
3241
+ return display;
3242
+ }
3243
+ function runTool(spawn, command, args, text, timeoutMs) {
3244
+ return new Promise((resolve) => {
3245
+ let settled = false;
3246
+ const done = (ok) => {
3247
+ if (settled) return;
3248
+ settled = true;
3249
+ clearTimeout(timer);
3250
+ resolve(ok);
3251
+ };
3252
+ const child = spawn(command, args, { stdio: [
3253
+ "pipe",
3254
+ "ignore",
3255
+ "ignore"
3256
+ ] });
3257
+ const timer = setTimeout(() => {
3258
+ child.kill();
3259
+ done(false);
3260
+ }, timeoutMs);
3261
+ child.on("error", () => done(false));
3262
+ child.on("exit", (code) => done(code === 0));
3263
+ child.stdin?.on("error", () => done(false));
3264
+ child.stdin?.end(text);
3265
+ });
3266
+ }
3267
+ function defaultWriteTerminal(data) {
3268
+ if (!process.stdout.isTTY) return false;
3269
+ process.stdout.write(data);
3270
+ return true;
3271
+ }
3272
+ /**
3273
+ * Locally the platform tool goes first and OSC 52 is the fallback. Over SSH OSC 52 goes first,
3274
+ * since it is what reaches the user's terminal.
3275
+ */
3276
+ async function copyToClipboard(text, deps = {}) {
3277
+ const platform = deps.platform ?? process.platform;
3278
+ const env = deps.env ?? process.env;
3279
+ const spawn$1 = deps.spawn ?? spawn;
3280
+ const writeTerminal = deps.writeTerminal ?? defaultWriteTerminal;
3281
+ const timeoutMs = deps.timeoutMs ?? 2e3;
3282
+ const sendOsc52 = () => {
3283
+ try {
3284
+ return writeTerminal(osc52(text));
3285
+ } catch {
3286
+ return false;
3287
+ }
3288
+ };
3289
+ const sentFirst = isSshSession(env) && sendOsc52();
3290
+ for (const [command, args] of clipboardCommands(platform, env)) try {
3291
+ if (await runTool(spawn$1, command, args, text, timeoutMs)) return "clipboard";
3292
+ } catch {}
3293
+ return (isSshSession(env) ? sentFirst : sendOsc52()) ? "terminal" : "failed";
3264
3294
  }
3265
3295
  //#endregion
3266
3296
  //#region src/components/LoginFlow.tsx
@@ -3327,18 +3357,34 @@ function extractErrorMessage(err) {
3327
3357
  if (err instanceof Error) return err.message || "Unknown error occurred";
3328
3358
  return "Unknown error occurred";
3329
3359
  }
3330
- function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, onError }) {
3360
+ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, onError, onCancel }) {
3331
3361
  const [status, setStatus] = useState("initiating");
3332
3362
  const [deviceFlow, setDeviceFlow] = useState(null);
3333
3363
  const [statusMessage, setStatusMessage] = useState("Initiating device authorization...");
3334
3364
  const [error, setError] = useState(null);
3335
3365
  const [account, setAccount] = useState(null);
3366
+ const [copyResult, setCopyResult] = useState(null);
3367
+ const callbacks = useRef({
3368
+ onSuccess,
3369
+ onError,
3370
+ onCancel
3371
+ });
3372
+ callbacks.current = {
3373
+ onSuccess,
3374
+ onError,
3375
+ onCancel
3376
+ };
3377
+ const abortRef = useRef(null);
3378
+ const tokenIssued = useRef(false);
3336
3379
  useEffect(() => {
3380
+ const abort = new AbortController();
3381
+ abortRef.current = abort;
3382
+ let successTimer;
3337
3383
  const runLoginFlow = async () => {
3338
3384
  const oauth = new OAuthClient(apiUrl);
3339
3385
  try {
3340
3386
  setStatus("initiating");
3341
- const deviceFlowResponse = await oauth.initiateDeviceFlow();
3387
+ const deviceFlowResponse = await oauth.initiateDeviceFlow(abort.signal);
3342
3388
  setDeviceFlow({
3343
3389
  ...deviceFlowResponse,
3344
3390
  verification_uri: stripControlChars(deviceFlowResponse.verification_uri),
@@ -3347,51 +3393,74 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
3347
3393
  });
3348
3394
  setStatus("waiting");
3349
3395
  setStatusMessage("Waiting for authorization...");
3350
- const tokens = await oauth.waitForAuthorization(deviceFlowResponse.device_code, deviceFlowResponse.interval, (message) => setStatusMessage(message));
3396
+ const tokens = await oauth.waitForAuthorization(deviceFlowResponse.device_code, deviceFlowResponse.interval, (message) => setStatusMessage(message), abort.signal);
3397
+ if (abort.signal.aborted) return;
3398
+ tokenIssued.current = true;
3351
3399
  const userId = jwt.decode(tokens.access_token)?.id || "";
3352
3400
  const expiresAt = new Date(Date.now() + tokens.expires_in * 1e3).toISOString();
3353
- await configStore.setAuthTokens({
3401
+ await configStore.withRefreshLock(() => configStore.setAuthTokens({
3354
3402
  accessToken: tokens.access_token,
3355
3403
  refreshToken: tokens.refresh_token,
3356
3404
  expiresAt,
3357
3405
  userId
3358
- });
3406
+ }));
3359
3407
  setAccount({ userId });
3360
3408
  setStatus("success");
3361
3409
  setStatusMessage("Successfully authenticated!");
3362
- setTimeout(() => onSuccess(), 1500);
3410
+ successTimer = setTimeout(() => callbacks.current.onSuccess(), 1500);
3363
3411
  new ApiClient(apiUrl, configStore).get("/api/identify").then((res) => setAccount({
3364
3412
  userId,
3365
3413
  email: stripControlChars(res?.user?.email),
3366
3414
  username: stripControlChars(res?.user?.username)
3367
3415
  })).catch(() => {});
3368
3416
  } catch (err) {
3417
+ if (abort.signal.aborted) return;
3369
3418
  setStatus("error");
3370
3419
  const errorMessage = stripControlChars(extractErrorMessage(err));
3371
3420
  setError(errorMessage);
3372
- onError(new Error(errorMessage));
3421
+ callbacks.current.onError(new Error(errorMessage));
3373
3422
  }
3374
3423
  };
3375
3424
  runLoginFlow();
3376
- }, [
3377
- apiUrl,
3378
- configStore,
3379
- onSuccess,
3380
- onError
3381
- ]);
3382
- const uris = deviceFlow ? [deviceFlow.verification_uri, deviceFlow.verification_uri_complete] : [];
3425
+ return () => {
3426
+ abort.abort(/* @__PURE__ */ new Error("Sign-in cancelled"));
3427
+ clearTimeout(successTimer);
3428
+ };
3429
+ }, [apiUrl, configStore]);
3430
+ const uri = deviceFlow?.verification_uri || void 0;
3431
+ const rawLink = deviceFlow?.verification_uri_complete || void 0;
3383
3432
  const isTrustedUri = (u) => isBrowserOpenableUrl(u) && isOnApiOrigin(u, apiUrl);
3384
- const untrustedUri = uris.find((u) => !isTrustedUri(u));
3385
- const trusted = uris.length > 0 && uris.every(isTrustedUri);
3433
+ const uriTrusted = uri !== void 0 && isTrustedUri(uri);
3434
+ const link = rawLink && isTrustedUri(rawLink) && (uri === void 0 || uriTrusted) ? rawLink : void 0;
3435
+ const untrustedUri = [uri, rawLink].find((u) => u && !isTrustedUri(u));
3436
+ const trusted = Boolean(deviceFlow) && uriTrusted && !untrustedUri;
3437
+ const warning = !deviceFlow ? void 0 : uri === void 0 ? link ? "Not opening browser: the server sent a sign-in link but no verification URL." : "Not opening browser: the server did not return a verification URL." : !untrustedUri ? void 0 : isOnApiOrigin(untrustedUri, apiUrl) ? `Not opening browser: verification URL ${originOf(untrustedUri)} is not https (plain http is only auto-opened on localhost). Only continue if you trust it.` : `Not opening browser: verification URL origin ${originOf(untrustedUri)} does not match the configured server ${originOf(apiUrl)}. Only continue if you trust it.`;
3386
3438
  useEffect(() => {
3387
- if (deviceFlow && status === "waiting" && trusted) open(deviceFlow.verification_uri_complete).catch((err) => {
3439
+ const openTarget = link ?? deviceFlow?.verification_uri;
3440
+ if (openTarget && status === "waiting" && trusted) open(openTarget).catch((err) => {
3388
3441
  console.error("Failed to auto-open browser:", err);
3389
3442
  });
3390
3443
  }, [
3444
+ link,
3391
3445
  deviceFlow,
3392
3446
  status,
3393
3447
  trusted
3394
3448
  ]);
3449
+ const { isRawModeSupported } = useStdin();
3450
+ const copyTarget = link ?? (uriTrusted ? deviceFlow?.user_code : void 0);
3451
+ const copying = useRef(false);
3452
+ useInput((input, key) => {
3453
+ if (key.escape && callbacks.current.onCancel && !tokenIssued.current) {
3454
+ abortRef.current?.abort(/* @__PURE__ */ new Error("Sign-in cancelled"));
3455
+ callbacks.current.onCancel();
3456
+ return;
3457
+ }
3458
+ if (key.ctrl || key.meta || input.toLowerCase() !== "c" || !copyTarget || copying.current) return;
3459
+ copying.current = true;
3460
+ copyToClipboard(copyTarget).then(setCopyResult).catch(() => setCopyResult("failed")).finally(() => {
3461
+ copying.current = false;
3462
+ });
3463
+ }, { isActive: (status === "waiting" || status === "initiating") && isRawModeSupported });
3395
3464
  if (status === "initiating") return /* @__PURE__ */ React.createElement(Box, {
3396
3465
  flexDirection: "column",
3397
3466
  padding: 1
@@ -3418,22 +3487,43 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
3418
3487
  }, /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, {
3419
3488
  color: "cyan",
3420
3489
  bold: true
3421
- }, "🔐 Device Authorization")), trusted ? /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, null, "Opening browser automatically... If it doesn't open, please visit:")) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, {
3490
+ }, "🔐 Device Authorization")), warning && /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, {
3422
3491
  color: "red",
3423
3492
  bold: true
3424
- }, !untrustedUri ? "Not opening browser: the server did not return a verification URL." : isOnApiOrigin(untrustedUri, apiUrl) ? `Not opening browser: verification URL ${originOf(untrustedUri)} is not https (plain http is only auto-opened on localhost). Only continue if you trust it.` : `Not opening browser: verification URL origin ${originOf(untrustedUri)} does not match the configured server ${originOf(apiUrl)}. Only continue if you trust it.`)), /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, null, "Please visit:"))), /* @__PURE__ */ React.createElement(Box, {
3493
+ }, warning)), link ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, null, trusted ? "Opening browser automatically... If it doesn't open, visit this link:" : "To sign in, visit this link:")), /* @__PURE__ */ React.createElement(Box, {
3494
+ marginBottom: 1,
3495
+ paddingLeft: 2
3496
+ }, /* @__PURE__ */ React.createElement(Text, {
3497
+ color: "blue",
3498
+ bold: true
3499
+ }, link)), /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, uri ? /* @__PURE__ */ React.createElement(Text, null, "Or open ", /* @__PURE__ */ React.createElement(Text, { color: "blue" }, uri), " and enter this code:") : /* @__PURE__ */ React.createElement(Text, null, "Check that the page shows this code:"))) : /* @__PURE__ */ React.createElement(React.Fragment, null, uri && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, null, trusted ? "Opening browser automatically... If it doesn't open, please visit:" : uriTrusted ? "Please visit:" : "The server asked you to visit:")), /* @__PURE__ */ React.createElement(Box, {
3425
3500
  marginBottom: 1,
3426
3501
  paddingLeft: 2
3427
3502
  }, /* @__PURE__ */ React.createElement(Text, {
3428
3503
  color: "blue",
3429
3504
  bold: true
3430
- }, deviceFlow?.verification_uri)), /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, null, "And enter this code when prompted:")), /* @__PURE__ */ React.createElement(Box, {
3505
+ }, uri))), /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, null, "And enter this code when prompted:"))), /* @__PURE__ */ React.createElement(Box, {
3431
3506
  marginBottom: 1,
3432
3507
  paddingLeft: 2
3433
3508
  }, /* @__PURE__ */ React.createElement(Text, {
3434
3509
  color: "yellow",
3435
3510
  bold: true
3436
- }, deviceFlow?.user_code)), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { color: "cyan" }, /* @__PURE__ */ React.createElement(Spinner, { type: "dots" }), " ", statusMessage)), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "Expires in ", deviceFlow ? Math.floor(deviceFlow.expires_in / 60) : 0, " minutes")));
3511
+ }, deviceFlow?.user_code)), copyTarget && isRawModeSupported && /* @__PURE__ */ React.createElement(Box, null, copyResult === null ? /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "Press c to copy the ", link ? "link" : "code") : copyResult === "failed" ? /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "Copy failed, select the ", link ? "link" : "code", " above") : copyResult === "terminal" ? /* @__PURE__ */ React.createElement(Text, { color: "green" }, "Sent the ", link ? "link" : "code", " to your terminal clipboard (if it does not paste, select it above)") : /* @__PURE__ */ React.createElement(Text, { color: "green" }, link ? "Link" : "Code", " copied to clipboard")), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { color: "cyan" }, /* @__PURE__ */ React.createElement(Spinner, { type: "dots" }), " ", statusMessage)), /* @__PURE__ */ React.createElement(Box, { marginTop: 1 }, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "Expires in ", deviceFlow ? Math.floor(deviceFlow.expires_in / 60) : 0, " minutes")), onCancel && isRawModeSupported && /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "Press Esc to cancel.")));
3512
+ }
3513
+ //#endregion
3514
+ //#region src/utils/whoami.ts
3515
+ /** What /whoami prints. A signed-out local session says so even when another process has since saved a sign-in. */
3516
+ function whoamiReport(authTokens, session, now = /* @__PURE__ */ new Date()) {
3517
+ if (session.signedOutLocal) return `This session is local and signed out. ${SIGN_IN_HINT}`;
3518
+ if (!authTokens) return "Not authenticated. Run /login to authenticate.";
3519
+ const expires = new Date(authTokens.expiresAt);
3520
+ return [
3521
+ "\n👤 Current User:\n",
3522
+ `User ID: ${authTokens.userId}`,
3523
+ `Status: ${expires <= now ? `${String.fromCodePoint(9888, 65039)} Token expired` : `${String.fromCodePoint(9989)} Authenticated`}`,
3524
+ `Expires: ${expires.toLocaleString()}`,
3525
+ ""
3526
+ ].join("\n");
3437
3527
  }
3438
3528
  //#endregion
3439
3529
  //#region src/utils/formatStep.ts
@@ -3580,6 +3670,17 @@ function resolveModelCommand(models, args, currentModel) {
3580
3670
  //#region src/utils/performModelSwitch.ts
3581
3671
  const MODEL_SWITCH_BUSY_MESSAGE = "Agent is busy - wait for the current response to finish before switching models.";
3582
3672
  /**
3673
+ * What to save for a picked model. A model on an Ollama found by detection also saves that host and the
3674
+ * local default, since later runs that never detect (`b4m -p`) must reach it instead of a hosted model.
3675
+ */
3676
+ function modelSavePatch(model, config, detectedOllama) {
3677
+ return detectedOllama !== null && detectedOllama.modelIds.has(model.id) && (!config.ollamaHost || config.ollamaHost === detectedOllama.host) ? {
3678
+ defaultModel: model.id,
3679
+ ollamaHost: detectedOllama.host,
3680
+ localDefaultModel: model.id
3681
+ } : { defaultModel: model.id };
3682
+ }
3683
+ /**
3583
3684
  * Side-effect layer for a `/model` switch, shared by the argument dispatcher and
3584
3685
  * the interactive picker so both entry points get the same guards and messages.
3585
3686
  *
@@ -3608,6 +3709,21 @@ async function performModelSwitch(model, deps) {
3608
3709
  deps.error(`Failed to switch model: ${error instanceof Error ? error.message : String(error)}`);
3609
3710
  }
3610
3711
  }
3712
+ //#endregion
3713
+ //#region src/utils/reportCommandErrors.ts
3714
+ /**
3715
+ * Wraps the interactive slash-command handler so a command that fails (a config save that was refused, a disk
3716
+ * error) prints why and the session goes on; left unhandled, the rejection would end the CLI.
3717
+ */
3718
+ function reportCommandErrors(handler, report) {
3719
+ return async (command, args) => {
3720
+ try {
3721
+ await handler(command, args);
3722
+ } catch (error) {
3723
+ report(`/${command} failed: ${error instanceof Error ? error.message : String(error)}`);
3724
+ }
3725
+ };
3726
+ }
3611
3727
  /** Per-line elision caps (chars) keeping single items from eating the budget. */
3612
3728
  const MAX_ITEM_CHARS = 160;
3613
3729
  /**
@@ -3860,7 +3976,7 @@ function extractJsonObject(text) {
3860
3976
  * timestamp so the user knows how fresh the context is.
3861
3977
  */
3862
3978
  function formatHandoffOutput(handoff) {
3863
- return formatHandoff(handoff, { includeTimestamp: true });
3979
+ return sanitizeTerminalText(formatHandoff(handoff, { includeTimestamp: true }));
3864
3980
  }
3865
3981
  /**
3866
3982
  * Build the system message that injects handoff context into a resumed
@@ -4001,7 +4117,8 @@ function buildLocalHandoff(session, workflowOverride) {
4001
4117
  }
4002
4118
  /**
4003
4119
  * Render a full Markdown handoff document from session state. Includes
4004
- * session metadata, all decisions and open blockers verbatim, the last
4120
+ * session metadata, all decisions and open blockers verbatim (minus terminal
4121
+ * control characters, see sanitizeTerminalText), the last
4005
4122
  * `LOCAL_HANDOFF_MESSAGE_TAIL` messages role-labeled and lightly truncated,
4006
4123
  * and a pointer to the on-disk session JSON for deeper context.
4007
4124
  *
@@ -4085,7 +4202,7 @@ function renderLocalHandoffMarkdown(session, sessionJsonPath) {
4085
4202
  lines.push(content);
4086
4203
  lines.push("");
4087
4204
  }
4088
- return lines.join("\n");
4205
+ return sanitizeTerminalText(lines.join("\n"));
4089
4206
  }
4090
4207
  function appendMarkdownSection(lines, heading, items) {
4091
4208
  if (items.length === 0) return;
@@ -7458,6 +7575,7 @@ function hearthSessionFromStore() {
7458
7575
  */
7459
7576
  function createBuiltinModules(config, apiClient) {
7460
7577
  const modules = [];
7578
+ if (apiClient.signedOut) return modules;
7461
7579
  if (config.features?.tavern) modules.push(new TavernModule(apiClient, (entry) => useCliStore.getState().addTavernLogEntry(entry), () => useCliStore.getState().tavernActivityLog));
7462
7580
  if (config.features?.hearth) modules.push(new HearthModule(apiClient, () => hearthSessionFromStore()));
7463
7581
  return modules;
@@ -8011,9 +8129,11 @@ function updatePendingAssistant(update) {
8011
8129
  * step handlers already used) and emits tavern events through the bridge
8012
8130
  * singleton; neither owns React-lifecycle state.
8013
8131
  */
8132
+ let nextSubagentRunId = 0;
8014
8133
  function wireAgentEvents(input) {
8015
- const { agent, orchestrator } = input;
8134
+ const { agent, orchestrator, isCurrent = () => true } = input;
8016
8135
  const stepHandler = (step) => {
8136
+ if (!isCurrent()) return;
8017
8137
  updatePendingAssistant((message) => ({
8018
8138
  ...message,
8019
8139
  metadata: {
@@ -8028,6 +8148,7 @@ function wireAgentEvents(input) {
8028
8148
  text: ""
8029
8149
  };
8030
8150
  const textDeltaHandler = ({ delta, iteration }) => {
8151
+ if (!isCurrent()) return;
8031
8152
  updatePendingAssistant((message) => {
8032
8153
  const sameStream = liveText.messageId === message.id && liveText.iteration === iteration;
8033
8154
  liveText = {
@@ -8042,6 +8163,7 @@ function wireAgentEvents(input) {
8042
8163
  });
8043
8164
  };
8044
8165
  const clearLiveText = () => {
8166
+ if (!isCurrent()) return;
8045
8167
  if (!liveText.text) return;
8046
8168
  liveText = {
8047
8169
  ...liveText,
@@ -8069,6 +8191,7 @@ function wireAgentEvents(input) {
8069
8191
  }
8070
8192
  };
8071
8193
  const tavernActionHandler = (step) => {
8194
+ if (!isCurrent()) return;
8072
8195
  const toolName = step.metadata?.toolName ?? "tool";
8073
8196
  const toolUseId = `${toolName}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
8074
8197
  const queue = pendingToolUseIds.get(toolName) ?? [];
@@ -8082,6 +8205,7 @@ function wireAgentEvents(input) {
8082
8205
  });
8083
8206
  };
8084
8207
  const tavernObservationHandler = (step) => {
8208
+ if (!isCurrent()) return;
8085
8209
  const toolName = step.metadata?.toolName;
8086
8210
  let toolUseId;
8087
8211
  if (toolName) {
@@ -8107,6 +8231,7 @@ function wireAgentEvents(input) {
8107
8231
  });
8108
8232
  };
8109
8233
  const tavernFinalAnswerHandler = (step) => {
8234
+ if (!isCurrent()) return;
8110
8235
  const text = typeof step.content === "string" ? step.content : "";
8111
8236
  if (!text) return;
8112
8237
  bridgePresence.emitEvent({
@@ -8119,8 +8244,8 @@ function wireAgentEvents(input) {
8119
8244
  agent.on("observation", tavernObservationHandler);
8120
8245
  agent.on("final_answer", tavernFinalAnswerHandler);
8121
8246
  const subagentRunState = /* @__PURE__ */ new WeakMap();
8122
- let nextSubagentRunId = 0;
8123
8247
  orchestrator.setBeforeRunCallback((subagent, subagentType) => {
8248
+ if (!isCurrent()) return;
8124
8249
  subagent.on("thought", stepHandler);
8125
8250
  subagent.on("observation", stepHandler);
8126
8251
  subagent.on("action", stepHandler);
@@ -8129,6 +8254,7 @@ function wireAgentEvents(input) {
8129
8254
  subagent.on("final_answer", tavernFinalAnswerHandler);
8130
8255
  const runId = `run-${nextSubagentRunId++}`;
8131
8256
  const usageHandler = () => {
8257
+ if (!isCurrent()) return;
8132
8258
  useCliStore.getState().updateLiveSubagentUsage(runId, subagentType, subagent.getTokenUsage(), subagent.getCreditsUsage());
8133
8259
  };
8134
8260
  subagentRunState.set(subagent, {
@@ -8157,6 +8283,72 @@ function wireAgentEvents(input) {
8157
8283
  }
8158
8284
  });
8159
8285
  }
8286
+ //#endregion
8287
+ //#region src/bootstrap/startupTrustGates.ts
8288
+ /**
8289
+ * The B4M_* variables bin/bike4mind-cli.mjs sets from the claude-compatible host flags
8290
+ * (--mcp-config, --append-system-prompt, --allowedTools, --settings, --session-id, --resume).
8291
+ * A host app that launches b4m as a drop-in for `claude` passes these on every launch; a
8292
+ * person who passes one alongside a prompt gets the safe inert default.
8293
+ * Keep in sync with the claude-compatible flags block in bin/bike4mind-cli.mjs.
8294
+ */
8295
+ const HOST_FLAG_ENV_KEYS = [
8296
+ "B4M_MCP_CONFIG_FILE",
8297
+ "B4M_APPEND_SYSTEM_PROMPT",
8298
+ "B4M_ALLOWED_TOOLS",
8299
+ "B4M_SETTINGS_JSON",
8300
+ "B4M_SESSION_ID",
8301
+ "B4M_RESUME_ID"
8302
+ ];
8303
+ /**
8304
+ * Whether this is a host-driven launch with work already queued: an initial prompt (the
8305
+ * claude `<prompt>` positional, auto-submitted once init completes) AND at least one host flag.
8306
+ *
8307
+ * Both are required. A bare `b4m "task"` is a person at the terminal who can answer a prompt,
8308
+ * so it keeps today's behaviour. Host flags with no queued prompt also keep it: nothing is
8309
+ * waiting, and whoever is looking at the pane can answer. Only the combination means a prompt
8310
+ * would block work that no one is watching for.
8311
+ */
8312
+ function isHostLaunchWithQueuedPrompt(env = process.env) {
8313
+ if (!env.B4M_INITIAL_PROMPT) return false;
8314
+ return HOST_FLAG_ENV_KEYS.some((key) => Boolean(env[key]));
8315
+ }
8316
+ function decideFolderTrustGate(input) {
8317
+ if (input.alreadyResolved || input.projectTrusted || !input.projectHasB4mFiles || !input.isTty) return "none";
8318
+ return input.hostLaunch ? "inert" : "prompt";
8319
+ }
8320
+ /**
8321
+ * Whether a resolved endpoint still warrants the first-run backend picker: only on a fresh install
8322
+ * of a build with a baked default (nothing chosen yet, nothing signed in). An unresolved endpoint
8323
+ * always gets the picker; init() checks that first.
8324
+ */
8325
+ function shouldShowEndpointPicker({ endpointSource, endpointChosen, hasAuthTokens }) {
8326
+ return endpointSource === "baked-default" && !endpointChosen && !hasAuthTokens;
8327
+ }
8328
+ /** Where a sign-in begins: the backend picker when no endpoint resolves or the first-run gate holds. */
8329
+ function signInStart({ endpoint, endpointChosen, hasAuthTokens }) {
8330
+ if (endpoint.status === "unconfigured") return "endpoint-picker";
8331
+ return shouldShowEndpointPicker({
8332
+ endpointSource: endpoint.source,
8333
+ endpointChosen,
8334
+ hasAuthTokens
8335
+ }) ? "endpoint-picker" : "login";
8336
+ }
8337
+ /**
8338
+ * Whether to show the repo MCP-definition approval prompt. When it is not shown, the pending
8339
+ * servers stay off this session and the caller warns once - the same outcome as declining it,
8340
+ * or as a non-interactive run, with nothing persisted.
8341
+ */
8342
+ function shouldPromptMcpApproval(input) {
8343
+ return input.pendingCount > 0 && !input.alreadyResolved && input.isTty && !input.hostLaunch;
8344
+ }
8345
+ /**
8346
+ * The one-line notice printed when a host launch leaves an untrusted folder's config inert. The path
8347
+ * is escaped like the trust prompt it replaces, since a directory name can carry control bytes.
8348
+ */
8349
+ function hostInertNotice(projectRoot) {
8350
+ return `Project config in ${escapeTerminalControlChars(projectRoot).replace(/\r/g, "\\r").replace(/\n/g, "\\n")} stays inert this session (host launch with a queued prompt; no trust prompt shown). Use /trust folder to trust it later.`;
8351
+ }
8160
8352
  const infoCommands = [
8161
8353
  {
8162
8354
  name: "help",
@@ -8207,7 +8399,9 @@ Terminal Setup:
8207
8399
 
8208
8400
  Keyboard Shortcuts:
8209
8401
  Ctrl+C - Press twice to exit
8210
- Esc - Abort current operation
8402
+ Esc - Abort current operation (queued messages return to the input)
8403
+ Enter (busy) - Steer the running turn with the message
8404
+ Tab (busy) - Queue the message to run as the next turn
8211
8405
  Shift+Tab - Toggle auto-accept edits
8212
8406
  Ctrl+U - Clear current line
8213
8407
  Ctrl+K - Clear from cursor to end of line
@@ -8304,17 +8498,17 @@ Multi-line Input:
8304
8498
  */
8305
8499
  function printDecisions(store) {
8306
8500
  console.log("\n📋 Decision Log\n");
8307
- console.log(formatDecisionsOutput(store.decisions));
8501
+ console.log(sanitizeTerminalText(formatDecisionsOutput(store.decisions)));
8308
8502
  console.log("");
8309
8503
  }
8310
8504
  function printBlockers(store) {
8311
8505
  console.log("\n🚧 Blockers\n");
8312
- console.log(formatBlockersOutput(store.blockers));
8506
+ console.log(sanitizeTerminalText(formatBlockersOutput(store.blockers)));
8313
8507
  console.log("");
8314
8508
  }
8315
8509
  function printReviewGates(store) {
8316
8510
  console.log("\n🛑 Review Gates\n");
8317
- console.log(formatReviewGatesOutput(store.reviewGates));
8511
+ console.log(sanitizeTerminalText(formatReviewGatesOutput(store.reviewGates)));
8318
8512
  console.log("");
8319
8513
  }
8320
8514
  const workflowViewCommands = [
@@ -8394,6 +8588,57 @@ async function handleSandboxTrustDomainCommand(deps, domains) {
8394
8588
  return lines.join("\n");
8395
8589
  }
8396
8590
  //#endregion
8591
+ //#region src/session/steering.ts
8592
+ /**
8593
+ * Steering: user input submitted while a turn runs joins that turn at its next
8594
+ * model request instead of waiting for the turn to end.
8595
+ *
8596
+ * Delivery rides the agent's `drainFeedback` hook (see AgentRunOptions), which
8597
+ * fires after a tool batch resolves or when the model answers with iterations
8598
+ * left, and is never called once the run is aborted. A drain call is therefore
8599
+ * the delivery point: the steers leave the queue and enter the session in one
8600
+ * synchronous step, so each one is delivered exactly once - to the model and
8601
+ * the transcript together - or stays queued for the host to run as a follow-up
8602
+ * turn (turnController.ts) or restore to the input on cancel (index.tsx ESC).
8603
+ */
8604
+ const STEER_PREAMBLE = "The user sent the following while you were working. Take it into account before you continue, and change course if it asks you to.";
8605
+ /** The feedback text the model sees for `steers`, or null when there are none. */
8606
+ function formatSteerFeedback(steers) {
8607
+ if (steers.length === 0) return null;
8608
+ return [STEER_PREAMBLE, ...steers].join("\n\n");
8609
+ }
8610
+ /**
8611
+ * Take every queued steer and record each as a user message on the session.
8612
+ * Returns the feedback for the agent, or null when nothing is queued or the
8613
+ * turn was cancelled (the steers then stay queued).
8614
+ */
8615
+ function deliverSteers(signal) {
8616
+ if (signal.aborted) return null;
8617
+ const store = useCliStore.getState();
8618
+ const session = store.session;
8619
+ if (!session) return null;
8620
+ const steers = store.takeSteerMessages();
8621
+ const feedback = formatSteerFeedback(steers);
8622
+ if (!feedback) return null;
8623
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
8624
+ const steerMessages = steers.map((text) => ({
8625
+ id: v4(),
8626
+ role: "user",
8627
+ content: text,
8628
+ timestamp,
8629
+ metadata: { steered: true }
8630
+ }));
8631
+ store.setSession({
8632
+ ...session,
8633
+ messages: [...session.messages, ...steerMessages],
8634
+ updatedAt: timestamp
8635
+ });
8636
+ return {
8637
+ feedback,
8638
+ steers
8639
+ };
8640
+ }
8641
+ //#endregion
8397
8642
  //#region src/session/turnController.ts
8398
8643
  /**
8399
8644
  * Turn lifecycle (issue #228, phase 2).
@@ -8407,20 +8652,55 @@ async function handleSandboxTrustDomainCommand(deps, domains) {
8407
8652
  * keeps only a thin wrapper that builds the context from its render state.
8408
8653
  */
8409
8654
  /**
8410
- * Run one user turn to completion. Never throws: transport, auth, and abort
8411
- * errors are handled and surfaced to the console; the queue-drain in `finally`
8412
- * recurses with the same context for messages submitted mid-turn.
8655
+ * Run one user turn to completion, then each follow-up queued behind it. Never
8656
+ * throws: transport, auth, and abort errors are handled and surfaced to the
8657
+ * console.
8658
+ *
8659
+ * Only one runTurn turn is in flight at a time. A call that arrives while one
8660
+ * is (a tavern prompt, a bash-command drain, a submit during an ESC unwind) is
8661
+ * queued as a follow-up rather than run as a second agent loop over the same
8662
+ * agent. Other agent runs (custom commands, background results) gate on
8663
+ * `turnInFlight` themselves. After
8664
+ * each turn settles - completed, failed, or cancelled - everything still queued
8665
+ * runs as one combined next turn: follow-ups, steers that never reached a
8666
+ * request boundary, and input submitted after a cancel (ESC moves what was
8667
+ * queued before it back to the input, see index.tsx).
8413
8668
  */
8414
8669
  async function runTurn(message, ctx) {
8415
- const releaseSession = useCliStore.getState().holdSession();
8670
+ const store = useCliStore.getState();
8671
+ if (store.turnInFlight) {
8672
+ store.enqueueMessage(message, "followUp");
8673
+ return;
8674
+ }
8675
+ store.setTurnInFlight(true);
8676
+ const generation = ctx.sessionGeneration?.();
8416
8677
  try {
8417
- await runHeldTurn(message, ctx);
8678
+ let next = message;
8679
+ while (next !== null) {
8680
+ const releaseSession = useCliStore.getState().holdSession();
8681
+ try {
8682
+ await runHeldTurn(next, ctx);
8683
+ } catch (error) {
8684
+ console.error(`\n\u274C ${error instanceof Error ? error.message : String(error)}\n`);
8685
+ logger.debug(`Turn failed outside its error handling: ${error instanceof Error ? error.stack : String(error)}`);
8686
+ } finally {
8687
+ releaseSession();
8688
+ }
8689
+ if (ctx.sessionGeneration?.() !== generation) {
8690
+ useCliStore.getState().restoreQueueToInput();
8691
+ break;
8692
+ }
8693
+ const queued = useCliStore.getState().dequeueAllMessages();
8694
+ next = queued.length > 0 ? queued.join("\n\n") : null;
8695
+ }
8418
8696
  } finally {
8419
- releaseSession();
8697
+ useCliStore.getState().setTurnInFlight(false);
8420
8698
  }
8421
8699
  }
8422
8700
  async function runHeldTurn(message, ctx) {
8423
- const { agent, sessionStore, configStore, commandHistoryStore, customCommandStore, messageBuilder, config, availableModels, agentStore, contextContent, additionalDirectories, featureRegistry, backgroundManager, toolCatalog, todoStore, decisionStore, blockerStore, postEditDiagnostics, workflowStores, setCommandHistory, setAbortController } = ctx;
8701
+ const { agent, sessionStore, configStore, customCommandStore, messageBuilder, config, availableModels, agentStore, contextContent, additionalDirectories, featureRegistry, backgroundManager, toolCatalog, todoStore, decisionStore, blockerStore, postEditDiagnostics, workflowStores, setAbortController } = ctx;
8702
+ const generation = ctx.sessionGeneration?.();
8703
+ const replaced = () => ctx.sessionGeneration?.() !== generation;
8424
8704
  const storeSession = useCliStore.getState().session;
8425
8705
  if (!agent || !storeSession) {
8426
8706
  console.error("❌ CLI failed to initialize. Try restarting b4m.\n");
@@ -8437,8 +8717,6 @@ async function runHeldTurn(message, ctx) {
8437
8717
  status: "running",
8438
8718
  text: message.slice(0, 240)
8439
8719
  });
8440
- await commandHistoryStore.add(message);
8441
- setCommandHistory(await commandHistoryStore.list());
8442
8720
  let activeSession = storeSession;
8443
8721
  if (config?.preferences.autoCompact !== false && activeSession.messages.length >= 6) {
8444
8722
  const tokenCounter = getTokenCounter().forModel(activeSession.model);
@@ -8466,20 +8744,24 @@ async function runHeldTurn(message, ctx) {
8466
8744
  maxIterations: 1,
8467
8745
  streamText: false
8468
8746
  });
8747
+ if (replaced()) return;
8469
8748
  const sessionToCompact = withFlushedWorkflowState(activeSession, workflowStores);
8470
8749
  await sessionStore.save(sessionToCompact);
8471
8750
  const newSession = createCompactedSession(sessionToCompact, result.finalAnswer, preservedMessages, !!(process.env.B4M_SESSION_ID || process.env.B4M_RESUME_ID));
8751
+ if (replaced()) return;
8472
8752
  await logger.initialize(newSession.id);
8753
+ if (replaced()) return;
8473
8754
  useCliStore.getState().setSession(newSession);
8474
8755
  useCliStore.getState().clearPendingMessages();
8475
8756
  console.log("✅ Auto-compacted. Continuing with your message...\n");
8476
8757
  activeSession = newSession;
8477
8758
  }
8478
8759
  } finally {
8479
- useCliStore.getState().setIsThinking(false);
8760
+ if (!replaced()) useCliStore.getState().setIsThinking(false);
8480
8761
  }
8481
8762
  }
8482
8763
  }
8764
+ if (replaced()) return;
8483
8765
  useCliStore.getState().setIsThinking(true);
8484
8766
  const abortController = new AbortController();
8485
8767
  setAbortController(abortController);
@@ -8506,6 +8788,7 @@ async function runHeldTurn(message, ctx) {
8506
8788
  metadata: { steps: [] }
8507
8789
  };
8508
8790
  pendingAssistantId = pendingAssistantMessage.id;
8791
+ if (replaced()) return;
8509
8792
  const sessionWithUserMessage = {
8510
8793
  ...activeSession,
8511
8794
  messages: [...activeSession.messages, userMessage],
@@ -8540,7 +8823,16 @@ async function runHeldTurn(message, ctx) {
8540
8823
  parallelExecution: cliConfig.preferences.enableParallelToolExecution === true,
8541
8824
  isReadOnlyTool: (toolName) => toolCatalog.isReadOnly(toolName),
8542
8825
  workflowReminder,
8543
- drainFeedback: diagnostics ? (phase) => diagnostics.drain(DRAIN_BUDGET_MS[phase], abortController.signal) : void 0,
8826
+ drainFeedback: async (phase) => {
8827
+ const diagnosticsFeedback = diagnostics ? await diagnostics.drain(DRAIN_BUDGET_MS[phase], abortController.signal) : null;
8828
+ const steered = deliverSteers(abortController.signal);
8829
+ if (steered) for (const text of steered.steers) bridgePresence.emitEvent({
8830
+ type: "message",
8831
+ role: "user",
8832
+ text: text.slice(0, 4e3)
8833
+ });
8834
+ return [steered?.feedback, diagnosticsFeedback].filter(Boolean).join("\n\n") || null;
8835
+ },
8544
8836
  onContextLimit: createReactiveCompactionHandler(agent, activeSession)
8545
8837
  });
8546
8838
  } finally {
@@ -8569,6 +8861,7 @@ async function runHeldTurn(message, ctx) {
8569
8861
  ...isEarlyStop(result.completionInfo.finishReason) ? { earlyStopReason: result.completionInfo.finishReason } : {}
8570
8862
  }
8571
8863
  };
8864
+ if (replaced()) return;
8572
8865
  useCliStore.getState().completePendingMessage(0, finalAssistantMessage);
8573
8866
  const currentSession = useCliStore.getState().session;
8574
8867
  if (!currentSession) return;
@@ -8586,11 +8879,11 @@ async function runHeldTurn(message, ctx) {
8586
8879
  await sessionStore.save(updatedSession);
8587
8880
  } catch (error) {
8588
8881
  const stepsBeforeAbort = useCliStore.getState().pendingMessages.find((m) => m.id === pendingAssistantId)?.metadata?.steps;
8589
- useCliStore.getState().clearPendingMessages();
8882
+ if (!replaced()) useCliStore.getState().clearPendingMessages();
8590
8883
  if (error instanceof Error && error.name === "AbortError") {
8591
8884
  logger.debug("[ABORT] Operation aborted by user");
8592
8885
  const currentSession = useCliStore.getState().session;
8593
- if (currentSession) {
8886
+ if (currentSession && !replaced()) {
8594
8887
  const cancelMessage = {
8595
8888
  id: v4(),
8596
8889
  role: "assistant",
@@ -8624,29 +8917,151 @@ async function runHeldTurn(message, ctx) {
8624
8917
  logger.debug(`Full error details: ${error.stack || error.message}`);
8625
8918
  return;
8626
8919
  }
8627
- console.error(`\n❌ ${rawMessage}\n`);
8920
+ console.error(`\n\u274C ${sanitizeTerminalText(rawMessage)}\n`);
8628
8921
  logger.debug(`Full error details: ${error instanceof Error ? error.stack || error.message : String(error)}`);
8629
8922
  } finally {
8630
8923
  const wasAborted = abortController.signal.aborted;
8631
- setAbortController(null);
8632
- useCliStore.getState().setIsThinking(false);
8924
+ if (!replaced()) {
8925
+ setAbortController(null);
8926
+ useCliStore.getState().setIsThinking(false);
8927
+ }
8633
8928
  getProcessHooks()?.fireStop();
8634
8929
  bridgePresence.emitEvent({
8635
8930
  type: "status",
8636
8931
  status: wasAborted ? "idle" : "awaiting_input"
8637
8932
  });
8638
- if (!wasAborted) {
8639
- const queued = useCliStore.getState().dequeueAllMessages();
8640
- if (queued.length > 0) {
8641
- const combined = queued.join("\n\n");
8642
- setImmediate(() => {
8643
- runTurn(combined, ctx);
8644
- });
8645
- }
8646
- }
8647
8933
  }
8648
8934
  }
8649
8935
  //#endregion
8936
+ //#region src/session/restartAfterSignIn.ts
8937
+ const SIGNED_IN_RESTART_MESSAGE = "Signed in; starting a new session on Bike4Mind models.";
8938
+ /** How long a sign-in waits for the running session to let go of its MCP servers and the rest (ms). */
8939
+ const SESSION_RELEASE_TIMEOUT_MS = 5e3;
8940
+ /**
8941
+ * A sign-in rebuilds the session from scratch, so the running one is released first; otherwise its MCP servers,
8942
+ * feature modules and background agents would run alongside the new session's. Its background shells are
8943
+ * stopped too, so their output never reaches the signed-in session.
8944
+ */
8945
+ async function restartAfterSignIn({ release, restart, print }) {
8946
+ const shells = (await release().catch(() => null))?.shellsStopped ?? 0;
8947
+ print(shells > 0 ? `${SIGNED_IN_RESTART_MESSAGE} The local session's background shells (${shells}) were stopped.` : SIGNED_IN_RESTART_MESSAGE);
8948
+ await restart();
8949
+ }
8950
+ //#endregion
8951
+ //#region src/session/releaseSession.ts
8952
+ const errorText = (error) => error instanceof Error ? error.message : String(error);
8953
+ /**
8954
+ * Stops everything the session started, waiting at most `timeoutMs` for the asynchronous parts (session save,
8955
+ * MCP servers, bridge presence). Each step is best-effort, so one failure never skips the rest.
8956
+ */
8957
+ async function releaseSession(resources, timeoutMs) {
8958
+ const step = (name, run) => {
8959
+ try {
8960
+ run();
8961
+ } catch (error) {
8962
+ logger.debug(`[CLEANUP] ${name} error: ${errorText(error)}`);
8963
+ }
8964
+ };
8965
+ const pending = (name, work) => Promise.resolve().then(work).catch((error) => logger.debug(`[CLEANUP] ${name} error: ${errorText(error)}`));
8966
+ const { abortTurn } = resources;
8967
+ if (abortTurn) step("Turn abort", abortTurn);
8968
+ let shellsStopped = 0;
8969
+ step("Shell session reap", () => {
8970
+ shellsStopped = resources.killShellSessions();
8971
+ });
8972
+ step("Bang command reap", resources.killBangCommands);
8973
+ const tasks = [pending("Command history", () => resources.commandHistory.whenIdle())];
8974
+ const { saveSession, mcpManager, featureRegistry, wsManager, agent, backgroundManager, imageStore } = resources;
8975
+ if (saveSession) tasks.push(pending("Session save", saveSession));
8976
+ if (mcpManager) tasks.push(pending("MCP disconnect", () => mcpManager.disconnect()));
8977
+ if (featureRegistry) step("Feature dispose", () => featureRegistry.disposeAll());
8978
+ if (wsManager) {
8979
+ step("WebSocket disconnect", () => wsManager.disconnect());
8980
+ step("WebSocket tool executor", resources.clearWebSocketToolExecutor);
8981
+ }
8982
+ tasks.push(pending("Bridge presence stop", resources.stopBridgePresence));
8983
+ if (agent) step("Agent listeners", () => agent.removeAllListeners());
8984
+ if (backgroundManager) {
8985
+ for (const status of ["queued", "running"]) for (const job of backgroundManager.listJobs()) if (job.status === status) step("Background agent cancel", () => backgroundManager.cancelJob(job.id));
8986
+ }
8987
+ if (imageStore) step("Image store close", () => imageStore.close());
8988
+ let timer;
8989
+ await Promise.race([Promise.all(tasks), new Promise((resolve) => {
8990
+ timer = setTimeout(resolve, timeoutMs);
8991
+ })]);
8992
+ clearTimeout(timer);
8993
+ return { shellsStopped };
8994
+ }
8995
+ //#endregion
8996
+ //#region src/session/backgroundCallbacks.ts
8997
+ /**
8998
+ * Background-agent callbacks for one session. Once `isCurrent` turns false (the session was released for a
8999
+ * sign-in), they do nothing, so the released session's agents never queue a turn in the session that replaced it.
9000
+ */
9001
+ function sessionBackgroundCallbacks(isCurrent) {
9002
+ return {
9003
+ onSubagentUsage: (usage) => {
9004
+ if (!isCurrent()) return;
9005
+ useCliStore.getState().recordSubagentUsage({
9006
+ agentName: usage.agentName,
9007
+ tokens: usage.totalTokens,
9008
+ credits: usage.totalCredits
9009
+ });
9010
+ },
9011
+ onBackgroundStatusChange: (job) => {
9012
+ if (isCurrent()) useCliStore.getState().upsertBackgroundAgent(job);
9013
+ },
9014
+ onGroupCompletion: (notification, groupDescription) => {
9015
+ if (!isCurrent()) return;
9016
+ const store = useCliStore.getState();
9017
+ store.addCompletedGroupNotification(notification, groupDescription);
9018
+ store.setPendingBackgroundTrigger(true);
9019
+ }
9020
+ };
9021
+ }
9022
+ /**
9023
+ * Removes a released session's background agents and live subagent usage from the store. Its callbacks are
9024
+ * retired before its agents are cancelled, so no later status update would ever mark them finished.
9025
+ */
9026
+ function forgetReleasedAgents(jobIds, runIds) {
9027
+ const jobs = new Set(jobIds);
9028
+ const runs = new Set(runIds);
9029
+ useCliStore.setState((state) => ({
9030
+ backgroundAgents: state.backgroundAgents.filter((job) => !jobs.has(job.id)),
9031
+ liveSubagentUsage: Object.fromEntries(Object.entries(state.liveSubagentUsage).filter(([runId]) => !runs.has(runId)))
9032
+ }));
9033
+ }
9034
+ /** Drops background results a released session left waiting, so the next session does not act on them. */
9035
+ function forgetBackgroundCompletions() {
9036
+ const store = useCliStore.getState();
9037
+ store.setPendingBackgroundTrigger(false);
9038
+ store.clearCompletedGroupNotifications();
9039
+ }
9040
+ //#endregion
9041
+ //#region src/session/pendingPrompts.ts
9042
+ const SESSION_ENDED_NOTE = "The session that asked for this review has ended.";
9043
+ /**
9044
+ * Answers every prompt a released session left open (permissions denied, questions and review gates cancelled)
9045
+ * and empties the queues, so nothing it asked can be answered, or acted on, in the session that replaces it.
9046
+ */
9047
+ function settlePendingPrompts() {
9048
+ const { permissionPrompt, permissionQueue, userQuestionPrompt, userQuestionQueue, reviewGatePrompt, reviewGateQueue } = useCliStore.getState();
9049
+ useCliStore.setState({
9050
+ permissionPrompt: null,
9051
+ permissionQueue: [],
9052
+ userQuestionPrompt: null,
9053
+ userQuestionQueue: [],
9054
+ reviewGatePrompt: null,
9055
+ reviewGateQueue: []
9056
+ });
9057
+ for (const prompt of [permissionPrompt, ...permissionQueue]) prompt?.resolve({ action: "deny" });
9058
+ for (const prompt of [userQuestionPrompt, ...userQuestionQueue]) prompt?.resolve({ answers: [] });
9059
+ for (const prompt of [reviewGatePrompt, ...reviewGateQueue]) prompt?.resolve({
9060
+ decision: "rejected",
9061
+ note: SESSION_ENDED_NOTE
9062
+ });
9063
+ }
9064
+ //#endregion
8650
9065
  //#region src/session/lifecycle.ts
8651
9066
  /**
8652
9067
  * Session lifecycle (issue #228, phase 3).
@@ -8740,7 +9155,7 @@ async function createFreshSession(ctx) {
8740
9155
  async function resumeSession(ctx, selected) {
8741
9156
  const loadedSession = await ctx.sessionStore.load(selected.id);
8742
9157
  if (!loadedSession) {
8743
- console.log(`❌ Failed to load session: ${selected.name}`);
9158
+ console.log(`\u274C Failed to load session: ${sanitizeTerminalText(selected.name)}`);
8744
9159
  console.log(" The session file may be corrupted or deleted.");
8745
9160
  return null;
8746
9161
  }
@@ -8756,7 +9171,7 @@ async function resumeSession(ctx, selected) {
8756
9171
  useCliStore.getState().setSession(sessionForState);
8757
9172
  useCliStore.getState().clearPendingMessages();
8758
9173
  ctx.onSessionReplaced();
8759
- console.log(`\n✅ Session resumed: "${sessionForState.name}"`);
9174
+ console.log(`\n\u2705 Session resumed: "${sanitizeTerminalText(sessionForState.name)}"`);
8760
9175
  console.log(`📝 ${sessionForState.messages.length} messages | 🤖 ${sessionForState.model} | 📊 ${sessionForState.metadata.totalTokens.toLocaleString()} tokens\n`);
8761
9176
  if (handoff) {
8762
9177
  console.log("🤝 Session handoff:\n");
@@ -8811,8 +9226,8 @@ async function compactHeldSession(ctx, options) {
8811
9226
  useCliStore.getState().clearPendingMessages();
8812
9227
  ctx.onSessionReplaced();
8813
9228
  console.log("✅ Conversation compacted");
8814
- console.log(`\u{1F4DD} New session: ${newSession.name}`);
8815
- console.log(`\u{1F4BE} Previous session preserved: ${oldSessionName}\n`);
9229
+ console.log(`\u{1F4DD} New session: ${sanitizeTerminalText(newSession.name)}`);
9230
+ console.log(`\u{1F4BE} Previous session preserved: ${sanitizeTerminalText(oldSessionName)}\n`);
8816
9231
  } finally {
8817
9232
  useCliStore.getState().setIsThinking(false);
8818
9233
  }
@@ -8950,7 +9365,7 @@ function renderBanner(startupLog = []) {
8950
9365
  const right = startupLog[i] || "";
8951
9366
  const coloredLeft = leftText ? `${leftAnsi}${leftText}\x1b[0m` : "";
8952
9367
  const gap = " ".repeat(bannerWidth - leftText.length + 2);
8953
- console.log(coloredLeft + gap + truncate(right, rightColWidth));
9368
+ console.log(coloredLeft + gap + truncate(sanitizeTerminalText(right), rightColWidth));
8954
9369
  }
8955
9370
  }
8956
9371
  let exitTimestamp = null;
@@ -8989,7 +9404,8 @@ function CliApp() {
8989
9404
  checkpointStore: null,
8990
9405
  additionalDirectories: [],
8991
9406
  featureRegistry: null,
8992
- pluginDescriptors: []
9407
+ pluginDescriptors: [],
9408
+ signedOutLocal: false
8993
9409
  });
8994
9410
  const [isInitialized, setIsInitialized] = useState(false);
8995
9411
  const [initError, setInitError] = useState(null);
@@ -8997,6 +9413,8 @@ function CliApp() {
8997
9413
  const imageStoreInitPromise = useRef(null);
8998
9414
  const folderTrustResolvedRef = useRef(false);
8999
9415
  const mcpApprovalResolvedRef = useRef(false);
9416
+ const detectedOllamaRef = useRef(null);
9417
+ const initGenerationRef = useRef(0);
9000
9418
  const todoStoreRef = useRef(createTodoStore());
9001
9419
  const decisionStoreRef = useRef(createDecisionStore());
9002
9420
  const blockerStoreRef = useRef(createBlockerStore());
@@ -9011,46 +9429,44 @@ function CliApp() {
9011
9429
  const setShowConfigEditor = useCliStore((state) => state.setShowConfigEditor);
9012
9430
  const setShowMcpViewer = useCliStore((state) => state.setShowMcpViewer);
9013
9431
  const setExitRequested = useCliStore((state) => state.setExitRequested);
9014
- const performCleanup = useCallback(async () => {
9015
- const cleanupTasks = [];
9016
- try {
9017
- getShellSessionManager().killAll();
9018
- } catch (err) {
9019
- logger.debug(`[CLEANUP] Shell session reap error: ${err}`);
9020
- }
9021
- killRunningBangCommands();
9432
+ const sessionResources = (reason) => {
9022
9433
  const session = useCliStore.getState().session;
9023
- if (session) cleanupTasks.push(state.sessionStore.save(session).catch((err) => {
9024
- logger.debug(`[CLEANUP] Session save error: ${err.message}`);
9025
- }));
9026
- if (state.mcpManager) cleanupTasks.push(state.mcpManager.disconnect().catch((err) => {
9027
- logger.debug(`[CLEANUP] MCP disconnect error: ${err.message}`);
9028
- }));
9029
- if (state.featureRegistry) state.featureRegistry.disposeAll();
9030
- if (state.wsManager) {
9031
- state.wsManager.disconnect();
9032
- setWebSocketToolExecutor(null);
9033
- }
9034
- cleanupTasks.push(bridgePresence.stop("cli_exit").catch((err) => {
9035
- logger.debug(`[CLEANUP] Bridge presence stop error: ${err.message}`);
9036
- }));
9037
- if (state.agent) state.agent.removeAllListeners();
9038
- if (state.imageStore) try {
9039
- state.imageStore.close();
9040
- } catch (err) {
9041
- logger.debug(`[CLEANUP] Image store close error: ${err}`);
9042
- }
9043
- await Promise.race([Promise.all(cleanupTasks), new Promise((resolve) => setTimeout(resolve, 500))]);
9434
+ return {
9435
+ abortTurn: reason === "sign_in" ? () => abortControllerRef.current?.abort() : null,
9436
+ killShellSessions: () => {
9437
+ const shells = getShellSessionManager();
9438
+ const running = shells.runningCount();
9439
+ shells.killAll();
9440
+ return running;
9441
+ },
9442
+ killBangCommands: killRunningBangCommands,
9443
+ commandHistory: state.commandHistoryStore,
9444
+ saveSession: session ? () => state.sessionStore.save(session) : null,
9445
+ mcpManager: state.mcpManager,
9446
+ featureRegistry: state.featureRegistry,
9447
+ wsManager: state.wsManager,
9448
+ clearWebSocketToolExecutor: () => setWebSocketToolExecutor(null),
9449
+ stopBridgePresence: () => bridgePresence.stop(reason),
9450
+ agent: state.agent,
9451
+ backgroundManager: state.backgroundManager,
9452
+ imageStore: reason === "cli_exit" ? state.imageStore : null
9453
+ };
9454
+ };
9455
+ const performCleanup = useCallback(async () => {
9456
+ await releaseSession(sessionResources("cli_exit"), 500);
9457
+ await settleSignInRefresh();
9044
9458
  setTimeout(() => {
9045
9459
  process.exit(0);
9046
9460
  }, 100);
9047
9461
  }, [
9048
9462
  state.sessionStore,
9463
+ state.commandHistoryStore,
9049
9464
  state.mcpManager,
9050
9465
  state.agent,
9051
9466
  state.imageStore,
9052
9467
  state.wsManager,
9053
- state.featureRegistry
9468
+ state.featureRegistry,
9469
+ state.backgroundManager
9054
9470
  ]);
9055
9471
  useEffect(() => {
9056
9472
  return getShellSessionManager().subscribe((session) => {
@@ -9059,11 +9475,13 @@ function CliApp() {
9059
9475
  }, []);
9060
9476
  useInput((input, key) => {
9061
9477
  if (key.escape) {
9478
+ if (state.showLoginFlow || state.showEnvironmentPicker) return;
9062
9479
  const store = useCliStore.getState();
9063
9480
  if (store.pastedContent) {
9064
9481
  store.clearPaste();
9065
9482
  return;
9066
9483
  }
9484
+ store.restoreQueueToInput();
9067
9485
  if (state.abortController) {
9068
9486
  logger.debug("[ABORT] ESC pressed - aborting current operation...");
9069
9487
  state.abortController.abort();
@@ -9071,9 +9489,8 @@ function CliApp() {
9071
9489
  ...prev,
9072
9490
  abortController: null
9073
9491
  }));
9074
- useCliStore.getState().setIsThinking(false);
9075
- useCliStore.getState().clearMessageQueue();
9076
- } else useCliStore.getState().clearMessageQueue();
9492
+ store.setIsThinking(false);
9493
+ }
9077
9494
  return;
9078
9495
  }
9079
9496
  if (key.ctrl && input === "c") {
@@ -9105,7 +9522,19 @@ function CliApp() {
9105
9522
  try {
9106
9523
  const startupLog = [];
9107
9524
  const config = await state.configStore.load();
9108
- if (!folderTrustResolvedRef.current && !state.configStore.isProjectTrusted() && state.configStore.projectHasB4mFiles() && Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY)) {
9525
+ const isTty = Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
9526
+ const hostLaunch = isHostLaunchWithQueuedPrompt();
9527
+ const folderTrustGate = decideFolderTrustGate({
9528
+ alreadyResolved: folderTrustResolvedRef.current,
9529
+ projectTrusted: state.configStore.isProjectTrusted(),
9530
+ projectHasB4mFiles: state.configStore.projectHasB4mFiles(),
9531
+ isTty,
9532
+ hostLaunch
9533
+ });
9534
+ if (folderTrustGate === "inert") {
9535
+ folderTrustResolvedRef.current = true;
9536
+ console.log(`\n${hostInertNotice(state.configStore.getProjectRealPath() ?? process.cwd())}\n`);
9537
+ } else if (folderTrustGate === "prompt") {
9109
9538
  folderTrustResolvedRef.current = true;
9110
9539
  setState((prev) => ({
9111
9540
  ...prev,
@@ -9115,7 +9544,12 @@ function CliApp() {
9115
9544
  return;
9116
9545
  }
9117
9546
  const pendingMcp = state.configStore.getPendingMcpApprovals();
9118
- if (pendingMcp.length > 0 && !mcpApprovalResolvedRef.current && Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY)) {
9547
+ if (shouldPromptMcpApproval({
9548
+ alreadyResolved: mcpApprovalResolvedRef.current,
9549
+ pendingCount: pendingMcp.length,
9550
+ isTty,
9551
+ hostLaunch
9552
+ })) {
9119
9553
  mcpApprovalResolvedRef.current = true;
9120
9554
  setState((prev) => ({
9121
9555
  ...prev,
@@ -9140,10 +9574,78 @@ function CliApp() {
9140
9574
  console.warn("Failed to load custom commands:", error instanceof Error ? error.message : String(error));
9141
9575
  }
9142
9576
  const authTokens = await state.configStore.getAuthTokens();
9143
- const tokenExpired = authTokens ? new Date(authTokens.expiresAt) <= /* @__PURE__ */ new Date() : false;
9144
- if (!authTokens || tokenExpired) {
9577
+ if (authTokens && !config.apiConfig?.endpointChosen) await state.configStore.markEndpointChosen();
9578
+ const signIn = await checkSavedSignIn(state.configStore, (rejected) => new ApiClient(requireApiUrl(config.apiConfig), state.configStore).refreshSession(rejected));
9579
+ const tokenGetter = async () => {
9580
+ return (await state.configStore.getAuthTokens())?.accessToken ?? null;
9581
+ };
9582
+ const liveModels = { current: null };
9583
+ const generation = ++initGenerationRef.current;
9584
+ const sessionEnded = () => generation !== initGenerationRef.current;
9585
+ const backendInput = {
9586
+ config,
9587
+ tokenGetter,
9588
+ startupLog,
9589
+ detectOllama: true,
9590
+ getSessionId: () => useCliStore.getState().session?.id,
9591
+ onModelsAdded: (next) => {
9592
+ if (generation !== initGenerationRef.current) return;
9593
+ liveModels.current = next;
9594
+ setState((prev) => ({
9595
+ ...prev,
9596
+ availableModels: next
9597
+ }));
9598
+ }
9599
+ };
9600
+ let signedOutBackend = null;
9601
+ let noLocalModelsReason = null;
9602
+ const signedOutClient = signIn.status === "signed-in" ? null : ApiClient.whileSignedOut(state.configStore);
9603
+ if (signedOutClient) try {
9604
+ signedOutBackend = await buildLlmBackend({
9605
+ ...backendInput,
9606
+ apiClient: signedOutClient
9607
+ });
9608
+ } catch (error) {
9609
+ noLocalModelsReason = error instanceof NoLocalModelsError ? error.reason : extractErrorMessage$1(error);
9610
+ }
9611
+ let apiClient;
9612
+ let backend;
9613
+ const mode = startupMode(signIn, signedOutBackend !== null);
9614
+ if (mode === "signed-in" && signIn.status === "signed-in") {
9615
+ const expiresAt = new Date(signIn.tokens.expiresAt);
9616
+ const daysUntilExpiry = Math.floor((expiresAt.getTime() - Date.now()) / 864e5);
9617
+ startupLog.push(`\u{2705} Authenticated (expires in ${daysUntilExpiry} day${daysUntilExpiry !== 1 ? "s" : ""})`);
9618
+ const apiBaseURL = requireApiUrl(config.apiConfig);
9619
+ const envName = getEnvironmentName(config.apiConfig);
9620
+ startupLog.unshift(`\u{1f30d} API Environment: ${envName} (${apiBaseURL})`);
9621
+ apiClient = new ApiClient(apiBaseURL, state.configStore);
9622
+ if (process.env.B4M_NO_REMOTE_SKILLS !== "1" && config.preferences.enableRemoteSkills !== false) try {
9623
+ state.customCommandStore.setRemoteSource(new RemoteSkillSource(apiClient));
9624
+ await state.customCommandStore.mergeRemoteCommands();
9625
+ const remoteCount = state.customCommandStore.getCommandsBySource("remote").length;
9626
+ if (remoteCount > 0) startupLog.push(`\u{2601}\u{fe0f} Synced ${remoteCount} skill${remoteCount === 1 ? "" : "s"} from B4M web`);
9627
+ } catch (error) {
9628
+ console.warn("Failed to sync remote skills:", error instanceof Error ? error.message : String(error));
9629
+ }
9630
+ backend = await buildLlmBackend({
9631
+ ...backendInput,
9632
+ apiClient
9633
+ });
9634
+ } else if (mode === "local" && signedOutClient && signedOutBackend) {
9635
+ apiClient = signedOutClient;
9636
+ backend = signedOutBackend;
9637
+ if (signIn.status === "expired") startupLog.unshift(SIGN_IN_EXPIRED);
9638
+ if (signIn.status === "unchecked") startupLog.unshift(signInUncheckedMessage(signIn.reason));
9639
+ startupLog.unshift(SIGNED_OUT_BANNER);
9640
+ if (config.features?.tavern || config.features?.hearth) startupLog.push("Tavern and Hearth are Bike4Mind cloud features; they stay off while signed out.");
9641
+ } else {
9642
+ if (noLocalModelsReason) console.log(`\n${noLocalModelsReason}\n`);
9145
9643
  const endpoint = resolveApiEndpoint(config.apiConfig);
9146
- if (endpoint.status === "unconfigured") {
9644
+ if (signInStart({
9645
+ endpoint,
9646
+ endpointChosen: !!config.apiConfig?.endpointChosen,
9647
+ hasAuthTokens: !!authTokens
9648
+ }) === "endpoint-picker") {
9147
9649
  setState((prev) => ({
9148
9650
  ...prev,
9149
9651
  showEnvironmentPicker: true,
@@ -9151,11 +9653,10 @@ function CliApp() {
9151
9653
  }));
9152
9654
  return;
9153
9655
  }
9154
- if (tokenExpired) {
9155
- console.log("\n🔐 Your session has expired. Let's re-authenticate.\n");
9156
- await state.configStore.clearAuthTokens();
9157
- } else console.log("\n🔐 Welcome to B4M CLI! Authentication is required to get started.\n");
9158
- if (endpoint.source === "dev-default") console.log(`🔧 No endpoint configured; defaulting to the local dev server (${endpoint.url}).\n Use \`b4m --prod\` or \`b4m --api-url <url>\` to target a different backend.
9656
+ if (signIn.status === "expired") console.log("\n🔐 Your session has expired. Let's re-authenticate.\n");
9657
+ else if (signIn.status === "unchecked") console.log(`\n${signInUncheckedLoginMessage(signIn.reason)}\n`);
9658
+ else console.log("\n🔐 Welcome to B4M CLI! Sign in to use Bike4Mind cloud models.\n");
9659
+ if (endpoint.status === "configured" && endpoint.source === "dev-default") console.log(`🔧 No endpoint configured; defaulting to the local dev server (${endpoint.url}).\n Use \`b4m --prod\` or \`b4m --api-url <url>\` to target a different backend.
9159
9660
  `);
9160
9661
  setState((prev) => ({
9161
9662
  ...prev,
@@ -9164,30 +9665,8 @@ function CliApp() {
9164
9665
  }));
9165
9666
  return;
9166
9667
  }
9167
- const expiresAt = new Date(authTokens.expiresAt);
9168
- const daysUntilExpiry = Math.floor((expiresAt.getTime() - Date.now()) / 864e5);
9169
- startupLog.push(`✅ Authenticated (expires in ${daysUntilExpiry} day${daysUntilExpiry !== 1 ? "s" : ""})`);
9170
- const apiBaseURL = requireApiUrl(config.apiConfig);
9171
- const envName = getEnvironmentName(config.apiConfig);
9172
- startupLog.unshift(`🌍 API Environment: ${envName} (${apiBaseURL})`);
9173
- const apiClient = new ApiClient(apiBaseURL, state.configStore);
9174
- if (process.env.B4M_NO_REMOTE_SKILLS !== "1" && config.preferences.enableRemoteSkills !== false) try {
9175
- state.customCommandStore.setRemoteSource(new RemoteSkillSource(apiClient));
9176
- await state.customCommandStore.mergeRemoteCommands();
9177
- const remoteCount = state.customCommandStore.getCommandsBySource("remote").length;
9178
- if (remoteCount > 0) startupLog.push(`☁️ Synced ${remoteCount} skill${remoteCount === 1 ? "" : "s"} from B4M web`);
9179
- } catch (error) {
9180
- console.warn("Failed to sync remote skills:", error instanceof Error ? error.message : String(error));
9181
- }
9182
- const tokenGetter = async () => {
9183
- return (await state.configStore.getAuthTokens())?.accessToken ?? null;
9184
- };
9185
- const { llm, wsManager, models, modelInfo } = await buildLlmBackend({
9186
- config,
9187
- apiClient,
9188
- tokenGetter,
9189
- startupLog
9190
- });
9668
+ const { llm, wsManager, models, modelInfo, detectedOllama } = backend;
9669
+ detectedOllamaRef.current = detectedOllama;
9191
9670
  const pinnedSessionId = process.env.B4M_SESSION_ID;
9192
9671
  const resumeSessionId = process.env.B4M_RESUME_ID;
9193
9672
  if (pinnedSessionId && !isValidSessionId(pinnedSessionId)) {
@@ -9240,17 +9719,22 @@ function CliApp() {
9240
9719
  checkpointStore
9241
9720
  });
9242
9721
  let permissionPromptCounter = 0;
9243
- const promptFn = (toolName, args, preview, kind) => {
9722
+ const promptFn = (toolName, args, preview, kind, options) => {
9244
9723
  return new Promise((resolve) => {
9724
+ if (sessionEnded()) {
9725
+ resolve({ action: "deny" });
9726
+ return;
9727
+ }
9245
9728
  getProcessHooks()?.fireNotificationPermissionPrompt(toolName);
9246
9729
  const canBeTrusted = permissionManager.canBeTrusted(toolName);
9247
- const id = `perm-${++permissionPromptCounter}`;
9730
+ const id = `perm-${generation}-${++permissionPromptCounter}`;
9248
9731
  const prompt = {
9249
9732
  id,
9250
9733
  toolName,
9251
9734
  args,
9252
9735
  preview,
9253
9736
  canBeTrusted,
9737
+ sessionScope: options?.sessionScope,
9254
9738
  kind,
9255
9739
  resolve
9256
9740
  };
@@ -9282,7 +9766,11 @@ function CliApp() {
9282
9766
  let userQuestionCounter = 0;
9283
9767
  const userQuestionFn = (payload) => {
9284
9768
  return new Promise((resolve) => {
9285
- const id = `uq-${++userQuestionCounter}`;
9769
+ if (sessionEnded()) {
9770
+ resolve({ answers: [] });
9771
+ return;
9772
+ }
9773
+ const id = `uq-${generation}-${++userQuestionCounter}`;
9286
9774
  enqueueUserQuestionPrompt({
9287
9775
  id,
9288
9776
  payload,
@@ -9297,6 +9785,13 @@ function CliApp() {
9297
9785
  };
9298
9786
  const reviewGateFn = (params) => {
9299
9787
  return new Promise((resolve) => {
9788
+ if (sessionEnded()) {
9789
+ resolve({
9790
+ decision: "rejected",
9791
+ note: "The session that asked for this review has ended."
9792
+ });
9793
+ return;
9794
+ }
9300
9795
  enqueueReviewGatePrompt({
9301
9796
  id: params.id,
9302
9797
  description: params.description,
@@ -9331,28 +9826,24 @@ function CliApp() {
9331
9826
  userQuestionFn,
9332
9827
  startupLog,
9333
9828
  silentLogger,
9334
- onBackgroundStatusChange: (job) => {
9335
- useCliStore.getState().upsertBackgroundAgent(job);
9336
- },
9337
- onGroupCompletion: (notification, groupDescription) => {
9338
- useCliStore.getState().addCompletedGroupNotification(notification, groupDescription);
9339
- useCliStore.getState().setPendingBackgroundTrigger(true);
9340
- },
9341
- onSubagentUsage: (usage) => {
9342
- useCliStore.getState().recordSubagentUsage({
9343
- agentName: usage.agentName,
9344
- tokens: usage.totalTokens,
9345
- credits: usage.totalCredits
9346
- });
9347
- }
9829
+ isCancelled: sessionEnded,
9830
+ ...sessionBackgroundCallbacks(() => !sessionEnded())
9348
9831
  });
9349
9832
  const agentDelegateTool = createAgentDelegateTool(orchestrator, agentStore, newSession.id, backgroundManager);
9350
9833
  const dynamicAgentTool = config.preferences.enableDynamicAgentCreation === true ? createDynamicAgentTool(orchestrator, newSession.id, backgroundManager) : null;
9351
9834
  const backgroundTools = createBackgroundAgentTools(backgroundManager);
9352
9835
  const resumeAgentTool = createResumeAgentTool(orchestrator, historyStore, backgroundManager);
9353
- const llmWithFallback = config.fallbackModels && config.fallbackModels.length > 0 ? new FallbackLlmBackend(llm, config.fallbackModels, (fromModel, toModel, error) => {
9836
+ const agentToolsRef = { current: null };
9837
+ const { llm: toolSearchLlm, toolSearchTool } = buildToolSearch({
9838
+ llm,
9839
+ models,
9840
+ registry: deferredToolRegistry,
9841
+ logger,
9842
+ agentToolsRef
9843
+ });
9844
+ const llmWithFallback = config.fallbackModels && config.fallbackModels.length > 0 ? new FallbackLlmBackend(toolSearchLlm, config.fallbackModels, (fromModel, toModel, error) => {
9354
9845
  logger.warn(`⚠️ Model "${fromModel}" failed (${error.message}) — falling back to "${toModel}"`);
9355
- }) : llm;
9846
+ }) : toolSearchLlm;
9356
9847
  const notifyingLlm = new NotifyingLlmBackend(llmWithFallback, backgroundManager);
9357
9848
  const todoStore = todoStoreRef.current;
9358
9849
  todoStore.todos = [];
@@ -9376,7 +9867,8 @@ function CliApp() {
9376
9867
  configStore: state.configStore,
9377
9868
  apiClient,
9378
9869
  sandboxOrchestrator: sandboxOrchestrator ?? void 0,
9379
- allowedDirectories: additionalDirectories
9870
+ allowedDirectories: additionalDirectories,
9871
+ isCancelled: sessionEnded
9380
9872
  };
9381
9873
  const enableSkillTool = config.preferences.enableSkillTool !== false;
9382
9874
  const skillTool = enableSkillTool ? createSkillTool({
@@ -9385,20 +9877,12 @@ function CliApp() {
9385
9877
  sessionId: newSession.id,
9386
9878
  permission: {
9387
9879
  permissionManager,
9388
- promptFn
9880
+ promptFn,
9881
+ isCancelled: sessionEnded
9389
9882
  },
9390
9883
  allowedDirectories: additionalDirectories
9391
9884
  }) : null;
9392
- const workItemTools = config.preferences.enableWorkItemTools ? createWorkItemTools(new WorkItemsClient(apiClient)) : [];
9393
- const agentToolsRef = { current: null };
9394
- const toolSearchTool = deferredToolRegistry.size() > 0 ? createToolSearchTool({
9395
- registry: deferredToolRegistry,
9396
- logger,
9397
- toolListAccessor: () => {
9398
- if (!agentToolsRef.current) throw new Error("tool_search invoked before agent context was wired");
9399
- return agentToolsRef.current;
9400
- }
9401
- }) : null;
9885
+ const workItemTools = config.preferences.enableWorkItemTools && !apiClient.signedOut ? createWorkItemTools(new WorkItemsClient(apiClient)) : [];
9402
9886
  const cliTools = buildCliToolList({
9403
9887
  toolSearchTool,
9404
9888
  agentDelegateTool,
@@ -9421,7 +9905,11 @@ function CliApp() {
9421
9905
  descriptors: pluginDescriptors,
9422
9906
  config,
9423
9907
  logger,
9424
- reservedToolNames: [...loadedB4mTools, ...cliTools].map((t) => t.toolSchema.name).concat("tool_search")
9908
+ reservedToolNames: [
9909
+ ...[...loadedB4mTools, ...cliTools].map((t) => t.toolSchema.name),
9910
+ ...deferredToolRegistry.getDirectoryNames(),
9911
+ "tool_search"
9912
+ ]
9425
9913
  });
9426
9914
  rewireReservedNames(state, featureRegistry);
9427
9915
  if (wsManager && featureRegistry.hasModules) featureRegistry.registerAllWsHandlers(wsManager);
@@ -9474,7 +9962,8 @@ function CliApp() {
9474
9962
  });
9475
9963
  wireAgentEvents({
9476
9964
  agent,
9477
- orchestrator
9965
+ orchestrator,
9966
+ isCurrent: () => !sessionEnded()
9478
9967
  });
9479
9968
  setState((prev) => ({
9480
9969
  ...prev,
@@ -9482,7 +9971,7 @@ function CliApp() {
9482
9971
  mcpManager,
9483
9972
  permissionManager,
9484
9973
  config,
9485
- availableModels: models,
9974
+ availableModels: liveModels.current ?? models,
9486
9975
  orchestrator,
9487
9976
  agentStore,
9488
9977
  contextContent: contextResult.mergedContent,
@@ -9492,7 +9981,8 @@ function CliApp() {
9492
9981
  checkpointStore,
9493
9982
  additionalDirectories,
9494
9983
  featureRegistry,
9495
- pluginDescriptors
9984
+ pluginDescriptors,
9985
+ signedOutLocal: apiClient.signedOut
9496
9986
  }));
9497
9987
  setStoreSession(newSession);
9498
9988
  renderBanner(startupLog);
@@ -9567,7 +10057,7 @@ function CliApp() {
9567
10057
  status: "running"
9568
10058
  });
9569
10059
  };
9570
- const tavernPresenceEnabled = state.config?.features?.tavern ?? false;
10060
+ const tavernPresenceEnabled = (state.config?.features?.tavern ?? false) && !state.signedOutLocal;
9571
10061
  useEffect(() => {
9572
10062
  if (!isInitialized) return;
9573
10063
  if (!tavernPresenceEnabled) {
@@ -9608,6 +10098,8 @@ function CliApp() {
9608
10098
  console.error("❌ CLI failed to initialize. Try restarting b4m.\n");
9609
10099
  return;
9610
10100
  }
10101
+ const generation = initGenerationRef.current;
10102
+ const replaced = () => initGenerationRef.current !== generation;
9611
10103
  useCliStore.getState().setIsThinking(true);
9612
10104
  const releaseSession = useCliStore.getState().holdSession();
9613
10105
  const abortController = new AbortController();
@@ -9619,7 +10111,7 @@ function CliApp() {
9619
10111
  const stepHandler = (step) => {
9620
10112
  currentSteps.push(step);
9621
10113
  const currentSession = useCliStore.getState().session;
9622
- if (currentSession) {
10114
+ if (currentSession && !replaced()) {
9623
10115
  const messages = [...currentSession.messages];
9624
10116
  const lastMessage = messages[messages.length - 1];
9625
10117
  if (lastMessage && lastMessage.role === "assistant") {
@@ -9659,6 +10151,7 @@ function CliApp() {
9659
10151
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9660
10152
  metadata: { steps: [] }
9661
10153
  };
10154
+ if (replaced()) return;
9662
10155
  const sessionWithMessages = {
9663
10156
  ...session,
9664
10157
  messages: [
@@ -9693,7 +10186,7 @@ function CliApp() {
9693
10186
  if (permissionDenied) console.log("\n⚠️ Action denied by user\n");
9694
10187
  const successfulToolCalls = result.steps.filter((s) => s.type === "observation").length;
9695
10188
  const currentSession = useCliStore.getState().session;
9696
- if (!currentSession) return;
10189
+ if (!currentSession || replaced()) return;
9697
10190
  const updatedMessages = [...currentSession.messages];
9698
10191
  const lastMessage = updatedMessages[updatedMessages.length - 1];
9699
10192
  const richContent = reconstructTurnBlocks(result.steps, result.finalAnswer);
@@ -9736,11 +10229,11 @@ function CliApp() {
9736
10229
  usageCache = null;
9737
10230
  useCliStore.getState().setIsThinking(false);
9738
10231
  } catch (error) {
9739
- useCliStore.getState().setIsThinking(false);
10232
+ if (!replaced()) useCliStore.getState().setIsThinking(false);
9740
10233
  if (error instanceof Error && error.name === "AbortError") {
9741
10234
  logger.debug("[ABORT] Custom command aborted by user");
9742
10235
  const currentSession = useCliStore.getState().session;
9743
- if (currentSession) {
10236
+ if (currentSession && !replaced()) {
9744
10237
  const messages = [...currentSession.messages];
9745
10238
  const lastMessage = messages[messages.length - 1];
9746
10239
  if (lastMessage && lastMessage.role === "assistant") messages[messages.length - 1] = {
@@ -9764,7 +10257,7 @@ function CliApp() {
9764
10257
  if (error?.message?.includes("Permission denied")) {
9765
10258
  console.log("\n⚠️ Action blocked by permission settings");
9766
10259
  const currentSession = useCliStore.getState().session;
9767
- if (!currentSession) return;
10260
+ if (!currentSession || replaced()) return;
9768
10261
  const sessionWithDenied = { ...currentSession };
9769
10262
  const messages = [...sessionWithDenied.messages];
9770
10263
  const lastMessage = messages[messages.length - 1];
@@ -9784,7 +10277,7 @@ function CliApp() {
9784
10277
  console.error("Error executing command:", error);
9785
10278
  console.error(error.stack);
9786
10279
  const currentSession = useCliStore.getState().session;
9787
- if (!currentSession) return;
10280
+ if (!currentSession || replaced()) return;
9788
10281
  const sessionWithError = { ...currentSession };
9789
10282
  const messages = [...sessionWithError.messages];
9790
10283
  const lastMessage = messages[messages.length - 1];
@@ -9795,10 +10288,10 @@ function CliApp() {
9795
10288
  sessionWithError.messages = messages;
9796
10289
  setStoreSession(sessionWithError);
9797
10290
  } finally {
9798
- setState((prev) => ({
10291
+ setState((prev) => prev.abortController === abortController ? {
9799
10292
  ...prev,
9800
10293
  abortController: null
9801
- }));
10294
+ } : prev);
9802
10295
  state.agent.off("thought", stepHandler);
9803
10296
  state.agent.off("action", stepHandler);
9804
10297
  releaseSession();
@@ -9808,7 +10301,6 @@ function CliApp() {
9808
10301
  agent: state.agent,
9809
10302
  sessionStore: state.sessionStore,
9810
10303
  configStore: state.configStore,
9811
- commandHistoryStore: state.commandHistoryStore,
9812
10304
  customCommandStore: state.customCommandStore,
9813
10305
  messageBuilder: state.messageBuilder,
9814
10306
  config: state.config,
@@ -9828,11 +10320,11 @@ function CliApp() {
9828
10320
  blockerStore: blockerStoreRef.current,
9829
10321
  reviewGateStore: reviewGateStoreRef.current
9830
10322
  },
9831
- setCommandHistory,
9832
10323
  setAbortController: (controller) => setState((prev) => ({
9833
10324
  ...prev,
9834
10325
  abortController: controller
9835
- }))
10326
+ })),
10327
+ sessionGeneration: () => initGenerationRef.current
9836
10328
  });
9837
10329
  handleMessageRef.current = handleMessage;
9838
10330
  const buildLifecycleContext = () => ({
@@ -9855,10 +10347,14 @@ function CliApp() {
9855
10347
  * without adding a user message to the conversation.
9856
10348
  */
9857
10349
  const handleBackgroundCompletion = async () => {
9858
- const authTokens = await state.configStore.getAuthTokens();
9859
- if (!authTokens || new Date(authTokens.expiresAt) <= /* @__PURE__ */ new Date()) return;
10350
+ if (!state.signedOutLocal) {
10351
+ const authTokens = await state.configStore.getAuthTokens();
10352
+ if (!authTokens || new Date(authTokens.expiresAt) <= /* @__PURE__ */ new Date()) return;
10353
+ }
9860
10354
  const session = useCliStore.getState().session;
9861
10355
  if (!state.agent || !session) return;
10356
+ const startedGeneration = initGenerationRef.current;
10357
+ const stillThisSession = () => initGenerationRef.current === startedGeneration && useCliStore.getState().session?.id === session.id;
9862
10358
  useCliStore.getState().setIsThinking(true);
9863
10359
  const releaseSession = useCliStore.getState().holdSession();
9864
10360
  const abortController = new AbortController();
@@ -9866,9 +10362,10 @@ function CliApp() {
9866
10362
  ...prev,
9867
10363
  abortController
9868
10364
  }));
10365
+ const pendingId = v4();
9869
10366
  try {
9870
10367
  const pendingAssistantMessage = {
9871
- id: v4(),
10368
+ id: pendingId,
9872
10369
  role: "assistant",
9873
10370
  content: "...",
9874
10371
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -9890,7 +10387,7 @@ function CliApp() {
9890
10387
  });
9891
10388
  const successfulToolCalls = result.steps.filter((s) => s.type === "observation").length;
9892
10389
  const currentSession = useCliStore.getState().session;
9893
- if (!currentSession) return;
10390
+ if (!currentSession || !stillThisSession()) return;
9894
10391
  const richContent = reconstructTurnBlocks(result.steps, result.finalAnswer);
9895
10392
  const continuationMessage = {
9896
10393
  id: v4(),
@@ -9924,15 +10421,17 @@ function CliApp() {
9924
10421
  setStoreSession(updatedSession);
9925
10422
  await state.sessionStore.save(updatedSession);
9926
10423
  } catch (error) {
10424
+ if (!stillThisSession()) return;
9927
10425
  useCliStore.getState().clearPendingMessages();
9928
10426
  if (error instanceof Error && error.name === "AbortError") return;
9929
10427
  console.error("Error processing background results:", error);
9930
10428
  } finally {
9931
- setState((prev) => ({
10429
+ if (stillThisSession() || abortControllerRef.current === abortController) useCliStore.getState().setIsThinking(false);
10430
+ setState((prev) => prev.abortController === abortController ? {
9932
10431
  ...prev,
9933
10432
  abortController: null
9934
- }));
9935
- useCliStore.getState().setIsThinking(false);
10433
+ } : prev);
10434
+ if (!stillThisSession()) useCliStore.setState((prev) => ({ pendingMessages: prev.pendingMessages.filter((m) => m.id !== pendingId) }));
9936
10435
  releaseSession();
9937
10436
  }
9938
10437
  };
@@ -10033,8 +10532,9 @@ function CliApp() {
10033
10532
  const nameWidth = 25;
10034
10533
  const maxDescLength = Math.max(20, terminalWidth - 30);
10035
10534
  agents.forEach((agent) => {
10036
- const desc = agent.description.length > maxDescLength ? agent.description.slice(0, maxDescLength - 3) + "..." : agent.description;
10037
- console.log(` ${agent.name.padEnd(nameWidth)} - ${desc}`);
10535
+ const description = sanitizeTerminalText(agent.description);
10536
+ const desc = description.length > maxDescLength ? description.slice(0, maxDescLength - 3) + "..." : description;
10537
+ console.log(` ${sanitizeTerminalText(agent.name).padEnd(nameWidth)} - ${desc}`);
10038
10538
  });
10039
10539
  console.log("");
10040
10540
  }
@@ -10281,7 +10781,7 @@ function CliApp() {
10281
10781
  if (result.filePath) console.log(`\n📄 Handoff written to ${result.filePath}`);
10282
10782
  console.log(fellBack ? "✅ Session saved with local fallback handoff" : "✅ Session saved with refreshed handoff");
10283
10783
  };
10284
- const handleCommand = async (command, args) => {
10784
+ const runCommand = async (command, args) => {
10285
10785
  const customCommand = state.customCommandStore.getModelReachableCommand(command);
10286
10786
  if (customCommand) try {
10287
10787
  const sourceIcon = customCommand.source === "global" ? "🏠" : "📁";
@@ -10289,18 +10789,18 @@ function CliApp() {
10289
10789
  let substitutedBody = substituteArguments(customCommand.body, args);
10290
10790
  const processed = await processFileReferences(substitutedBody);
10291
10791
  substitutedBody = processed.content;
10292
- if (processed.errors.length > 0) processed.errors.forEach((error) => console.warn(`Warning: ${error}`));
10293
- if (process.env.B4M_VERBOSE === "1") console.log("📝 Expanded command:\n", substitutedBody);
10792
+ if (processed.errors.length > 0) processed.errors.forEach((error) => console.warn(`Warning: ${sanitizeTerminalText(String(error))}`));
10793
+ if (process.env.B4M_VERBOSE === "1") console.log("📝 Expanded command:\n", sanitizeTerminalText(substitutedBody));
10294
10794
  const displayMessage = `/${command}${args.length > 0 ? " " + args.join(" ") : ""}`;
10295
10795
  if (customCommand.agent && state.orchestrator && state.agentStore) {
10296
10796
  const { name: agentName } = parseAgentConfig(customCommand.agent);
10297
10797
  if (!state.agentStore.hasAgent(agentName)) {
10298
10798
  const available = state.agentStore.getAgentNames().join(", ");
10299
- console.error(`❌ Unknown agent "${agentName}" specified in command.`);
10300
- console.error(` Available agents: ${available}`);
10799
+ console.error(`❌ Unknown agent "${sanitizeTerminalText(agentName)}" specified in command.`);
10800
+ console.error(` Available agents: ${sanitizeTerminalText(available)}`);
10301
10801
  return;
10302
10802
  }
10303
- console.log(`🤖 Delegating to ${agentName} agent...\n`);
10803
+ console.log(`🤖 Delegating to ${sanitizeTerminalText(agentName)} agent...\n`);
10304
10804
  const result = await state.orchestrator.delegateToAgent({
10305
10805
  task: substitutedBody,
10306
10806
  agentName,
@@ -10308,11 +10808,11 @@ function CliApp() {
10308
10808
  variables: customCommand.variables,
10309
10809
  parentSessionId: useCliStore.getState().session?.id || "unknown"
10310
10810
  });
10311
- console.log("\n" + result.summary + "\n");
10811
+ console.log("\n" + sanitizeTerminalText(result.summary) + "\n");
10312
10812
  return;
10313
10813
  }
10314
10814
  if (customCommand.model && state.agent) {
10315
- console.log(`🔄 Using model override: ${customCommand.model}`);
10815
+ console.log(`🔄 Using model override: ${sanitizeTerminalText(customCommand.model)}`);
10316
10816
  await runWithModelOverride({
10317
10817
  applyModel: applyModelToSession,
10318
10818
  sessionStore: state.sessionStore
@@ -10335,6 +10835,11 @@ function CliApp() {
10335
10835
  reviewGateStore: reviewGateStoreRef.current,
10336
10836
  openConfigEditor: () => setShowConfigEditor(true)
10337
10837
  })) return;
10838
+ const signedOutRefusal = state.signedOutLocal ? signedOutCommandMessage(command) : null;
10839
+ if (signedOutRefusal) {
10840
+ console.log(`\n${signedOutRefusal}\n`);
10841
+ return;
10842
+ }
10338
10843
  switch (command) {
10339
10844
  case "exit":
10340
10845
  case "quit":
@@ -10417,8 +10922,7 @@ function CliApp() {
10417
10922
  return;
10418
10923
  }
10419
10924
  const { url } = result;
10420
- await state.configStore.setCustomApiUrl(url);
10421
- await state.configStore.clearAuthTokens();
10925
+ await state.configStore.withRefreshLock(() => state.configStore.setCustomApiUrlSignedOut(url));
10422
10926
  console.log(`\n✅ API URL updated: ${url}`);
10423
10927
  console.log("🔓 Authentication cleared");
10424
10928
  console.log(`💡 Run /login to authenticate with ${url}`);
@@ -10426,8 +10930,7 @@ function CliApp() {
10426
10930
  break;
10427
10931
  }
10428
10932
  case "reset-api": {
10429
- await state.configStore.setCustomApiUrl(null);
10430
- await state.configStore.clearAuthTokens();
10933
+ await state.configStore.withRefreshLock(() => state.configStore.setCustomApiUrlSignedOut(null));
10431
10934
  const resetEndpoint = resolveApiEndpoint();
10432
10935
  console.log("\n✅ Custom API URL cleared");
10433
10936
  console.log("🔓 Authentication cleared");
@@ -10576,29 +11079,37 @@ function CliApp() {
10576
11079
  console.log(`✅ Tool '${toolToUntrust}' removed from trusted list`);
10577
11080
  break;
10578
11081
  }
10579
- case "login":
11082
+ case "login": {
11083
+ const busy = useCliStore.getState();
11084
+ if (loginBlocked({
11085
+ ...busy,
11086
+ abortController: abortControllerRef.current
11087
+ })) {
11088
+ console.log(SIGN_IN_DURING_TURN);
11089
+ break;
11090
+ }
11091
+ const loginConfig = await state.configStore.get();
11092
+ const start = signInStart({
11093
+ endpoint: resolveApiEndpoint(loginConfig.apiConfig),
11094
+ endpointChosen: !!loginConfig.apiConfig?.endpointChosen,
11095
+ hasAuthTokens: !!await state.configStore.getAuthTokens()
11096
+ });
10580
11097
  setState((prev) => ({
10581
11098
  ...prev,
10582
- showLoginFlow: true
11099
+ config: loginConfig,
11100
+ ...start === "endpoint-picker" ? { showEnvironmentPicker: true } : { showLoginFlow: true }
10583
11101
  }));
10584
11102
  break;
11103
+ }
10585
11104
  case "logout":
10586
11105
  usageCache = null;
10587
- await state.configStore.clearAuthTokens();
11106
+ await state.configStore.withRefreshLock(() => state.configStore.clearAuthTokens());
10588
11107
  console.log("✅ Successfully logged out");
11108
+ if (!state.signedOutLocal) console.log(LOGGED_OUT_RESTART);
10589
11109
  break;
10590
11110
  case "whoami": {
10591
11111
  const authTokens = await state.configStore.getAuthTokens();
10592
- if (!authTokens) {
10593
- console.log("Not authenticated. Run /login to authenticate.");
10594
- return;
10595
- }
10596
- const isExpired = new Date(authTokens.expiresAt) <= /* @__PURE__ */ new Date();
10597
- console.log("\n👤 Current User:\n");
10598
- console.log(`User ID: ${authTokens.userId}`);
10599
- console.log(`Status: ${isExpired ? "⚠️ Token expired" : "✅ Authenticated"}`);
10600
- console.log(`Expires: ${new Date(authTokens.expiresAt).toLocaleString()}`);
10601
- console.log("");
11112
+ console.log(whoamiReport(authTokens, { signedOutLocal: state.signedOutLocal }));
10602
11113
  break;
10603
11114
  }
10604
11115
  case "clear":
@@ -10771,8 +11282,8 @@ function CliApp() {
10771
11282
  else if (error.response?.status === 403) console.log("\n❌ Access denied. You may not have permission to view usage data.\n");
10772
11283
  else if (error.response?.status === 404) console.log("\n❌ Usage endpoint not available on this server.\n");
10773
11284
  else if (error.code === "ECONNREFUSED" || error.code === "ENOTFOUND") console.log("\n❌ Cannot connect to server. Check your API configuration with /api-info\n");
10774
- else console.log(`\n❌ Error fetching usage data: ${error.message}\n`);
10775
- } else if (error instanceof Error) console.log(`\n❌ Error: ${error.message}\n`);
11285
+ else console.log(`\n\u274C Error fetching usage data: ${sanitizeTerminalText(error.message)}\n`);
11286
+ } else if (error instanceof Error) console.log(`\n\u274C Error: ${sanitizeTerminalText(error.message)}\n`);
10776
11287
  else console.log("\n❌ Unexpected error fetching usage data. Please try again.\n");
10777
11288
  break;
10778
11289
  }
@@ -10873,7 +11384,7 @@ function CliApp() {
10873
11384
  if (mcpTools.length > 0) {
10874
11385
  console.log("\nMCP Tools (deferred):");
10875
11386
  console.log(` Schemas: load on demand via tool_search (${mcpTools.length} tools available)`);
10876
- for (const { serverName, count } of mcpToolCount) console.log(` ${serverName}: ${count} tools`);
11387
+ for (const { serverName, count } of mcpToolCount) console.log(` ${sanitizeTerminalText(serverName)}: ${count} tools`);
10877
11388
  }
10878
11389
  if (agentTools.length > 0) {
10879
11390
  console.log("\nLoaded Tool Schemas:");
@@ -10903,15 +11414,15 @@ function CliApp() {
10903
11414
  const localConfig = await state.configStore.loadRawProjectLocalConfig();
10904
11415
  if (projectConfig) {
10905
11416
  console.log("Team Config (.bike4mind/config.json):");
10906
- if (projectConfig.defaultModel) console.log(` Default Model: ${projectConfig.defaultModel}`);
10907
- if (projectConfig.tools?.denied && projectConfig.tools.denied.length > 0) console.log(` Denied Tools: ${projectConfig.tools.denied.join(", ")}`);
10908
- if (projectConfig.mcpServers && projectConfig.mcpServers.length > 0) console.log(` MCP Servers: ${projectConfig.mcpServers.map((s) => s.name).join(", ")}`);
11417
+ if (projectConfig.defaultModel) console.log(` Default Model: ${sanitizeTerminalText(projectConfig.defaultModel)}`);
11418
+ if (projectConfig.tools?.denied && projectConfig.tools.denied.length > 0) console.log(` Denied Tools: ${sanitizeTerminalText(projectConfig.tools.denied.join(", "))}`);
11419
+ if (projectConfig.mcpServers && projectConfig.mcpServers.length > 0) console.log(` MCP Servers: ${sanitizeTerminalText(projectConfig.mcpServers.map((s) => s.name).join(", "))}`);
10909
11420
  console.log("");
10910
11421
  }
10911
11422
  if (localConfig) {
10912
11423
  console.log("Local Config (.bike4mind/local.json):");
10913
- if (localConfig.trustedTools && localConfig.trustedTools.length > 0) console.log(` Trusted Tools: ${localConfig.trustedTools.join(", ")}`);
10914
- if (localConfig.mcpServers && localConfig.mcpServers.length > 0) console.log(` MCP Servers: ${localConfig.mcpServers.map((s) => s.name).join(", ")}`);
11424
+ if (localConfig.trustedTools && localConfig.trustedTools.length > 0) console.log(` Trusted Tools: ${sanitizeTerminalText(localConfig.trustedTools.join(", "))}`);
11425
+ if (localConfig.mcpServers && localConfig.mcpServers.length > 0) console.log(` MCP Servers: ${sanitizeTerminalText(localConfig.mcpServers.map((s) => s.name).join(", "))}`);
10915
11426
  console.log("");
10916
11427
  }
10917
11428
  console.log("Merged Configuration (what you're using):");
@@ -10948,9 +11459,9 @@ function CliApp() {
10948
11459
  if (globalCommands.length > 0) {
10949
11460
  console.log("🏠 Global Commands (~/.bike4mind/commands/):");
10950
11461
  globalCommands.forEach((cmd) => {
10951
- const argHint = cmd.argumentHint ? ` ${cmd.argumentHint}` : "";
10952
- const prefix = ` /${cmd.name}${argHint}`;
10953
- const desc = truncateDescription(cmd.description, prefix.length);
11462
+ const argHint = cmd.argumentHint ? ` ${sanitizeTerminalText(cmd.argumentHint)}` : "";
11463
+ const prefix = ` /${sanitizeTerminalText(cmd.name)}${argHint}`;
11464
+ const desc = truncateDescription(sanitizeTerminalText(cmd.description), prefix.length);
10954
11465
  console.log(`${prefix} - ${desc}`);
10955
11466
  });
10956
11467
  console.log("");
@@ -10958,9 +11469,9 @@ function CliApp() {
10958
11469
  if (projectCommands.length > 0) {
10959
11470
  console.log("📁 Project Commands (.bike4mind/commands/):");
10960
11471
  projectCommands.forEach((cmd) => {
10961
- const argHint = cmd.argumentHint ? ` ${cmd.argumentHint}` : "";
10962
- const prefix = ` /${cmd.name}${argHint}`;
10963
- const desc = truncateDescription(cmd.description, prefix.length);
11472
+ const argHint = cmd.argumentHint ? ` ${sanitizeTerminalText(cmd.argumentHint)}` : "";
11473
+ const prefix = ` /${sanitizeTerminalText(cmd.name)}${argHint}`;
11474
+ const desc = truncateDescription(sanitizeTerminalText(cmd.description), prefix.length);
10964
11475
  console.log(`${prefix} - ${desc}`);
10965
11476
  });
10966
11477
  console.log("");
@@ -11277,9 +11788,9 @@ function CliApp() {
11277
11788
  const time = new Date(v.timestamp).toLocaleTimeString();
11278
11789
  const typeColor = v.type === "filesystem" ? "\x1B[33m" : "\x1B[36m";
11279
11790
  const typeLabel = v.type === "filesystem" ? "FS " : "NET";
11280
- const target = v.path ?? v.domain ?? "";
11281
- console.log(` ${typeColor}${typeLabel}\x1b[0m ${time} \x1b[90m${v.blockedBy}\x1b[0m ${target}`);
11282
- if (v.detail) console.log(` \x1b[90m${v.detail.slice(0, 120)}\x1b[0m`);
11791
+ const target = sanitizeTerminalText(v.path ?? v.domain ?? "");
11792
+ console.log(` ${typeColor}${typeLabel}\x1b[0m ${time} \x1b[90m${sanitizeTerminalText(v.blockedBy)}\x1b[0m ${target}`);
11793
+ if (v.detail) console.log(` \x1b[90m${sanitizeTerminalText(v.detail).slice(0, 120)}\x1b[0m`);
11283
11794
  }
11284
11795
  console.log("");
11285
11796
  break;
@@ -11313,7 +11824,7 @@ function CliApp() {
11313
11824
  }));
11314
11825
  break;
11315
11826
  case "no-match":
11316
- console.log(`No model matches "${result.query}". Run /model to browse available models.`);
11827
+ console.log(state.signedOutLocal ? signedOutNoMatchMessage(result.query) : `No model matches "${result.query}". Run /model to browse available models.`);
11317
11828
  break;
11318
11829
  case "ambiguous":
11319
11830
  console.log(`"${args.join(" ")}" matches ${result.models.length} models - be more specific:`);
@@ -11332,6 +11843,7 @@ function CliApp() {
11332
11843
  console.log("Type /help for available commands");
11333
11844
  }
11334
11845
  };
11846
+ const handleCommand = reportCommandErrors(runCommand, (message) => console.error(message));
11335
11847
  /**
11336
11848
  * Handle saving config from the interactive editor
11337
11849
  */
@@ -11343,7 +11855,7 @@ function CliApp() {
11343
11855
  let newFeatureRegistry = state.featureRegistry;
11344
11856
  if (featuresChanged && state.agent) {
11345
11857
  state.featureRegistry?.disposeAll();
11346
- const apiClient = new ApiClient(requireApiUrl(updatedConfig.apiConfig), state.configStore);
11858
+ const apiClient = state.signedOutLocal ? ApiClient.whileSignedOut(state.configStore) : new ApiClient(requireApiUrl(updatedConfig.apiConfig), state.configStore);
11347
11859
  const oldFeatureToolNames = new Set(state.featureRegistry?.getAllToolNames() ?? []);
11348
11860
  const baseTools = state.agent.getTools().filter((t) => !oldFeatureToolNames.has(t.toolSchema.name));
11349
11861
  const rebuilt = await buildFeatureRegistry({
@@ -11351,12 +11863,16 @@ function CliApp() {
11351
11863
  descriptors: state.pluginDescriptors,
11352
11864
  config: updatedConfig,
11353
11865
  logger,
11354
- reservedToolNames: baseTools.map((t) => t.toolSchema.name)
11866
+ reservedToolNames: [
11867
+ ...baseTools.map((t) => t.toolSchema.name),
11868
+ ...deferredToolRegistry.getDirectoryNames(),
11869
+ "tool_search"
11870
+ ]
11355
11871
  });
11356
11872
  const rebuiltRegistry = rebuilt.registry;
11357
11873
  newFeatureRegistry = rebuiltRegistry;
11358
11874
  rewireReservedNames(state, rebuiltRegistry);
11359
- for (const skippedPlugin of rebuilt.skipped) console.error(`\n\x1b[33m⚠️ Plugin ${skippedPlugin.name} skipped: ${skippedPlugin.reason}\x1b[0m`);
11875
+ for (const skippedPlugin of rebuilt.skipped) console.error(`\n\x1b[33m\u26A0\uFE0F Plugin ${sanitizeTerminalText(skippedPlugin.name)} skipped: ${sanitizeTerminalText(skippedPlugin.reason)}\x1b[0m`);
11360
11876
  if (state.wsManager && newFeatureRegistry.hasModules) newFeatureRegistry.registerAllWsHandlers(state.wsManager);
11361
11877
  const newFeatureTools = newFeatureRegistry.getAllTools();
11362
11878
  state.agent.setTools([...baseTools, ...newFeatureTools]);
@@ -11424,12 +11940,16 @@ function CliApp() {
11424
11940
  isBusy: () => useCliStore.getState().isThinking,
11425
11941
  saveModel: async (modelId) => {
11426
11942
  if (!state.config) throw new Error("no CLI config is loaded");
11427
- await state.configStore.save({ defaultModel: modelId });
11943
+ const patch = modelSavePatch({
11944
+ ...model,
11945
+ id: modelId
11946
+ }, state.config, detectedOllamaRef.current);
11947
+ await state.configStore.save(patch);
11428
11948
  setState((prev) => prev.config ? {
11429
11949
  ...prev,
11430
11950
  config: {
11431
11951
  ...prev.config,
11432
- defaultModel: modelId
11952
+ ...patch
11433
11953
  }
11434
11954
  } : prev);
11435
11955
  },
@@ -11465,6 +11985,8 @@ function CliApp() {
11465
11985
  await state.configStore.trustProject();
11466
11986
  console.log("\n✅ Folder trusted. Loading its config, agents, skills and MCP servers.\n");
11467
11987
  } else console.log("\nℹ️ Project config stays inert this session. Use /trust folder to trust it later.\n");
11988
+ } catch (error) {
11989
+ console.error(`Could not trust this folder: ${error instanceof Error ? error.message : String(error)}. Use /trust folder to try again.`);
11468
11990
  } finally {
11469
11991
  setState((prev) => ({
11470
11992
  ...prev,
@@ -11549,29 +12071,47 @@ function CliApp() {
11549
12071
  }))
11550
12072
  });
11551
12073
  }
11552
- if (state.showEnvironmentPicker) return /* @__PURE__ */ React.createElement(EnvironmentPicker, { onSelect: (choice) => {
11553
- (async () => {
11554
- try {
11555
- const result = await state.configStore.switchApiEnvironment(choice.target);
11556
- setState((prev) => ({
11557
- ...prev,
11558
- showEnvironmentPicker: false
11559
- }));
11560
- console.log(`\n✅ Connecting to ${result.envName} (${result.url})\n`);
11561
- init().catch((err) => {
11562
- console.error("\n❌ Initialization failed:", err.message, "\n");
11563
- exit();
11564
- });
11565
- } catch (err) {
12074
+ const localSessionRunning = isInitialized && state.signedOutLocal;
12075
+ const backToLocalSession = localSessionRunning ? () => {
12076
+ setState((prev) => ({
12077
+ ...prev,
12078
+ showLoginFlow: false,
12079
+ showEnvironmentPicker: false
12080
+ }));
12081
+ console.log(`\n${LOCAL_SESSION_CONTINUES}\n`);
12082
+ } : void 0;
12083
+ if (state.showEnvironmentPicker) return /* @__PURE__ */ React.createElement(EnvironmentPicker, {
12084
+ onSelect: (choice) => {
12085
+ (async () => {
11566
12086
  setState((prev) => ({
11567
12087
  ...prev,
11568
12088
  showEnvironmentPicker: false
11569
12089
  }));
11570
- console.error(`\n❌ Failed to save endpoint: ${err instanceof Error ? err.message : String(err)}\n`);
11571
- exit();
11572
- }
11573
- })();
11574
- } });
12090
+ try {
12091
+ const result = await state.configStore.switchApiEnvironment(choice.target);
12092
+ console.log(`\n✅ Connecting to ${result.envName} (${result.url})\n`);
12093
+ if (localSessionRunning) {
12094
+ const config = await state.configStore.get();
12095
+ setState((prev) => ({
12096
+ ...prev,
12097
+ config,
12098
+ showLoginFlow: true
12099
+ }));
12100
+ return;
12101
+ }
12102
+ init().catch((err) => {
12103
+ console.error("\n❌ Initialization failed:", err.message, "\n");
12104
+ exit();
12105
+ });
12106
+ } catch (err) {
12107
+ console.error(`\n❌ Failed to save endpoint: ${err instanceof Error ? err.message : String(err)}\n`);
12108
+ if (localSessionRunning) console.log(`${LOCAL_SESSION_CONTINUES}\n`);
12109
+ else exit();
12110
+ }
12111
+ })();
12112
+ },
12113
+ onCancel: backToLocalSession
12114
+ });
11575
12115
  if (state.showLoginFlow) {
11576
12116
  const endpoint = resolveApiEndpoint(state.config?.apiConfig);
11577
12117
  if (endpoint.status === "unconfigured") return /* @__PURE__ */ React.createElement(Box, {
@@ -11586,8 +12126,21 @@ function CliApp() {
11586
12126
  ...prev,
11587
12127
  showLoginFlow: false
11588
12128
  }));
11589
- console.log("\n✅ Login successful! Initializing CLI...\n");
11590
- init().catch((err) => {
12129
+ setIsInitialized(false);
12130
+ restartAfterSignIn({
12131
+ release: async () => {
12132
+ initGenerationRef.current++;
12133
+ const jobIds = state.backgroundManager?.listJobs().map((job) => job.id) ?? [];
12134
+ const runIds = Object.keys(useCliStore.getState().liveSubagentUsage);
12135
+ settlePendingPrompts();
12136
+ const released = await releaseSession(sessionResources("sign_in"), SESSION_RELEASE_TIMEOUT_MS);
12137
+ forgetBackgroundCompletions();
12138
+ forgetReleasedAgents(jobIds, runIds);
12139
+ return released;
12140
+ },
12141
+ restart: init,
12142
+ print: (line) => console.log(`\n${line}\n`)
12143
+ }).catch((err) => {
11591
12144
  console.error("\n❌ Initialization failed:", err.message, "\n");
11592
12145
  exit();
11593
12146
  });
@@ -11598,9 +12151,14 @@ function CliApp() {
11598
12151
  showLoginFlow: false
11599
12152
  }));
11600
12153
  console.error(`\n❌ Login failed: ${error.message}`);
12154
+ if (localSessionRunning) {
12155
+ console.log(`${LOCAL_SESSION_CONTINUES}\n`);
12156
+ return;
12157
+ }
11601
12158
  console.log("Run b4m again when you're ready to authenticate.\n");
11602
12159
  exit();
11603
- }
12160
+ },
12161
+ onCancel: backToLocalSession
11604
12162
  });
11605
12163
  }
11606
12164
  if (!isInitialized) return /* @__PURE__ */ React.createElement(Box, {
@@ -11619,6 +12177,7 @@ function CliApp() {
11619
12177
  onBashCommand: handleBashCommand,
11620
12178
  onImageDetected: handleImageDetected,
11621
12179
  commandHistory,
12180
+ onHistoryEntry: (entry) => setCommandHistory(state.commandHistoryStore.add(entry)),
11622
12181
  commands: allCommands,
11623
12182
  config: state.config,
11624
12183
  availableModels: state.availableModels,