@bike4mind/cli 4.0.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 (51) hide show
  1. package/README.md +86 -4
  2. package/bin/bike4mind-cli.mjs +249 -40
  3. package/bin/envFlags.d.mts +17 -0
  4. package/bin/envFlags.mjs +89 -0
  5. package/dist/{AgentHistoryStore-DgqmcVLN.mjs → AgentHistoryStore--J3sgO_-.mjs} +3794 -1368
  6. package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-CdO4Gamg.mjs} +22 -3
  7. package/dist/BubblewrapRuntime-3jAbC60G.mjs +157 -0
  8. package/dist/ConfigStore-CausUCzY.mjs +2 -0
  9. package/dist/ConfigStore-Dusy6glb.mjs +3364 -0
  10. package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-C1Wj6xla.mjs} +32672 -21643
  11. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  12. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-CQwYq_uy.mjs} +26 -7
  13. package/dist/SandboxRuntimeAdapter-BsT2iLky.mjs +190 -0
  14. package/dist/SandboxRuntimeAdapter-Zg_0th7V.mjs +2 -0
  15. package/dist/SeatbeltRuntime-C2DEkrjy.mjs +194 -0
  16. package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-CxNZaOmc.mjs} +1 -1
  17. package/dist/agents/defaults/review.md +8 -1
  18. package/dist/agents/defaults/test.md +8 -1
  19. package/dist/buildToolSearch-DOb7mx6F.mjs +417 -0
  20. package/dist/commands/acpCommand.mjs +25 -19
  21. package/dist/commands/apiCommand.mjs +3 -5
  22. package/dist/commands/doctorCommand.mjs +2 -2
  23. package/dist/commands/envCommand.mjs +1 -1
  24. package/dist/commands/headlessCommand.mjs +117 -36
  25. package/dist/commands/hostCommand.mjs +2344 -0
  26. package/dist/commands/mcpCommand.mjs +45 -30
  27. package/dist/commands/mirrorCommand.mjs +279 -0
  28. package/dist/commands/modelsCommand.mjs +1117 -0
  29. package/dist/commands/pluginCommand.mjs +9 -9
  30. package/dist/commands/skillsCommand.mjs +174 -29
  31. package/dist/commands/updateCommand.mjs +2 -2
  32. package/dist/curated-build.json +1 -0
  33. package/dist/dist-CbViwiS9.mjs +4739 -0
  34. package/dist/dist-Citbv0y0.mjs +7864 -0
  35. package/dist/fit-CVWDiavv.mjs +200 -0
  36. package/dist/index.mjs +853 -417
  37. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  38. package/dist/modelServers-BaegigV-.mjs +2465 -0
  39. package/dist/{package-CQaam4Dq.mjs → package-C9pfAdGF.mjs} +1 -1
  40. package/dist/{serve-CFxUhjml.mjs → serve-8wyGb8of.mjs} +595 -26
  41. package/dist/types-BFIvwByC.mjs +2 -0
  42. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  43. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-BAKb8KWP.mjs} +7 -29
  44. package/package.json +16 -13
  45. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  46. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  47. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  48. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  49. package/dist/buildToolSearch-D9GEK91u.mjs +0 -2351
  50. package/dist/dist-Ul2qwn5x.mjs +0 -624
  51. package/dist/types-I45lMh7Q.mjs +0 -2
package/dist/index.mjs CHANGED
@@ -1,23 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import { $ as processFileReferences, A as createAgentDelegateTool, B as DEFAULT_THOROUGHNESS, C as createTodoStore, D as createCoordinateTaskTool, E as parseAgentConfig, H as buildSkillsPromptSection, I as ALWAYS_DENIED_FOR_AGENTS, J as getProcessHooks, K as findIterationBoundary, L as DEFAULT_AGENT_MODEL, M as substituteArguments, N as PermissionManager, O as createResumeAgentTool, P as buildCliToolList, Q as CustomCommandStore, R as DEFAULT_MAX_ITERATIONS, S as createFindDefinitionTool, T as createSkillTool, V as buildSystemPrompt, Y as setWebSocketToolExecutor, Z as getPlanModeFilePath, _ as createDecisionLogTool, at as searchFiles, b as createGetFileStructureTool, ct as COMPACTION_SUMMARY_MARKER, d as createReviewGateStore, et as hasFileReferences, f as createReviewGateTool, g as formatBlockersOutput, h as createBlockerTools, it as formatFileSize, j as FallbackLlmBackend, k as createBackgroundAgentTools, m as createBlockerStore, nt as SessionStore, ot as warmFileCache, p as formatReviewGatesOutput, rt as searchCommands, s as buildSandbox, tt as CheckpointStore, u as isConnectionDrop, ut as MAX_PASTE_SIZE, v as createDecisionStore, w as createWriteTodosTool, x as createWorkItemTools, y as formatDecisionsOutput, z as DEFAULT_RETRY_CONFIG } from "./AgentHistoryStore-DgqmcVLN.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
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 { $t as selfClaimedActorKindSchema, B as ChatModels, Dt as isEarlyStop, Jt as DELEGATION_PAYLOAD_SCHEMA_NAME, Qt as delegationPayloadSchema, S as isValidSessionId, Vt as tokenEstimateMultiplier, Xt as actorKindMarker, Yt as actorColorIndex, Zt as actorKindSchema, _ as LOCAL_DEV_URL, at as REVIEW_GATE_STATUS_VALUES, b as logger, ct as SUBQUEST_STATUS_VALUES, d as getCreditsUrl, f as getEnvironmentName, i as ToolCatalog, m as resolveApiEndpoint, n as extractCompactInstructions, p as requireApiUrl, qt as ACTOR_COLOR_SLOTS, t as ConfigStore, u as ApiEndpointUnconfiguredError, x as SESSION_ID_PATTERN, y as parseApiUrl, z as CREDIT_DEDUCT_TRANSACTION_TYPES } from "./ConfigStore-BwqsQ0U9.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";
5
7
  import { a as rewireReservedNames, i as mergeCommands, t as RemoteSkillSource } from "./RemoteSkillSource-qTvRkaNA.mjs";
6
8
  import { r as isFeatureEnabled, t as PluginStore } from "./PluginStore-DwvOJ-G3.mjs";
7
- import { i as getTokenCounter, n as ConversationContext, r as reconstructTurnBlocks, t as WorkItemsClient } from "./WorkItemsClient-CERTDrhT.mjs";
8
- import { a as deferredToolRegistry, i as buildLlmBackend, n as buildAgent, o as NotifyingLlmBackend, r as buildSupportingStores, t as buildToolSearch } from "./buildToolSearch-D9GEK91u.mjs";
9
+ import { i as getTokenCounter, n as ConversationContext, r as reconstructTurnBlocks, t as WorkItemsClient } from "./WorkItemsClient-CxNZaOmc.mjs";
9
10
  import { t as getShellSessionManager } from "./ShellSessionManager-6o8KZzl1-vrbPAUTq.mjs";
10
- import { r as OAuthClient, t as ApiClient } from "./ApiClient-_JrM_xWw.mjs";
11
- import { t as version } from "./package-CQaam4Dq.mjs";
12
- 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";
13
15
  import React, { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
14
- 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";
15
17
  import { randomBytes } from "crypto";
16
18
  import { constants, existsSync, promises, readFileSync, statSync } from "fs";
17
19
  import { homedir } from "os";
18
20
  import path, { basename, extname, join } from "path";
19
21
  import { v4 } from "uuid";
20
- import * as path$1 from "node:path";
22
+ import * as path$2 from "node:path";
21
23
  import { z as z$1 } from "zod";
22
24
  import axios, { isAxiosError } from "axios";
23
25
  import Spinner from "ink-spinner";
@@ -336,14 +338,14 @@ function CommandAutocomplete({ commands, selectedIndex }) {
336
338
  }, /* @__PURE__ */ React.createElement(Text, {
337
339
  color: isSelected ? "cyan" : void 0,
338
340
  bold: isSelected
339
- }, isSelected ? "▸ " : " ", sourceIcon, "/", cmd.name, args, " - ", cmd.description));
341
+ }, isSelected ? "▸ " : " ", sourceIcon, "/", sanitizeTerminalText(cmd.name), sanitizeTerminalText(args), " - ", sanitizeTerminalText(cmd.description)));
340
342
  }));
341
343
  }
342
344
  //#endregion
343
345
  //#region src/components/FileAutocomplete.tsx
344
346
  function FileAutocomplete({ files, selectedIndex, query }) {
345
347
  if (files.length === 0) {
346
- if (path$1.isAbsolute(query)) return /* @__PURE__ */ React.createElement(Box, {
348
+ if (path$2.isAbsolute(query)) return /* @__PURE__ */ React.createElement(Box, {
347
349
  marginLeft: 2,
348
350
  marginTop: 1
349
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)"));
@@ -370,7 +372,7 @@ function FileAutocomplete({ files, selectedIndex, query }) {
370
372
  const isSelected = startIndex + viewportIndex === selectedIndex;
371
373
  const icon = file.isDirectory ? "[folder]" : "[file] ";
372
374
  const sizeDisplay = file.isDirectory ? "" : file.size !== void 0 ? ` (${formatFileSize(file.size)})` : "";
373
- const pathDisplay = file.isDirectory ? `${file.path}/` : file.path;
375
+ const pathDisplay = sanitizeTerminalText(file.isDirectory ? `${file.path}/` : file.path);
374
376
  return /* @__PURE__ */ React.createElement(Box, {
375
377
  key: file.path,
376
378
  marginLeft: 1
@@ -621,7 +623,7 @@ function findAtTrigger(value) {
621
623
  }
622
624
  return null;
623
625
  }
624
- 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 }) {
625
627
  const value = useCliStore((state) => state.inputValue);
626
628
  const setValue = useCliStore((state) => state.setInputValue);
627
629
  const pastedContent = useCliStore((state) => state.pastedContent);
@@ -646,7 +648,7 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
646
648
  onBashModeChange?.(isBashMode);
647
649
  }, [isBashMode, onBashModeChange]);
648
650
  const commandQuery = value.startsWith("/") ? value.slice(1) : "";
649
- 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(" ");
650
652
  const filteredCommands = useMemo(() => {
651
653
  if (!shouldShowCommandAutocomplete) return [];
652
654
  return searchCommands(commandQuery, commands);
@@ -711,6 +713,7 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
711
713
  const content = pastedContent ?? value;
712
714
  if (!content.trim()) return;
713
715
  if (pastedContent) clearPaste();
716
+ onHistoryEntry?.(content);
714
717
  onSubmit(content, { followUp: true });
715
718
  setValue("");
716
719
  setHistoryIndex(-1);
@@ -762,7 +765,9 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
762
765
  if (pastedContent) {
763
766
  const fullContent = pastedContent;
764
767
  clearPaste();
768
+ onHistoryEntry?.(fullContent);
765
769
  onSubmit(fullContent);
770
+ setHistoryIndex(-1);
766
771
  return;
767
772
  }
768
773
  if (!input.trim()) return;
@@ -781,12 +786,14 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
781
786
  }
782
787
  setValue("");
783
788
  setHistoryIndex(-1);
789
+ onHistoryEntry?.(commandText);
784
790
  onSubmit(commandText);
785
791
  return;
786
792
  }
787
793
  if (isBashMode && onBashCommand) {
788
794
  const command = input.slice(1).trim();
789
795
  if (command) {
796
+ onHistoryEntry?.(input);
790
797
  onBashCommand(command);
791
798
  setValue("");
792
799
  setHistoryIndex(-1);
@@ -794,6 +801,7 @@ function InputPrompt({ onSubmit, onBashCommand, onImageDetected, disabled = fals
794
801
  }
795
802
  return;
796
803
  }
804
+ onHistoryEntry?.(input);
797
805
  onSubmit(input);
798
806
  setValue("");
799
807
  setHistoryIndex(-1);
@@ -916,9 +924,10 @@ const AgentThinking = React.memo(function AgentThinking() {
916
924
  const JobItem = React.memo(function JobItem({ job, indented = false }) {
917
925
  const elapsed = Math.round((Date.now() - job.startTime) / 1e3);
918
926
  const maxTaskLength = indented ? 50 : 60;
919
- 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;
920
929
  const isQueued = job.status === "queued";
921
- 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)`));
922
931
  });
923
932
  /**
924
933
  * Counts running and queued jobs, returning a formatted status string
@@ -1006,7 +1015,8 @@ const TERMINAL_ICON = {
1006
1015
  function elapsedSeconds(session) {
1007
1016
  return Math.round(((session.endTime ?? Date.now()) - session.startTime) / 1e3);
1008
1017
  }
1009
- function commandPreview(command) {
1018
+ function commandPreview(rawCommand) {
1019
+ const command = sanitizeTerminalText(rawCommand);
1010
1020
  return command.length > MAX_COMMAND_LENGTH ? command.slice(0, 57) + "..." : command;
1011
1021
  }
1012
1022
  /** A running session: spinner + command + elapsed time. */
@@ -1090,35 +1100,13 @@ function CompletedGroupNotification() {
1090
1100
  }, "✔", " "), /* @__PURE__ */ React.createElement(Text, {
1091
1101
  color: "green",
1092
1102
  bold: true
1093
- }, 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, {
1094
1104
  dimColor: true,
1095
1105
  italic: true
1096
1106
  }, "Results will be incorporated in the next response.")))));
1097
1107
  }
1098
1108
  //#endregion
1099
1109
  //#region src/components/PermissionPrompt.tsx
1100
- /**
1101
- * Escape characters that let untrusted text render differently from what
1102
- * actually runs, into a visible escape form. Shared by every prompt that shows
1103
- * untrusted text for the user to decide on: tool previews/arguments here,
1104
- * repo-authored MCP definitions (McpApprovalPrompt), the folder-trust path
1105
- * (FolderTrustPrompt), and model-authored ReviewGatePrompt / UserQuestionPrompt text. Display only - never escape the
1106
- * value that is acted on or sent back.
1107
- * These ranges are covered, deliberately and no wider:
1108
- * - C0 controls (minus tab/newline), DEL and C1 controls -> `\xHH`: a raw
1109
- * `\r`, ESC or 8-bit CSI (U+009B) could rewrite the line being approved.
1110
- * - Unicode bidi overrides U+202A..U+202E and isolates U+2066..U+2069
1111
- * -> `\uXXXX`: these reorder displayed glyphs without changing the
1112
- * underlying code points, spoofing the same way.
1113
- * Tab and newline are left intact (newline is already the line delimiter).
1114
- * Widen the scope here, so both call sites gain it at once.
1115
- */
1116
- function escapeTerminalControlChars(text) {
1117
- return text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, (ch) => {
1118
- const code = ch.charCodeAt(0);
1119
- return code > 255 ? `\\u${code.toString(16).padStart(4, "0")}` : `\\x${code.toString(16).padStart(2, "0")}`;
1120
- });
1121
- }
1122
1110
  /** Render a diff/preview string, color-coding each line by its prefix (see per-branch comments below). */
1123
1111
  function renderDiffPreview(preview) {
1124
1112
  return escapeTerminalControlChars(preview).split("\n").map((line, index) => {
@@ -1150,16 +1138,25 @@ function renderDiffPreview(preview) {
1150
1138
  });
1151
1139
  }
1152
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
+ }
1153
1150
  /**
1154
1151
  * Permission prompt component
1155
1152
  *
1156
1153
  * Displays when a tool needs permission before execution.
1157
1154
  * Waits indefinitely for user response (like Claude Code).
1158
1155
  */
1159
- function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrusted, kind, onResponse }) {
1156
+ function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrusted, sessionScope, kind, onResponse }) {
1160
1157
  const isSandboxEscalation = kind === "sandbox-escalation";
1161
1158
  const hideArgs = TOOLS_WITH_HIDDEN_ARGS$1.has(toolName);
1162
- const items = isSandboxEscalation ? [
1159
+ const baseItems = isSandboxEscalation ? [
1163
1160
  {
1164
1161
  label: "✓ Retry once without sandbox",
1165
1162
  value: "allow-once"
@@ -1203,6 +1200,7 @@ function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrust
1203
1200
  value: "deny"
1204
1201
  }
1205
1202
  ];
1203
+ const items = isSandboxEscalation || sessionScope === void 0 ? baseItems : withSessionScope(baseItems, sessionScope);
1206
1204
  const [selectedIndex, setSelectedIndex] = useState(0);
1207
1205
  const [responded, setResponded] = useState(false);
1208
1206
  const handleSelect = useCallback(() => {
@@ -1438,7 +1436,7 @@ function UserQuestionPrompt({ payload, onResponse }) {
1438
1436
  }, /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Text, {
1439
1437
  bold: true,
1440
1438
  color: "cyan"
1441
- }, "? 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, {
1442
1440
  marginTop: 1,
1443
1441
  flexDirection: "column"
1444
1442
  }, options.map((opt, idx) => {
@@ -1448,12 +1446,12 @@ function UserQuestionPrompt({ payload, onResponse }) {
1448
1446
  return /* @__PURE__ */ React.createElement(Box, { key: idx }, /* @__PURE__ */ React.createElement(Text, { color: "cyan" }, idx + 1, "."), /* @__PURE__ */ React.createElement(Text, {
1449
1447
  color: isHighlighted ? "cyan" : void 0,
1450
1448
  bold: isHighlighted
1451
- }, " ", 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, {
1452
1450
  value: otherText,
1453
1451
  onChange: setOtherText,
1454
1452
  onSubmit: submitOther,
1455
1453
  placeholder: "Type your answer..."
1456
- })) : 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 })));
1457
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")));
1458
1456
  }
1459
1457
  //#endregion
@@ -1556,10 +1554,10 @@ function ReviewGatePrompt({ description, options, recommendation, onResponse })
1556
1554
  }, /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Text, {
1557
1555
  bold: true,
1558
1556
  color: "magenta"
1559
- }, "🛑 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, {
1560
1558
  marginTop: 1,
1561
1559
  flexDirection: "column"
1562
- }, /* @__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, {
1563
1561
  marginTop: 1,
1564
1562
  flexDirection: "column"
1565
1563
  }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "Options:"), /* @__PURE__ */ React.createElement(Box, {
@@ -1568,7 +1566,7 @@ function ReviewGatePrompt({ description, options, recommendation, onResponse })
1568
1566
  }, options.map((opt, idx) => /* @__PURE__ */ React.createElement(Text, {
1569
1567
  key: idx,
1570
1568
  dimColor: true
1571
- }, "• ", escapeTerminalControlChars(opt))))), /* @__PURE__ */ React.createElement(Box, {
1569
+ }, "• ", escapeTerminalControlChars(opt, { keepBidiMarks: true }))))), /* @__PURE__ */ React.createElement(Box, {
1572
1570
  marginTop: 1,
1573
1571
  flexDirection: "column"
1574
1572
  }, ITEMS.map((item, index) => {
@@ -2072,13 +2070,13 @@ function McpViewer({ config, mcpManager, onClose }) {
2072
2070
  dimColor: true
2073
2071
  }, "Configured Servers:"), config.mcpServers.map((server) => {
2074
2072
  const status = server.enabled ? "✅ Enabled" : "⏸️ Disabled";
2075
- const commandInfo = server.command ? `${server.command} ${(server.args || []).join(" ")}` : "(internal)";
2073
+ const commandInfo = server.command ? sanitizeTerminalText(`${server.command} ${(server.args || []).join(" ")}`) : "(internal)";
2076
2074
  return /* @__PURE__ */ React.createElement(Box, {
2077
2075
  key: server.name,
2078
2076
  flexDirection: "column",
2079
2077
  marginTop: 1,
2080
2078
  marginLeft: 2
2081
- }, /* @__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(", "))));
2082
2080
  })), enabledServers.length > 0 && mcpManager && /* @__PURE__ */ React.createElement(Box, {
2083
2081
  flexDirection: "column",
2084
2082
  marginBottom: 2
@@ -2117,7 +2115,7 @@ function McpViewer({ config, mcpManager, onClose }) {
2117
2115
  key: server.name,
2118
2116
  marginTop: 1,
2119
2117
  marginLeft: 2
2120
- }, /* @__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)));
2121
2119
  }), /* @__PURE__ */ React.createElement(Box, {
2122
2120
  marginTop: 1,
2123
2121
  marginLeft: 2
@@ -2134,109 +2132,6 @@ function McpViewer({ config, mcpManager, onClose }) {
2134
2132
  }, "Press Esc or q to close")));
2135
2133
  }
2136
2134
  //#endregion
2137
- //#region src/storage/CommandHistoryStore.ts
2138
- /**
2139
- * Maximum number of history entries to keep
2140
- */
2141
- const MAX_HISTORY_ENTRIES = 1e3;
2142
- /**
2143
- * Manages command history stored in JSONL format
2144
- * Uses append-friendly JSONL for efficient writes
2145
- */
2146
- var CommandHistoryStore = class {
2147
- constructor(historyPath) {
2148
- this.history = null;
2149
- this.historyPath = historyPath || path.join(homedir(), ".bike4mind", "history.jsonl");
2150
- }
2151
- /**
2152
- * Initialize history directory
2153
- */
2154
- async init() {
2155
- const dir = path.dirname(this.historyPath);
2156
- try {
2157
- await promises.mkdir(dir, { recursive: true });
2158
- } catch (error) {
2159
- console.error("Failed to initialize history directory:", error);
2160
- throw error;
2161
- }
2162
- }
2163
- /**
2164
- * Load command history from disk
2165
- * Returns array of commands (newest first)
2166
- */
2167
- async load() {
2168
- if (this.history) return this.history;
2169
- try {
2170
- const entries = (await promises.readFile(this.historyPath, "utf-8")).trim().split("\n").filter((line) => line.length > 0).map((line) => {
2171
- try {
2172
- return JSON.parse(line);
2173
- } catch {
2174
- return null;
2175
- }
2176
- }).filter((entry) => entry !== null);
2177
- this.history = entries.sort((a, b) => b.timestamp - a.timestamp).map((entry) => entry.command);
2178
- return this.history;
2179
- } catch (error) {
2180
- if (error.code === "ENOENT") {
2181
- this.history = [];
2182
- return this.history;
2183
- }
2184
- throw error;
2185
- }
2186
- }
2187
- /**
2188
- * Add a command to history
2189
- * Skips if it's the same as the most recent command (deduplicate)
2190
- */
2191
- async add(command) {
2192
- await this.load();
2193
- if (!command || !command.trim()) return;
2194
- if (this.history && this.history.length > 0 && this.history[0] === command) return;
2195
- const entry = {
2196
- command,
2197
- timestamp: Date.now()
2198
- };
2199
- await this.init();
2200
- const line = JSON.stringify(entry) + "\n";
2201
- await promises.appendFile(this.historyPath, line, "utf-8");
2202
- this.history = [command, ...this.history || []];
2203
- if (this.history.length > MAX_HISTORY_ENTRIES) await this.trim();
2204
- }
2205
- /**
2206
- * Trim history to max entries
2207
- * Rewrites the entire file with the most recent entries
2208
- */
2209
- async trim() {
2210
- if (!this.history || this.history.length <= MAX_HISTORY_ENTRIES) return;
2211
- const trimmedCommands = this.history.slice(0, MAX_HISTORY_ENTRIES);
2212
- const lines = trimmedCommands.reverse().map((command) => {
2213
- return JSON.stringify({
2214
- command,
2215
- timestamp: Date.now()
2216
- });
2217
- }).join("\n");
2218
- await promises.writeFile(this.historyPath, lines + "\n", "utf-8");
2219
- this.history = trimmedCommands;
2220
- }
2221
- /**
2222
- * Clear all command history
2223
- */
2224
- async clear() {
2225
- try {
2226
- await promises.unlink(this.historyPath);
2227
- } catch (error) {
2228
- if (error.code !== "ENOENT") throw error;
2229
- }
2230
- this.history = [];
2231
- }
2232
- /**
2233
- * Get all commands (newest first)
2234
- */
2235
- async list() {
2236
- return this.load();
2237
- }
2238
- };
2239
- //#endregion
2240
2135
  //#region src/storage/buildGlobalConfigPatch.ts
2241
2136
  /**
2242
2137
  * Compute the minimal global-config patch for a /config editor save: only the
@@ -2269,7 +2164,7 @@ function buildGlobalConfigPatch(prev, next) {
2269
2164
  //#region src/components/MarkdownRenderer.tsx
2270
2165
  function MarkdownRenderer({ content, columns: columnsProp }) {
2271
2166
  const columns = columnsProp ?? process.stdout.columns ?? 80;
2272
- const tokens = marked.lexer(content);
2167
+ const tokens = marked.lexer(sanitizeTerminalText(content));
2273
2168
  return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, tokens.map((token, idx) => renderToken(token, idx, columns)));
2274
2169
  }
2275
2170
  function renderToken(token, idx, columns) {
@@ -2480,13 +2375,17 @@ function useStdoutDimensions() {
2480
2375
  */
2481
2376
  /** Rows the trace Box spends on the "N earlier steps" hint and its bottom margin. */
2482
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;
2483
2380
  /**
2484
2381
  * Truncates a value to maxLength, converting objects to JSON strings.
2485
2382
  * Appends '...' if truncated.
2486
2383
  */
2487
2384
  function truncateValue(value, maxLength) {
2488
- const str = typeof value === "string" ? value : JSON.stringify(value);
2489
- 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;
2490
2389
  return str.slice(0, maxLength) + "...";
2491
2390
  }
2492
2391
  const isRenderable = (step, showThoughts) => step.type === "action" || step.type === "thought" && showThoughts;
@@ -2604,10 +2503,11 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2604
2503
  const traceWrap = isLive ? "truncate-end" : "wrap";
2605
2504
  const oneLine = (text) => isLive ? text.replace(/\s+/g, " ") : text;
2606
2505
  const hasReply = !isUser && message.content !== "...";
2506
+ const content = React.useMemo(() => sanitizeTerminalText(message.content), [message.content]);
2607
2507
  const allSteps = message.metadata?.steps;
2608
2508
  const liveSplit = React.useMemo(() => {
2609
2509
  if (liveRows === void 0) return void 0;
2610
- const replyRows = hasReply ? wrapReplyRows(message.content, terminalCols - REPLY_INDENT) : [];
2510
+ const replyRows = hasReply ? wrapReplyRows(content, terminalCols - REPLY_INDENT) : [];
2611
2511
  return splitLiveRows(liveRows, {
2612
2512
  steps: allSteps ?? [],
2613
2513
  replyRows,
@@ -2616,7 +2516,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2616
2516
  }, [
2617
2517
  liveRows,
2618
2518
  hasReply,
2619
- message.content,
2519
+ content,
2620
2520
  terminalCols,
2621
2521
  allSteps,
2622
2522
  showThoughts
@@ -2640,7 +2540,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2640
2540
  showThoughts
2641
2541
  ]);
2642
2542
  const visibleTraceSteps = traceSteps.filter((s) => showThoughts && s.type === "thought" || s.type === "action").length;
2643
- const userPromptText = `❯ ${message.content}`;
2543
+ const userPromptText = `\u276F ${content}`;
2644
2544
  const paddedUserPromptText = userPromptText.length >= terminalCols ? userPromptText : userPromptText.padEnd(terminalCols);
2645
2545
  return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, isUser && message.content && /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, {
2646
2546
  backgroundColor: "whiteBright",
@@ -2662,7 +2562,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2662
2562
  }, /* @__PURE__ */ React.createElement(Text, {
2663
2563
  dimColor: true,
2664
2564
  wrap: traceWrap
2665
- }, `💭 ${oneLine(step.content)}`));
2565
+ }, `\u{1F4AD} ${oneLine(sanitizeTerminalText(step.content))}`));
2666
2566
  }
2667
2567
  if (step.type === "action") {
2668
2568
  const toolName = step.metadata?.toolName || "unknown";
@@ -2675,7 +2575,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2675
2575
  key: idx,
2676
2576
  marginTop: 1,
2677
2577
  flexDirection: "column"
2678
- }, /* @__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, {
2679
2579
  dimColor: true,
2680
2580
  wrap: traceWrap
2681
2581
  }, `Result: ${oneLine(truncateValue(result, 200))}`)));
@@ -2691,8 +2591,8 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2691
2591
  }, row || " "))), !isLive && hasReply && /* @__PURE__ */ React.createElement(Box, {
2692
2592
  paddingLeft: REPLY_INDENT,
2693
2593
  marginBottom: 1
2694
- }, message.metadata?.permissionDenied ? /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "⚠️ ", message.content) : /* @__PURE__ */ React.createElement(MarkdownRenderer, {
2695
- content: message.content,
2594
+ }, message.metadata?.permissionDenied ? /* @__PURE__ */ React.createElement(Text, { color: "yellow" }, "⚠️", " ", content) : /* @__PURE__ */ React.createElement(MarkdownRenderer, {
2595
+ content,
2696
2596
  columns: terminalCols
2697
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, {
2698
2598
  paddingLeft: 2,
@@ -2719,7 +2619,7 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2719
2619
  const LIVE_CHROME_ROWS = 10;
2720
2620
  /** Shown under the queued-message rows; mirrors the routing in handleSubmit and the ESC handler in index.tsx. */
2721
2621
  const QUEUE_HINT = "Enter steers this turn · Tab queues for next turn · Esc cancels and restores to input";
2722
- function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPermissionResponse, onUserQuestionResponse, onReviewGateResponse, onImageDetected, commandHistory = [], commands = [], config, availableModels = [], pluginDescriptors = [], onSaveConfig, prefillInput, onPrefillConsumed, mcpManager }) {
2622
+ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPermissionResponse, onUserQuestionResponse, onReviewGateResponse, onImageDetected, commandHistory = [], onHistoryEntry, commands = [], config, availableModels = [], pluginDescriptors = [], onSaveConfig, prefillInput, onPrefillConsumed, mcpManager }) {
2723
2623
  const messages = useCliStore(useShallow((state) => state.session?.messages || []));
2724
2624
  const pendingMessages = useCliStore((state) => state.pendingMessages);
2725
2625
  const messageQueue = useCliStore((state) => state.messageQueue);
@@ -2866,6 +2766,7 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2866
2766
  args: permissionPrompt.args,
2867
2767
  preview: permissionPrompt.preview,
2868
2768
  canBeTrusted: permissionPrompt.canBeTrusted,
2769
+ sessionScope: permissionPrompt.sessionScope,
2869
2770
  kind: permissionPrompt.kind,
2870
2771
  onResponse: (response) => onPermissionResponse(response, permissionPrompt.id)
2871
2772
  })), userQuestionPrompt && /* @__PURE__ */ React.createElement(Box, {
@@ -2932,6 +2833,7 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2932
2833
  onImageDetected,
2933
2834
  disabled: !!permissionPrompt || !!userQuestionPrompt || !!reviewGatePrompt || !!exitHandoffPrompt,
2934
2835
  history: commandHistory,
2836
+ onHistoryEntry,
2935
2837
  commands,
2936
2838
  prefillInput,
2937
2839
  onPrefillConsumed,
@@ -3073,7 +2975,8 @@ function RewindSelector({ messages, onSelect, onCancel }) {
3073
2975
  msg,
3074
2976
  originalIndex: idx
3075
2977
  })).filter(({ msg }) => msg.role === "user" && !msg.metadata?.steered).map(({ msg, originalIndex }, index) => {
3076
- const preview = msg.content.length > 50 ? msg.content.substring(0, 50) + "..." : msg.content;
2978
+ const content = sanitizeTerminalText(msg.content);
2979
+ const preview = content.length > 50 ? content.substring(0, 50) + "..." : content;
3077
2980
  const timestamp = new Date(msg.timestamp).toLocaleString();
3078
2981
  return {
3079
2982
  label: `[${index + 1}] ${timestamp} - ${preview}`,
@@ -3111,7 +3014,8 @@ function RewindSelector({ messages, onSelect, onCancel }) {
3111
3014
  value: "cancel"
3112
3015
  }];
3113
3016
  const selectedMessage = selectedMessageIndex !== null && selectedMessageIndex >= 0 && selectedMessageIndex < messages.length ? messages[selectedMessageIndex] : null;
3114
- 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;
3115
3019
  return /* @__PURE__ */ React.createElement(Box, {
3116
3020
  flexDirection: "column",
3117
3021
  marginY: 1
@@ -3152,7 +3056,8 @@ function SessionSelector({ sessions, currentSession, onSelect, onCancel }) {
3152
3056
  const items = sessions.map((session, index) => {
3153
3057
  const userMessages = session.messages.filter((msg) => msg.role === "user");
3154
3058
  const lastUserMessage = userMessages[userMessages.length - 1];
3155
- 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";
3156
3061
  const timeAgo = formatTimeAgo(session.updatedAt);
3157
3062
  return {
3158
3063
  key: session.id,
@@ -3185,7 +3090,7 @@ function SessionSelector({ sessions, currentSession, onSelect, onCancel }) {
3185
3090
  }, /* @__PURE__ */ React.createElement(Box, {
3186
3091
  marginBottom: 1,
3187
3092
  flexDirection: "column"
3188
- }, /* @__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, {
3189
3094
  items: [{
3190
3095
  label: "Yes, resume this session",
3191
3096
  value: "confirm"
@@ -3238,18 +3143,41 @@ function ModelPicker({ models, currentModelId, onSelect, onCancel }) {
3238
3143
  }
3239
3144
  //#endregion
3240
3145
  //#region src/components/EnvironmentPicker.tsx
3241
- 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() }) {
3242
3155
  const [phase, setPhase] = useState("menu");
3243
3156
  const [customValue, setCustomValue] = useState("");
3244
3157
  const [error, setError] = useState(null);
3245
- const items = [{
3246
- label: `Local dev server (${LOCAL_DEV_URL})`,
3247
- value: "dev"
3248
- }, {
3249
- label: "Custom / self-hosted URL…",
3250
- value: "custom"
3251
- }];
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
+ ];
3252
3176
  const handleMenuSelect = (item) => {
3177
+ if (item.value === "prod") {
3178
+ onSelect({ target: "prod" });
3179
+ return;
3180
+ }
3253
3181
  if (item.value === "dev") {
3254
3182
  onSelect({ target: "dev" });
3255
3183
  return;
@@ -3275,15 +3203,94 @@ function EnvironmentPicker({ onSelect }) {
3275
3203
  },
3276
3204
  onSubmit: handleCustomSubmit,
3277
3205
  placeholder: "https://app.example.com"
3278
- })), 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)));
3279
3207
  return /* @__PURE__ */ React.createElement(Box, {
3280
3208
  flexDirection: "column",
3281
3209
  marginY: 1
3282
3210
  }, /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "🌍 Where should b4m connect?")), /* @__PURE__ */ React.createElement(SelectInput, {
3283
3211
  items,
3284
3212
  onSelect: handleMenuSelect,
3213
+ indicatorComponent: NoIndicator,
3285
3214
  itemComponent: ({ isSelected, label }) => /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Text, { color: isSelected ? "cyan" : void 0 }, isSelected ? "❯ " : " ", label))
3286
- }), /* @__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";
3287
3294
  }
3288
3295
  //#endregion
3289
3296
  //#region src/components/LoginFlow.tsx
@@ -3350,18 +3357,34 @@ function extractErrorMessage(err) {
3350
3357
  if (err instanceof Error) return err.message || "Unknown error occurred";
3351
3358
  return "Unknown error occurred";
3352
3359
  }
3353
- function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, onError }) {
3360
+ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, onError, onCancel }) {
3354
3361
  const [status, setStatus] = useState("initiating");
3355
3362
  const [deviceFlow, setDeviceFlow] = useState(null);
3356
3363
  const [statusMessage, setStatusMessage] = useState("Initiating device authorization...");
3357
3364
  const [error, setError] = useState(null);
3358
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);
3359
3379
  useEffect(() => {
3380
+ const abort = new AbortController();
3381
+ abortRef.current = abort;
3382
+ let successTimer;
3360
3383
  const runLoginFlow = async () => {
3361
3384
  const oauth = new OAuthClient(apiUrl);
3362
3385
  try {
3363
3386
  setStatus("initiating");
3364
- const deviceFlowResponse = await oauth.initiateDeviceFlow();
3387
+ const deviceFlowResponse = await oauth.initiateDeviceFlow(abort.signal);
3365
3388
  setDeviceFlow({
3366
3389
  ...deviceFlowResponse,
3367
3390
  verification_uri: stripControlChars(deviceFlowResponse.verification_uri),
@@ -3370,51 +3393,74 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
3370
3393
  });
3371
3394
  setStatus("waiting");
3372
3395
  setStatusMessage("Waiting for authorization...");
3373
- 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;
3374
3399
  const userId = jwt.decode(tokens.access_token)?.id || "";
3375
3400
  const expiresAt = new Date(Date.now() + tokens.expires_in * 1e3).toISOString();
3376
- await configStore.setAuthTokens({
3401
+ await configStore.withRefreshLock(() => configStore.setAuthTokens({
3377
3402
  accessToken: tokens.access_token,
3378
3403
  refreshToken: tokens.refresh_token,
3379
3404
  expiresAt,
3380
3405
  userId
3381
- });
3406
+ }));
3382
3407
  setAccount({ userId });
3383
3408
  setStatus("success");
3384
3409
  setStatusMessage("Successfully authenticated!");
3385
- setTimeout(() => onSuccess(), 1500);
3410
+ successTimer = setTimeout(() => callbacks.current.onSuccess(), 1500);
3386
3411
  new ApiClient(apiUrl, configStore).get("/api/identify").then((res) => setAccount({
3387
3412
  userId,
3388
3413
  email: stripControlChars(res?.user?.email),
3389
3414
  username: stripControlChars(res?.user?.username)
3390
3415
  })).catch(() => {});
3391
3416
  } catch (err) {
3417
+ if (abort.signal.aborted) return;
3392
3418
  setStatus("error");
3393
3419
  const errorMessage = stripControlChars(extractErrorMessage(err));
3394
3420
  setError(errorMessage);
3395
- onError(new Error(errorMessage));
3421
+ callbacks.current.onError(new Error(errorMessage));
3396
3422
  }
3397
3423
  };
3398
3424
  runLoginFlow();
3399
- }, [
3400
- apiUrl,
3401
- configStore,
3402
- onSuccess,
3403
- onError
3404
- ]);
3405
- 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;
3406
3432
  const isTrustedUri = (u) => isBrowserOpenableUrl(u) && isOnApiOrigin(u, apiUrl);
3407
- const untrustedUri = uris.find((u) => !isTrustedUri(u));
3408
- 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.`;
3409
3438
  useEffect(() => {
3410
- 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) => {
3411
3441
  console.error("Failed to auto-open browser:", err);
3412
3442
  });
3413
3443
  }, [
3444
+ link,
3414
3445
  deviceFlow,
3415
3446
  status,
3416
3447
  trusted
3417
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 });
3418
3464
  if (status === "initiating") return /* @__PURE__ */ React.createElement(Box, {
3419
3465
  flexDirection: "column",
3420
3466
  padding: 1
@@ -3441,22 +3487,43 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
3441
3487
  }, /* @__PURE__ */ React.createElement(Box, { marginBottom: 1 }, /* @__PURE__ */ React.createElement(Text, {
3442
3488
  color: "cyan",
3443
3489
  bold: true
3444
- }, "🔐 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, {
3445
3491
  color: "red",
3446
3492
  bold: true
3447
- }, !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, {
3448
3500
  marginBottom: 1,
3449
3501
  paddingLeft: 2
3450
3502
  }, /* @__PURE__ */ React.createElement(Text, {
3451
3503
  color: "blue",
3452
3504
  bold: true
3453
- }, 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, {
3454
3506
  marginBottom: 1,
3455
3507
  paddingLeft: 2
3456
3508
  }, /* @__PURE__ */ React.createElement(Text, {
3457
3509
  color: "yellow",
3458
3510
  bold: true
3459
- }, 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");
3460
3527
  }
3461
3528
  //#endregion
3462
3529
  //#region src/utils/formatStep.ts
@@ -3603,6 +3670,17 @@ function resolveModelCommand(models, args, currentModel) {
3603
3670
  //#region src/utils/performModelSwitch.ts
3604
3671
  const MODEL_SWITCH_BUSY_MESSAGE = "Agent is busy - wait for the current response to finish before switching models.";
3605
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
+ /**
3606
3684
  * Side-effect layer for a `/model` switch, shared by the argument dispatcher and
3607
3685
  * the interactive picker so both entry points get the same guards and messages.
3608
3686
  *
@@ -3631,6 +3709,21 @@ async function performModelSwitch(model, deps) {
3631
3709
  deps.error(`Failed to switch model: ${error instanceof Error ? error.message : String(error)}`);
3632
3710
  }
3633
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
+ }
3634
3727
  /** Per-line elision caps (chars) keeping single items from eating the budget. */
3635
3728
  const MAX_ITEM_CHARS = 160;
3636
3729
  /**
@@ -3883,7 +3976,7 @@ function extractJsonObject(text) {
3883
3976
  * timestamp so the user knows how fresh the context is.
3884
3977
  */
3885
3978
  function formatHandoffOutput(handoff) {
3886
- return formatHandoff(handoff, { includeTimestamp: true });
3979
+ return sanitizeTerminalText(formatHandoff(handoff, { includeTimestamp: true }));
3887
3980
  }
3888
3981
  /**
3889
3982
  * Build the system message that injects handoff context into a resumed
@@ -4024,7 +4117,8 @@ function buildLocalHandoff(session, workflowOverride) {
4024
4117
  }
4025
4118
  /**
4026
4119
  * Render a full Markdown handoff document from session state. Includes
4027
- * 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
4028
4122
  * `LOCAL_HANDOFF_MESSAGE_TAIL` messages role-labeled and lightly truncated,
4029
4123
  * and a pointer to the on-disk session JSON for deeper context.
4030
4124
  *
@@ -4108,7 +4202,7 @@ function renderLocalHandoffMarkdown(session, sessionJsonPath) {
4108
4202
  lines.push(content);
4109
4203
  lines.push("");
4110
4204
  }
4111
- return lines.join("\n");
4205
+ return sanitizeTerminalText(lines.join("\n"));
4112
4206
  }
4113
4207
  function appendMarkdownSection(lines, heading, items) {
4114
4208
  if (items.length === 0) return;
@@ -7481,6 +7575,7 @@ function hearthSessionFromStore() {
7481
7575
  */
7482
7576
  function createBuiltinModules(config, apiClient) {
7483
7577
  const modules = [];
7578
+ if (apiClient.signedOut) return modules;
7484
7579
  if (config.features?.tavern) modules.push(new TavernModule(apiClient, (entry) => useCliStore.getState().addTavernLogEntry(entry), () => useCliStore.getState().tavernActivityLog));
7485
7580
  if (config.features?.hearth) modules.push(new HearthModule(apiClient, () => hearthSessionFromStore()));
7486
7581
  return modules;
@@ -8034,9 +8129,11 @@ function updatePendingAssistant(update) {
8034
8129
  * step handlers already used) and emits tavern events through the bridge
8035
8130
  * singleton; neither owns React-lifecycle state.
8036
8131
  */
8132
+ let nextSubagentRunId = 0;
8037
8133
  function wireAgentEvents(input) {
8038
- const { agent, orchestrator } = input;
8134
+ const { agent, orchestrator, isCurrent = () => true } = input;
8039
8135
  const stepHandler = (step) => {
8136
+ if (!isCurrent()) return;
8040
8137
  updatePendingAssistant((message) => ({
8041
8138
  ...message,
8042
8139
  metadata: {
@@ -8051,6 +8148,7 @@ function wireAgentEvents(input) {
8051
8148
  text: ""
8052
8149
  };
8053
8150
  const textDeltaHandler = ({ delta, iteration }) => {
8151
+ if (!isCurrent()) return;
8054
8152
  updatePendingAssistant((message) => {
8055
8153
  const sameStream = liveText.messageId === message.id && liveText.iteration === iteration;
8056
8154
  liveText = {
@@ -8065,6 +8163,7 @@ function wireAgentEvents(input) {
8065
8163
  });
8066
8164
  };
8067
8165
  const clearLiveText = () => {
8166
+ if (!isCurrent()) return;
8068
8167
  if (!liveText.text) return;
8069
8168
  liveText = {
8070
8169
  ...liveText,
@@ -8092,6 +8191,7 @@ function wireAgentEvents(input) {
8092
8191
  }
8093
8192
  };
8094
8193
  const tavernActionHandler = (step) => {
8194
+ if (!isCurrent()) return;
8095
8195
  const toolName = step.metadata?.toolName ?? "tool";
8096
8196
  const toolUseId = `${toolName}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
8097
8197
  const queue = pendingToolUseIds.get(toolName) ?? [];
@@ -8105,6 +8205,7 @@ function wireAgentEvents(input) {
8105
8205
  });
8106
8206
  };
8107
8207
  const tavernObservationHandler = (step) => {
8208
+ if (!isCurrent()) return;
8108
8209
  const toolName = step.metadata?.toolName;
8109
8210
  let toolUseId;
8110
8211
  if (toolName) {
@@ -8130,6 +8231,7 @@ function wireAgentEvents(input) {
8130
8231
  });
8131
8232
  };
8132
8233
  const tavernFinalAnswerHandler = (step) => {
8234
+ if (!isCurrent()) return;
8133
8235
  const text = typeof step.content === "string" ? step.content : "";
8134
8236
  if (!text) return;
8135
8237
  bridgePresence.emitEvent({
@@ -8142,8 +8244,8 @@ function wireAgentEvents(input) {
8142
8244
  agent.on("observation", tavernObservationHandler);
8143
8245
  agent.on("final_answer", tavernFinalAnswerHandler);
8144
8246
  const subagentRunState = /* @__PURE__ */ new WeakMap();
8145
- let nextSubagentRunId = 0;
8146
8247
  orchestrator.setBeforeRunCallback((subagent, subagentType) => {
8248
+ if (!isCurrent()) return;
8147
8249
  subagent.on("thought", stepHandler);
8148
8250
  subagent.on("observation", stepHandler);
8149
8251
  subagent.on("action", stepHandler);
@@ -8152,6 +8254,7 @@ function wireAgentEvents(input) {
8152
8254
  subagent.on("final_answer", tavernFinalAnswerHandler);
8153
8255
  const runId = `run-${nextSubagentRunId++}`;
8154
8256
  const usageHandler = () => {
8257
+ if (!isCurrent()) return;
8155
8258
  useCliStore.getState().updateLiveSubagentUsage(runId, subagentType, subagent.getTokenUsage(), subagent.getCreditsUsage());
8156
8259
  };
8157
8260
  subagentRunState.set(subagent, {
@@ -8180,6 +8283,72 @@ function wireAgentEvents(input) {
8180
8283
  }
8181
8284
  });
8182
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
+ }
8183
8352
  const infoCommands = [
8184
8353
  {
8185
8354
  name: "help",
@@ -8329,17 +8498,17 @@ Multi-line Input:
8329
8498
  */
8330
8499
  function printDecisions(store) {
8331
8500
  console.log("\n📋 Decision Log\n");
8332
- console.log(formatDecisionsOutput(store.decisions));
8501
+ console.log(sanitizeTerminalText(formatDecisionsOutput(store.decisions)));
8333
8502
  console.log("");
8334
8503
  }
8335
8504
  function printBlockers(store) {
8336
8505
  console.log("\n🚧 Blockers\n");
8337
- console.log(formatBlockersOutput(store.blockers));
8506
+ console.log(sanitizeTerminalText(formatBlockersOutput(store.blockers)));
8338
8507
  console.log("");
8339
8508
  }
8340
8509
  function printReviewGates(store) {
8341
8510
  console.log("\n🛑 Review Gates\n");
8342
- console.log(formatReviewGatesOutput(store.reviewGates));
8511
+ console.log(sanitizeTerminalText(formatReviewGatesOutput(store.reviewGates)));
8343
8512
  console.log("");
8344
8513
  }
8345
8514
  const workflowViewCommands = [
@@ -8504,6 +8673,7 @@ async function runTurn(message, ctx) {
8504
8673
  return;
8505
8674
  }
8506
8675
  store.setTurnInFlight(true);
8676
+ const generation = ctx.sessionGeneration?.();
8507
8677
  try {
8508
8678
  let next = message;
8509
8679
  while (next !== null) {
@@ -8516,6 +8686,10 @@ async function runTurn(message, ctx) {
8516
8686
  } finally {
8517
8687
  releaseSession();
8518
8688
  }
8689
+ if (ctx.sessionGeneration?.() !== generation) {
8690
+ useCliStore.getState().restoreQueueToInput();
8691
+ break;
8692
+ }
8519
8693
  const queued = useCliStore.getState().dequeueAllMessages();
8520
8694
  next = queued.length > 0 ? queued.join("\n\n") : null;
8521
8695
  }
@@ -8523,17 +8697,10 @@ async function runTurn(message, ctx) {
8523
8697
  useCliStore.getState().setTurnInFlight(false);
8524
8698
  }
8525
8699
  }
8526
- /** Not awaited by the steer drain, so a failed history write is logged rather than left as an unhandled rejection. */
8527
- async function recordSteerHistory(steers, commandHistoryStore, setCommandHistory) {
8528
- try {
8529
- for (const text of steers) await commandHistoryStore.add(text);
8530
- setCommandHistory(await commandHistoryStore.list());
8531
- } catch (error) {
8532
- logger.debug(`[STEER] History write failed: ${error instanceof Error ? error.message : String(error)}`);
8533
- }
8534
- }
8535
8700
  async function runHeldTurn(message, ctx) {
8536
- 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;
8537
8704
  const storeSession = useCliStore.getState().session;
8538
8705
  if (!agent || !storeSession) {
8539
8706
  console.error("❌ CLI failed to initialize. Try restarting b4m.\n");
@@ -8550,8 +8717,6 @@ async function runHeldTurn(message, ctx) {
8550
8717
  status: "running",
8551
8718
  text: message.slice(0, 240)
8552
8719
  });
8553
- await commandHistoryStore.add(message);
8554
- setCommandHistory(await commandHistoryStore.list());
8555
8720
  let activeSession = storeSession;
8556
8721
  if (config?.preferences.autoCompact !== false && activeSession.messages.length >= 6) {
8557
8722
  const tokenCounter = getTokenCounter().forModel(activeSession.model);
@@ -8579,20 +8744,24 @@ async function runHeldTurn(message, ctx) {
8579
8744
  maxIterations: 1,
8580
8745
  streamText: false
8581
8746
  });
8747
+ if (replaced()) return;
8582
8748
  const sessionToCompact = withFlushedWorkflowState(activeSession, workflowStores);
8583
8749
  await sessionStore.save(sessionToCompact);
8584
8750
  const newSession = createCompactedSession(sessionToCompact, result.finalAnswer, preservedMessages, !!(process.env.B4M_SESSION_ID || process.env.B4M_RESUME_ID));
8751
+ if (replaced()) return;
8585
8752
  await logger.initialize(newSession.id);
8753
+ if (replaced()) return;
8586
8754
  useCliStore.getState().setSession(newSession);
8587
8755
  useCliStore.getState().clearPendingMessages();
8588
8756
  console.log("✅ Auto-compacted. Continuing with your message...\n");
8589
8757
  activeSession = newSession;
8590
8758
  }
8591
8759
  } finally {
8592
- useCliStore.getState().setIsThinking(false);
8760
+ if (!replaced()) useCliStore.getState().setIsThinking(false);
8593
8761
  }
8594
8762
  }
8595
8763
  }
8764
+ if (replaced()) return;
8596
8765
  useCliStore.getState().setIsThinking(true);
8597
8766
  const abortController = new AbortController();
8598
8767
  setAbortController(abortController);
@@ -8619,6 +8788,7 @@ async function runHeldTurn(message, ctx) {
8619
8788
  metadata: { steps: [] }
8620
8789
  };
8621
8790
  pendingAssistantId = pendingAssistantMessage.id;
8791
+ if (replaced()) return;
8622
8792
  const sessionWithUserMessage = {
8623
8793
  ...activeSession,
8624
8794
  messages: [...activeSession.messages, userMessage],
@@ -8656,14 +8826,11 @@ async function runHeldTurn(message, ctx) {
8656
8826
  drainFeedback: async (phase) => {
8657
8827
  const diagnosticsFeedback = diagnostics ? await diagnostics.drain(DRAIN_BUDGET_MS[phase], abortController.signal) : null;
8658
8828
  const steered = deliverSteers(abortController.signal);
8659
- if (steered) {
8660
- for (const text of steered.steers) bridgePresence.emitEvent({
8661
- type: "message",
8662
- role: "user",
8663
- text: text.slice(0, 4e3)
8664
- });
8665
- recordSteerHistory(steered.steers, commandHistoryStore, setCommandHistory);
8666
- }
8829
+ if (steered) for (const text of steered.steers) bridgePresence.emitEvent({
8830
+ type: "message",
8831
+ role: "user",
8832
+ text: text.slice(0, 4e3)
8833
+ });
8667
8834
  return [steered?.feedback, diagnosticsFeedback].filter(Boolean).join("\n\n") || null;
8668
8835
  },
8669
8836
  onContextLimit: createReactiveCompactionHandler(agent, activeSession)
@@ -8694,6 +8861,7 @@ async function runHeldTurn(message, ctx) {
8694
8861
  ...isEarlyStop(result.completionInfo.finishReason) ? { earlyStopReason: result.completionInfo.finishReason } : {}
8695
8862
  }
8696
8863
  };
8864
+ if (replaced()) return;
8697
8865
  useCliStore.getState().completePendingMessage(0, finalAssistantMessage);
8698
8866
  const currentSession = useCliStore.getState().session;
8699
8867
  if (!currentSession) return;
@@ -8711,11 +8879,11 @@ async function runHeldTurn(message, ctx) {
8711
8879
  await sessionStore.save(updatedSession);
8712
8880
  } catch (error) {
8713
8881
  const stepsBeforeAbort = useCliStore.getState().pendingMessages.find((m) => m.id === pendingAssistantId)?.metadata?.steps;
8714
- useCliStore.getState().clearPendingMessages();
8882
+ if (!replaced()) useCliStore.getState().clearPendingMessages();
8715
8883
  if (error instanceof Error && error.name === "AbortError") {
8716
8884
  logger.debug("[ABORT] Operation aborted by user");
8717
8885
  const currentSession = useCliStore.getState().session;
8718
- if (currentSession) {
8886
+ if (currentSession && !replaced()) {
8719
8887
  const cancelMessage = {
8720
8888
  id: v4(),
8721
8889
  role: "assistant",
@@ -8749,12 +8917,14 @@ async function runHeldTurn(message, ctx) {
8749
8917
  logger.debug(`Full error details: ${error.stack || error.message}`);
8750
8918
  return;
8751
8919
  }
8752
- console.error(`\n❌ ${rawMessage}\n`);
8920
+ console.error(`\n\u274C ${sanitizeTerminalText(rawMessage)}\n`);
8753
8921
  logger.debug(`Full error details: ${error instanceof Error ? error.stack || error.message : String(error)}`);
8754
8922
  } finally {
8755
8923
  const wasAborted = abortController.signal.aborted;
8756
- setAbortController(null);
8757
- useCliStore.getState().setIsThinking(false);
8924
+ if (!replaced()) {
8925
+ setAbortController(null);
8926
+ useCliStore.getState().setIsThinking(false);
8927
+ }
8758
8928
  getProcessHooks()?.fireStop();
8759
8929
  bridgePresence.emitEvent({
8760
8930
  type: "status",
@@ -8763,6 +8933,135 @@ async function runHeldTurn(message, ctx) {
8763
8933
  }
8764
8934
  }
8765
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
8766
9065
  //#region src/session/lifecycle.ts
8767
9066
  /**
8768
9067
  * Session lifecycle (issue #228, phase 3).
@@ -8856,7 +9155,7 @@ async function createFreshSession(ctx) {
8856
9155
  async function resumeSession(ctx, selected) {
8857
9156
  const loadedSession = await ctx.sessionStore.load(selected.id);
8858
9157
  if (!loadedSession) {
8859
- console.log(`❌ Failed to load session: ${selected.name}`);
9158
+ console.log(`\u274C Failed to load session: ${sanitizeTerminalText(selected.name)}`);
8860
9159
  console.log(" The session file may be corrupted or deleted.");
8861
9160
  return null;
8862
9161
  }
@@ -8872,7 +9171,7 @@ async function resumeSession(ctx, selected) {
8872
9171
  useCliStore.getState().setSession(sessionForState);
8873
9172
  useCliStore.getState().clearPendingMessages();
8874
9173
  ctx.onSessionReplaced();
8875
- console.log(`\n✅ Session resumed: "${sessionForState.name}"`);
9174
+ console.log(`\n\u2705 Session resumed: "${sanitizeTerminalText(sessionForState.name)}"`);
8876
9175
  console.log(`📝 ${sessionForState.messages.length} messages | 🤖 ${sessionForState.model} | 📊 ${sessionForState.metadata.totalTokens.toLocaleString()} tokens\n`);
8877
9176
  if (handoff) {
8878
9177
  console.log("🤝 Session handoff:\n");
@@ -8927,8 +9226,8 @@ async function compactHeldSession(ctx, options) {
8927
9226
  useCliStore.getState().clearPendingMessages();
8928
9227
  ctx.onSessionReplaced();
8929
9228
  console.log("✅ Conversation compacted");
8930
- console.log(`\u{1F4DD} New session: ${newSession.name}`);
8931
- 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`);
8932
9231
  } finally {
8933
9232
  useCliStore.getState().setIsThinking(false);
8934
9233
  }
@@ -9066,7 +9365,7 @@ function renderBanner(startupLog = []) {
9066
9365
  const right = startupLog[i] || "";
9067
9366
  const coloredLeft = leftText ? `${leftAnsi}${leftText}\x1b[0m` : "";
9068
9367
  const gap = " ".repeat(bannerWidth - leftText.length + 2);
9069
- console.log(coloredLeft + gap + truncate(right, rightColWidth));
9368
+ console.log(coloredLeft + gap + truncate(sanitizeTerminalText(right), rightColWidth));
9070
9369
  }
9071
9370
  }
9072
9371
  let exitTimestamp = null;
@@ -9105,7 +9404,8 @@ function CliApp() {
9105
9404
  checkpointStore: null,
9106
9405
  additionalDirectories: [],
9107
9406
  featureRegistry: null,
9108
- pluginDescriptors: []
9407
+ pluginDescriptors: [],
9408
+ signedOutLocal: false
9109
9409
  });
9110
9410
  const [isInitialized, setIsInitialized] = useState(false);
9111
9411
  const [initError, setInitError] = useState(null);
@@ -9113,6 +9413,8 @@ function CliApp() {
9113
9413
  const imageStoreInitPromise = useRef(null);
9114
9414
  const folderTrustResolvedRef = useRef(false);
9115
9415
  const mcpApprovalResolvedRef = useRef(false);
9416
+ const detectedOllamaRef = useRef(null);
9417
+ const initGenerationRef = useRef(0);
9116
9418
  const todoStoreRef = useRef(createTodoStore());
9117
9419
  const decisionStoreRef = useRef(createDecisionStore());
9118
9420
  const blockerStoreRef = useRef(createBlockerStore());
@@ -9127,46 +9429,44 @@ function CliApp() {
9127
9429
  const setShowConfigEditor = useCliStore((state) => state.setShowConfigEditor);
9128
9430
  const setShowMcpViewer = useCliStore((state) => state.setShowMcpViewer);
9129
9431
  const setExitRequested = useCliStore((state) => state.setExitRequested);
9130
- const performCleanup = useCallback(async () => {
9131
- const cleanupTasks = [];
9132
- try {
9133
- getShellSessionManager().killAll();
9134
- } catch (err) {
9135
- logger.debug(`[CLEANUP] Shell session reap error: ${err}`);
9136
- }
9137
- killRunningBangCommands();
9432
+ const sessionResources = (reason) => {
9138
9433
  const session = useCliStore.getState().session;
9139
- if (session) cleanupTasks.push(state.sessionStore.save(session).catch((err) => {
9140
- logger.debug(`[CLEANUP] Session save error: ${err.message}`);
9141
- }));
9142
- if (state.mcpManager) cleanupTasks.push(state.mcpManager.disconnect().catch((err) => {
9143
- logger.debug(`[CLEANUP] MCP disconnect error: ${err.message}`);
9144
- }));
9145
- if (state.featureRegistry) state.featureRegistry.disposeAll();
9146
- if (state.wsManager) {
9147
- state.wsManager.disconnect();
9148
- setWebSocketToolExecutor(null);
9149
- }
9150
- cleanupTasks.push(bridgePresence.stop("cli_exit").catch((err) => {
9151
- logger.debug(`[CLEANUP] Bridge presence stop error: ${err.message}`);
9152
- }));
9153
- if (state.agent) state.agent.removeAllListeners();
9154
- if (state.imageStore) try {
9155
- state.imageStore.close();
9156
- } catch (err) {
9157
- logger.debug(`[CLEANUP] Image store close error: ${err}`);
9158
- }
9159
- 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();
9160
9458
  setTimeout(() => {
9161
9459
  process.exit(0);
9162
9460
  }, 100);
9163
9461
  }, [
9164
9462
  state.sessionStore,
9463
+ state.commandHistoryStore,
9165
9464
  state.mcpManager,
9166
9465
  state.agent,
9167
9466
  state.imageStore,
9168
9467
  state.wsManager,
9169
- state.featureRegistry
9468
+ state.featureRegistry,
9469
+ state.backgroundManager
9170
9470
  ]);
9171
9471
  useEffect(() => {
9172
9472
  return getShellSessionManager().subscribe((session) => {
@@ -9175,6 +9475,7 @@ function CliApp() {
9175
9475
  }, []);
9176
9476
  useInput((input, key) => {
9177
9477
  if (key.escape) {
9478
+ if (state.showLoginFlow || state.showEnvironmentPicker) return;
9178
9479
  const store = useCliStore.getState();
9179
9480
  if (store.pastedContent) {
9180
9481
  store.clearPaste();
@@ -9221,7 +9522,19 @@ function CliApp() {
9221
9522
  try {
9222
9523
  const startupLog = [];
9223
9524
  const config = await state.configStore.load();
9224
- 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") {
9225
9538
  folderTrustResolvedRef.current = true;
9226
9539
  setState((prev) => ({
9227
9540
  ...prev,
@@ -9231,7 +9544,12 @@ function CliApp() {
9231
9544
  return;
9232
9545
  }
9233
9546
  const pendingMcp = state.configStore.getPendingMcpApprovals();
9234
- 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
+ })) {
9235
9553
  mcpApprovalResolvedRef.current = true;
9236
9554
  setState((prev) => ({
9237
9555
  ...prev,
@@ -9256,10 +9574,78 @@ function CliApp() {
9256
9574
  console.warn("Failed to load custom commands:", error instanceof Error ? error.message : String(error));
9257
9575
  }
9258
9576
  const authTokens = await state.configStore.getAuthTokens();
9259
- const tokenExpired = authTokens ? new Date(authTokens.expiresAt) <= /* @__PURE__ */ new Date() : false;
9260
- 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`);
9261
9643
  const endpoint = resolveApiEndpoint(config.apiConfig);
9262
- if (endpoint.status === "unconfigured") {
9644
+ if (signInStart({
9645
+ endpoint,
9646
+ endpointChosen: !!config.apiConfig?.endpointChosen,
9647
+ hasAuthTokens: !!authTokens
9648
+ }) === "endpoint-picker") {
9263
9649
  setState((prev) => ({
9264
9650
  ...prev,
9265
9651
  showEnvironmentPicker: true,
@@ -9267,11 +9653,10 @@ function CliApp() {
9267
9653
  }));
9268
9654
  return;
9269
9655
  }
9270
- if (tokenExpired) {
9271
- console.log("\n🔐 Your session has expired. Let's re-authenticate.\n");
9272
- await state.configStore.clearAuthTokens();
9273
- } else console.log("\n🔐 Welcome to B4M CLI! Authentication is required to get started.\n");
9274
- 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.
9275
9660
  `);
9276
9661
  setState((prev) => ({
9277
9662
  ...prev,
@@ -9280,30 +9665,8 @@ function CliApp() {
9280
9665
  }));
9281
9666
  return;
9282
9667
  }
9283
- const expiresAt = new Date(authTokens.expiresAt);
9284
- const daysUntilExpiry = Math.floor((expiresAt.getTime() - Date.now()) / 864e5);
9285
- startupLog.push(`✅ Authenticated (expires in ${daysUntilExpiry} day${daysUntilExpiry !== 1 ? "s" : ""})`);
9286
- const apiBaseURL = requireApiUrl(config.apiConfig);
9287
- const envName = getEnvironmentName(config.apiConfig);
9288
- startupLog.unshift(`🌍 API Environment: ${envName} (${apiBaseURL})`);
9289
- const apiClient = new ApiClient(apiBaseURL, state.configStore);
9290
- if (process.env.B4M_NO_REMOTE_SKILLS !== "1" && config.preferences.enableRemoteSkills !== false) try {
9291
- state.customCommandStore.setRemoteSource(new RemoteSkillSource(apiClient));
9292
- await state.customCommandStore.mergeRemoteCommands();
9293
- const remoteCount = state.customCommandStore.getCommandsBySource("remote").length;
9294
- if (remoteCount > 0) startupLog.push(`☁️ Synced ${remoteCount} skill${remoteCount === 1 ? "" : "s"} from B4M web`);
9295
- } catch (error) {
9296
- console.warn("Failed to sync remote skills:", error instanceof Error ? error.message : String(error));
9297
- }
9298
- const tokenGetter = async () => {
9299
- return (await state.configStore.getAuthTokens())?.accessToken ?? null;
9300
- };
9301
- const { llm, wsManager, models, modelInfo } = await buildLlmBackend({
9302
- config,
9303
- apiClient,
9304
- tokenGetter,
9305
- startupLog
9306
- });
9668
+ const { llm, wsManager, models, modelInfo, detectedOllama } = backend;
9669
+ detectedOllamaRef.current = detectedOllama;
9307
9670
  const pinnedSessionId = process.env.B4M_SESSION_ID;
9308
9671
  const resumeSessionId = process.env.B4M_RESUME_ID;
9309
9672
  if (pinnedSessionId && !isValidSessionId(pinnedSessionId)) {
@@ -9356,17 +9719,22 @@ function CliApp() {
9356
9719
  checkpointStore
9357
9720
  });
9358
9721
  let permissionPromptCounter = 0;
9359
- const promptFn = (toolName, args, preview, kind) => {
9722
+ const promptFn = (toolName, args, preview, kind, options) => {
9360
9723
  return new Promise((resolve) => {
9724
+ if (sessionEnded()) {
9725
+ resolve({ action: "deny" });
9726
+ return;
9727
+ }
9361
9728
  getProcessHooks()?.fireNotificationPermissionPrompt(toolName);
9362
9729
  const canBeTrusted = permissionManager.canBeTrusted(toolName);
9363
- const id = `perm-${++permissionPromptCounter}`;
9730
+ const id = `perm-${generation}-${++permissionPromptCounter}`;
9364
9731
  const prompt = {
9365
9732
  id,
9366
9733
  toolName,
9367
9734
  args,
9368
9735
  preview,
9369
9736
  canBeTrusted,
9737
+ sessionScope: options?.sessionScope,
9370
9738
  kind,
9371
9739
  resolve
9372
9740
  };
@@ -9398,7 +9766,11 @@ function CliApp() {
9398
9766
  let userQuestionCounter = 0;
9399
9767
  const userQuestionFn = (payload) => {
9400
9768
  return new Promise((resolve) => {
9401
- const id = `uq-${++userQuestionCounter}`;
9769
+ if (sessionEnded()) {
9770
+ resolve({ answers: [] });
9771
+ return;
9772
+ }
9773
+ const id = `uq-${generation}-${++userQuestionCounter}`;
9402
9774
  enqueueUserQuestionPrompt({
9403
9775
  id,
9404
9776
  payload,
@@ -9413,6 +9785,13 @@ function CliApp() {
9413
9785
  };
9414
9786
  const reviewGateFn = (params) => {
9415
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
+ }
9416
9795
  enqueueReviewGatePrompt({
9417
9796
  id: params.id,
9418
9797
  description: params.description,
@@ -9447,20 +9826,8 @@ function CliApp() {
9447
9826
  userQuestionFn,
9448
9827
  startupLog,
9449
9828
  silentLogger,
9450
- onBackgroundStatusChange: (job) => {
9451
- useCliStore.getState().upsertBackgroundAgent(job);
9452
- },
9453
- onGroupCompletion: (notification, groupDescription) => {
9454
- useCliStore.getState().addCompletedGroupNotification(notification, groupDescription);
9455
- useCliStore.getState().setPendingBackgroundTrigger(true);
9456
- },
9457
- onSubagentUsage: (usage) => {
9458
- useCliStore.getState().recordSubagentUsage({
9459
- agentName: usage.agentName,
9460
- tokens: usage.totalTokens,
9461
- credits: usage.totalCredits
9462
- });
9463
- }
9829
+ isCancelled: sessionEnded,
9830
+ ...sessionBackgroundCallbacks(() => !sessionEnded())
9464
9831
  });
9465
9832
  const agentDelegateTool = createAgentDelegateTool(orchestrator, agentStore, newSession.id, backgroundManager);
9466
9833
  const dynamicAgentTool = config.preferences.enableDynamicAgentCreation === true ? createDynamicAgentTool(orchestrator, newSession.id, backgroundManager) : null;
@@ -9500,7 +9867,8 @@ function CliApp() {
9500
9867
  configStore: state.configStore,
9501
9868
  apiClient,
9502
9869
  sandboxOrchestrator: sandboxOrchestrator ?? void 0,
9503
- allowedDirectories: additionalDirectories
9870
+ allowedDirectories: additionalDirectories,
9871
+ isCancelled: sessionEnded
9504
9872
  };
9505
9873
  const enableSkillTool = config.preferences.enableSkillTool !== false;
9506
9874
  const skillTool = enableSkillTool ? createSkillTool({
@@ -9509,11 +9877,12 @@ function CliApp() {
9509
9877
  sessionId: newSession.id,
9510
9878
  permission: {
9511
9879
  permissionManager,
9512
- promptFn
9880
+ promptFn,
9881
+ isCancelled: sessionEnded
9513
9882
  },
9514
9883
  allowedDirectories: additionalDirectories
9515
9884
  }) : null;
9516
- const workItemTools = config.preferences.enableWorkItemTools ? createWorkItemTools(new WorkItemsClient(apiClient)) : [];
9885
+ const workItemTools = config.preferences.enableWorkItemTools && !apiClient.signedOut ? createWorkItemTools(new WorkItemsClient(apiClient)) : [];
9517
9886
  const cliTools = buildCliToolList({
9518
9887
  toolSearchTool,
9519
9888
  agentDelegateTool,
@@ -9593,7 +9962,8 @@ function CliApp() {
9593
9962
  });
9594
9963
  wireAgentEvents({
9595
9964
  agent,
9596
- orchestrator
9965
+ orchestrator,
9966
+ isCurrent: () => !sessionEnded()
9597
9967
  });
9598
9968
  setState((prev) => ({
9599
9969
  ...prev,
@@ -9601,7 +9971,7 @@ function CliApp() {
9601
9971
  mcpManager,
9602
9972
  permissionManager,
9603
9973
  config,
9604
- availableModels: models,
9974
+ availableModels: liveModels.current ?? models,
9605
9975
  orchestrator,
9606
9976
  agentStore,
9607
9977
  contextContent: contextResult.mergedContent,
@@ -9611,7 +9981,8 @@ function CliApp() {
9611
9981
  checkpointStore,
9612
9982
  additionalDirectories,
9613
9983
  featureRegistry,
9614
- pluginDescriptors
9984
+ pluginDescriptors,
9985
+ signedOutLocal: apiClient.signedOut
9615
9986
  }));
9616
9987
  setStoreSession(newSession);
9617
9988
  renderBanner(startupLog);
@@ -9686,7 +10057,7 @@ function CliApp() {
9686
10057
  status: "running"
9687
10058
  });
9688
10059
  };
9689
- const tavernPresenceEnabled = state.config?.features?.tavern ?? false;
10060
+ const tavernPresenceEnabled = (state.config?.features?.tavern ?? false) && !state.signedOutLocal;
9690
10061
  useEffect(() => {
9691
10062
  if (!isInitialized) return;
9692
10063
  if (!tavernPresenceEnabled) {
@@ -9727,6 +10098,8 @@ function CliApp() {
9727
10098
  console.error("❌ CLI failed to initialize. Try restarting b4m.\n");
9728
10099
  return;
9729
10100
  }
10101
+ const generation = initGenerationRef.current;
10102
+ const replaced = () => initGenerationRef.current !== generation;
9730
10103
  useCliStore.getState().setIsThinking(true);
9731
10104
  const releaseSession = useCliStore.getState().holdSession();
9732
10105
  const abortController = new AbortController();
@@ -9738,7 +10111,7 @@ function CliApp() {
9738
10111
  const stepHandler = (step) => {
9739
10112
  currentSteps.push(step);
9740
10113
  const currentSession = useCliStore.getState().session;
9741
- if (currentSession) {
10114
+ if (currentSession && !replaced()) {
9742
10115
  const messages = [...currentSession.messages];
9743
10116
  const lastMessage = messages[messages.length - 1];
9744
10117
  if (lastMessage && lastMessage.role === "assistant") {
@@ -9778,6 +10151,7 @@ function CliApp() {
9778
10151
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9779
10152
  metadata: { steps: [] }
9780
10153
  };
10154
+ if (replaced()) return;
9781
10155
  const sessionWithMessages = {
9782
10156
  ...session,
9783
10157
  messages: [
@@ -9812,7 +10186,7 @@ function CliApp() {
9812
10186
  if (permissionDenied) console.log("\n⚠️ Action denied by user\n");
9813
10187
  const successfulToolCalls = result.steps.filter((s) => s.type === "observation").length;
9814
10188
  const currentSession = useCliStore.getState().session;
9815
- if (!currentSession) return;
10189
+ if (!currentSession || replaced()) return;
9816
10190
  const updatedMessages = [...currentSession.messages];
9817
10191
  const lastMessage = updatedMessages[updatedMessages.length - 1];
9818
10192
  const richContent = reconstructTurnBlocks(result.steps, result.finalAnswer);
@@ -9855,11 +10229,11 @@ function CliApp() {
9855
10229
  usageCache = null;
9856
10230
  useCliStore.getState().setIsThinking(false);
9857
10231
  } catch (error) {
9858
- useCliStore.getState().setIsThinking(false);
10232
+ if (!replaced()) useCliStore.getState().setIsThinking(false);
9859
10233
  if (error instanceof Error && error.name === "AbortError") {
9860
10234
  logger.debug("[ABORT] Custom command aborted by user");
9861
10235
  const currentSession = useCliStore.getState().session;
9862
- if (currentSession) {
10236
+ if (currentSession && !replaced()) {
9863
10237
  const messages = [...currentSession.messages];
9864
10238
  const lastMessage = messages[messages.length - 1];
9865
10239
  if (lastMessage && lastMessage.role === "assistant") messages[messages.length - 1] = {
@@ -9883,7 +10257,7 @@ function CliApp() {
9883
10257
  if (error?.message?.includes("Permission denied")) {
9884
10258
  console.log("\n⚠️ Action blocked by permission settings");
9885
10259
  const currentSession = useCliStore.getState().session;
9886
- if (!currentSession) return;
10260
+ if (!currentSession || replaced()) return;
9887
10261
  const sessionWithDenied = { ...currentSession };
9888
10262
  const messages = [...sessionWithDenied.messages];
9889
10263
  const lastMessage = messages[messages.length - 1];
@@ -9903,7 +10277,7 @@ function CliApp() {
9903
10277
  console.error("Error executing command:", error);
9904
10278
  console.error(error.stack);
9905
10279
  const currentSession = useCliStore.getState().session;
9906
- if (!currentSession) return;
10280
+ if (!currentSession || replaced()) return;
9907
10281
  const sessionWithError = { ...currentSession };
9908
10282
  const messages = [...sessionWithError.messages];
9909
10283
  const lastMessage = messages[messages.length - 1];
@@ -9914,10 +10288,10 @@ function CliApp() {
9914
10288
  sessionWithError.messages = messages;
9915
10289
  setStoreSession(sessionWithError);
9916
10290
  } finally {
9917
- setState((prev) => ({
10291
+ setState((prev) => prev.abortController === abortController ? {
9918
10292
  ...prev,
9919
10293
  abortController: null
9920
- }));
10294
+ } : prev);
9921
10295
  state.agent.off("thought", stepHandler);
9922
10296
  state.agent.off("action", stepHandler);
9923
10297
  releaseSession();
@@ -9927,7 +10301,6 @@ function CliApp() {
9927
10301
  agent: state.agent,
9928
10302
  sessionStore: state.sessionStore,
9929
10303
  configStore: state.configStore,
9930
- commandHistoryStore: state.commandHistoryStore,
9931
10304
  customCommandStore: state.customCommandStore,
9932
10305
  messageBuilder: state.messageBuilder,
9933
10306
  config: state.config,
@@ -9947,11 +10320,11 @@ function CliApp() {
9947
10320
  blockerStore: blockerStoreRef.current,
9948
10321
  reviewGateStore: reviewGateStoreRef.current
9949
10322
  },
9950
- setCommandHistory,
9951
10323
  setAbortController: (controller) => setState((prev) => ({
9952
10324
  ...prev,
9953
10325
  abortController: controller
9954
- }))
10326
+ })),
10327
+ sessionGeneration: () => initGenerationRef.current
9955
10328
  });
9956
10329
  handleMessageRef.current = handleMessage;
9957
10330
  const buildLifecycleContext = () => ({
@@ -9974,10 +10347,14 @@ function CliApp() {
9974
10347
  * without adding a user message to the conversation.
9975
10348
  */
9976
10349
  const handleBackgroundCompletion = async () => {
9977
- const authTokens = await state.configStore.getAuthTokens();
9978
- 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
+ }
9979
10354
  const session = useCliStore.getState().session;
9980
10355
  if (!state.agent || !session) return;
10356
+ const startedGeneration = initGenerationRef.current;
10357
+ const stillThisSession = () => initGenerationRef.current === startedGeneration && useCliStore.getState().session?.id === session.id;
9981
10358
  useCliStore.getState().setIsThinking(true);
9982
10359
  const releaseSession = useCliStore.getState().holdSession();
9983
10360
  const abortController = new AbortController();
@@ -9985,9 +10362,10 @@ function CliApp() {
9985
10362
  ...prev,
9986
10363
  abortController
9987
10364
  }));
10365
+ const pendingId = v4();
9988
10366
  try {
9989
10367
  const pendingAssistantMessage = {
9990
- id: v4(),
10368
+ id: pendingId,
9991
10369
  role: "assistant",
9992
10370
  content: "...",
9993
10371
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -10009,7 +10387,7 @@ function CliApp() {
10009
10387
  });
10010
10388
  const successfulToolCalls = result.steps.filter((s) => s.type === "observation").length;
10011
10389
  const currentSession = useCliStore.getState().session;
10012
- if (!currentSession) return;
10390
+ if (!currentSession || !stillThisSession()) return;
10013
10391
  const richContent = reconstructTurnBlocks(result.steps, result.finalAnswer);
10014
10392
  const continuationMessage = {
10015
10393
  id: v4(),
@@ -10043,15 +10421,17 @@ function CliApp() {
10043
10421
  setStoreSession(updatedSession);
10044
10422
  await state.sessionStore.save(updatedSession);
10045
10423
  } catch (error) {
10424
+ if (!stillThisSession()) return;
10046
10425
  useCliStore.getState().clearPendingMessages();
10047
10426
  if (error instanceof Error && error.name === "AbortError") return;
10048
10427
  console.error("Error processing background results:", error);
10049
10428
  } finally {
10050
- setState((prev) => ({
10429
+ if (stillThisSession() || abortControllerRef.current === abortController) useCliStore.getState().setIsThinking(false);
10430
+ setState((prev) => prev.abortController === abortController ? {
10051
10431
  ...prev,
10052
10432
  abortController: null
10053
- }));
10054
- useCliStore.getState().setIsThinking(false);
10433
+ } : prev);
10434
+ if (!stillThisSession()) useCliStore.setState((prev) => ({ pendingMessages: prev.pendingMessages.filter((m) => m.id !== pendingId) }));
10055
10435
  releaseSession();
10056
10436
  }
10057
10437
  };
@@ -10152,8 +10532,9 @@ function CliApp() {
10152
10532
  const nameWidth = 25;
10153
10533
  const maxDescLength = Math.max(20, terminalWidth - 30);
10154
10534
  agents.forEach((agent) => {
10155
- const desc = agent.description.length > maxDescLength ? agent.description.slice(0, maxDescLength - 3) + "..." : agent.description;
10156
- 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}`);
10157
10538
  });
10158
10539
  console.log("");
10159
10540
  }
@@ -10400,7 +10781,7 @@ function CliApp() {
10400
10781
  if (result.filePath) console.log(`\n📄 Handoff written to ${result.filePath}`);
10401
10782
  console.log(fellBack ? "✅ Session saved with local fallback handoff" : "✅ Session saved with refreshed handoff");
10402
10783
  };
10403
- const handleCommand = async (command, args) => {
10784
+ const runCommand = async (command, args) => {
10404
10785
  const customCommand = state.customCommandStore.getModelReachableCommand(command);
10405
10786
  if (customCommand) try {
10406
10787
  const sourceIcon = customCommand.source === "global" ? "🏠" : "📁";
@@ -10408,18 +10789,18 @@ function CliApp() {
10408
10789
  let substitutedBody = substituteArguments(customCommand.body, args);
10409
10790
  const processed = await processFileReferences(substitutedBody);
10410
10791
  substitutedBody = processed.content;
10411
- if (processed.errors.length > 0) processed.errors.forEach((error) => console.warn(`Warning: ${error}`));
10412
- 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));
10413
10794
  const displayMessage = `/${command}${args.length > 0 ? " " + args.join(" ") : ""}`;
10414
10795
  if (customCommand.agent && state.orchestrator && state.agentStore) {
10415
10796
  const { name: agentName } = parseAgentConfig(customCommand.agent);
10416
10797
  if (!state.agentStore.hasAgent(agentName)) {
10417
10798
  const available = state.agentStore.getAgentNames().join(", ");
10418
- console.error(`❌ Unknown agent "${agentName}" specified in command.`);
10419
- console.error(` Available agents: ${available}`);
10799
+ console.error(`❌ Unknown agent "${sanitizeTerminalText(agentName)}" specified in command.`);
10800
+ console.error(` Available agents: ${sanitizeTerminalText(available)}`);
10420
10801
  return;
10421
10802
  }
10422
- console.log(`🤖 Delegating to ${agentName} agent...\n`);
10803
+ console.log(`🤖 Delegating to ${sanitizeTerminalText(agentName)} agent...\n`);
10423
10804
  const result = await state.orchestrator.delegateToAgent({
10424
10805
  task: substitutedBody,
10425
10806
  agentName,
@@ -10427,11 +10808,11 @@ function CliApp() {
10427
10808
  variables: customCommand.variables,
10428
10809
  parentSessionId: useCliStore.getState().session?.id || "unknown"
10429
10810
  });
10430
- console.log("\n" + result.summary + "\n");
10811
+ console.log("\n" + sanitizeTerminalText(result.summary) + "\n");
10431
10812
  return;
10432
10813
  }
10433
10814
  if (customCommand.model && state.agent) {
10434
- console.log(`🔄 Using model override: ${customCommand.model}`);
10815
+ console.log(`🔄 Using model override: ${sanitizeTerminalText(customCommand.model)}`);
10435
10816
  await runWithModelOverride({
10436
10817
  applyModel: applyModelToSession,
10437
10818
  sessionStore: state.sessionStore
@@ -10454,6 +10835,11 @@ function CliApp() {
10454
10835
  reviewGateStore: reviewGateStoreRef.current,
10455
10836
  openConfigEditor: () => setShowConfigEditor(true)
10456
10837
  })) return;
10838
+ const signedOutRefusal = state.signedOutLocal ? signedOutCommandMessage(command) : null;
10839
+ if (signedOutRefusal) {
10840
+ console.log(`\n${signedOutRefusal}\n`);
10841
+ return;
10842
+ }
10457
10843
  switch (command) {
10458
10844
  case "exit":
10459
10845
  case "quit":
@@ -10536,8 +10922,7 @@ function CliApp() {
10536
10922
  return;
10537
10923
  }
10538
10924
  const { url } = result;
10539
- await state.configStore.setCustomApiUrl(url);
10540
- await state.configStore.clearAuthTokens();
10925
+ await state.configStore.withRefreshLock(() => state.configStore.setCustomApiUrlSignedOut(url));
10541
10926
  console.log(`\n✅ API URL updated: ${url}`);
10542
10927
  console.log("🔓 Authentication cleared");
10543
10928
  console.log(`💡 Run /login to authenticate with ${url}`);
@@ -10545,8 +10930,7 @@ function CliApp() {
10545
10930
  break;
10546
10931
  }
10547
10932
  case "reset-api": {
10548
- await state.configStore.setCustomApiUrl(null);
10549
- await state.configStore.clearAuthTokens();
10933
+ await state.configStore.withRefreshLock(() => state.configStore.setCustomApiUrlSignedOut(null));
10550
10934
  const resetEndpoint = resolveApiEndpoint();
10551
10935
  console.log("\n✅ Custom API URL cleared");
10552
10936
  console.log("🔓 Authentication cleared");
@@ -10695,29 +11079,37 @@ function CliApp() {
10695
11079
  console.log(`✅ Tool '${toolToUntrust}' removed from trusted list`);
10696
11080
  break;
10697
11081
  }
10698
- 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
+ });
10699
11097
  setState((prev) => ({
10700
11098
  ...prev,
10701
- showLoginFlow: true
11099
+ config: loginConfig,
11100
+ ...start === "endpoint-picker" ? { showEnvironmentPicker: true } : { showLoginFlow: true }
10702
11101
  }));
10703
11102
  break;
11103
+ }
10704
11104
  case "logout":
10705
11105
  usageCache = null;
10706
- await state.configStore.clearAuthTokens();
11106
+ await state.configStore.withRefreshLock(() => state.configStore.clearAuthTokens());
10707
11107
  console.log("✅ Successfully logged out");
11108
+ if (!state.signedOutLocal) console.log(LOGGED_OUT_RESTART);
10708
11109
  break;
10709
11110
  case "whoami": {
10710
11111
  const authTokens = await state.configStore.getAuthTokens();
10711
- if (!authTokens) {
10712
- console.log("Not authenticated. Run /login to authenticate.");
10713
- return;
10714
- }
10715
- const isExpired = new Date(authTokens.expiresAt) <= /* @__PURE__ */ new Date();
10716
- console.log("\n👤 Current User:\n");
10717
- console.log(`User ID: ${authTokens.userId}`);
10718
- console.log(`Status: ${isExpired ? "⚠️ Token expired" : "✅ Authenticated"}`);
10719
- console.log(`Expires: ${new Date(authTokens.expiresAt).toLocaleString()}`);
10720
- console.log("");
11112
+ console.log(whoamiReport(authTokens, { signedOutLocal: state.signedOutLocal }));
10721
11113
  break;
10722
11114
  }
10723
11115
  case "clear":
@@ -10890,8 +11282,8 @@ function CliApp() {
10890
11282
  else if (error.response?.status === 403) console.log("\n❌ Access denied. You may not have permission to view usage data.\n");
10891
11283
  else if (error.response?.status === 404) console.log("\n❌ Usage endpoint not available on this server.\n");
10892
11284
  else if (error.code === "ECONNREFUSED" || error.code === "ENOTFOUND") console.log("\n❌ Cannot connect to server. Check your API configuration with /api-info\n");
10893
- else console.log(`\n❌ Error fetching usage data: ${error.message}\n`);
10894
- } 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`);
10895
11287
  else console.log("\n❌ Unexpected error fetching usage data. Please try again.\n");
10896
11288
  break;
10897
11289
  }
@@ -10992,7 +11384,7 @@ function CliApp() {
10992
11384
  if (mcpTools.length > 0) {
10993
11385
  console.log("\nMCP Tools (deferred):");
10994
11386
  console.log(` Schemas: load on demand via tool_search (${mcpTools.length} tools available)`);
10995
- for (const { serverName, count } of mcpToolCount) console.log(` ${serverName}: ${count} tools`);
11387
+ for (const { serverName, count } of mcpToolCount) console.log(` ${sanitizeTerminalText(serverName)}: ${count} tools`);
10996
11388
  }
10997
11389
  if (agentTools.length > 0) {
10998
11390
  console.log("\nLoaded Tool Schemas:");
@@ -11022,15 +11414,15 @@ function CliApp() {
11022
11414
  const localConfig = await state.configStore.loadRawProjectLocalConfig();
11023
11415
  if (projectConfig) {
11024
11416
  console.log("Team Config (.bike4mind/config.json):");
11025
- if (projectConfig.defaultModel) console.log(` Default Model: ${projectConfig.defaultModel}`);
11026
- if (projectConfig.tools?.denied && projectConfig.tools.denied.length > 0) console.log(` Denied Tools: ${projectConfig.tools.denied.join(", ")}`);
11027
- 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(", "))}`);
11028
11420
  console.log("");
11029
11421
  }
11030
11422
  if (localConfig) {
11031
11423
  console.log("Local Config (.bike4mind/local.json):");
11032
- if (localConfig.trustedTools && localConfig.trustedTools.length > 0) console.log(` Trusted Tools: ${localConfig.trustedTools.join(", ")}`);
11033
- 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(", "))}`);
11034
11426
  console.log("");
11035
11427
  }
11036
11428
  console.log("Merged Configuration (what you're using):");
@@ -11067,9 +11459,9 @@ function CliApp() {
11067
11459
  if (globalCommands.length > 0) {
11068
11460
  console.log("🏠 Global Commands (~/.bike4mind/commands/):");
11069
11461
  globalCommands.forEach((cmd) => {
11070
- const argHint = cmd.argumentHint ? ` ${cmd.argumentHint}` : "";
11071
- const prefix = ` /${cmd.name}${argHint}`;
11072
- 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);
11073
11465
  console.log(`${prefix} - ${desc}`);
11074
11466
  });
11075
11467
  console.log("");
@@ -11077,9 +11469,9 @@ function CliApp() {
11077
11469
  if (projectCommands.length > 0) {
11078
11470
  console.log("📁 Project Commands (.bike4mind/commands/):");
11079
11471
  projectCommands.forEach((cmd) => {
11080
- const argHint = cmd.argumentHint ? ` ${cmd.argumentHint}` : "";
11081
- const prefix = ` /${cmd.name}${argHint}`;
11082
- 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);
11083
11475
  console.log(`${prefix} - ${desc}`);
11084
11476
  });
11085
11477
  console.log("");
@@ -11396,9 +11788,9 @@ function CliApp() {
11396
11788
  const time = new Date(v.timestamp).toLocaleTimeString();
11397
11789
  const typeColor = v.type === "filesystem" ? "\x1B[33m" : "\x1B[36m";
11398
11790
  const typeLabel = v.type === "filesystem" ? "FS " : "NET";
11399
- const target = v.path ?? v.domain ?? "";
11400
- console.log(` ${typeColor}${typeLabel}\x1b[0m ${time} \x1b[90m${v.blockedBy}\x1b[0m ${target}`);
11401
- 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`);
11402
11794
  }
11403
11795
  console.log("");
11404
11796
  break;
@@ -11432,7 +11824,7 @@ function CliApp() {
11432
11824
  }));
11433
11825
  break;
11434
11826
  case "no-match":
11435
- 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.`);
11436
11828
  break;
11437
11829
  case "ambiguous":
11438
11830
  console.log(`"${args.join(" ")}" matches ${result.models.length} models - be more specific:`);
@@ -11451,6 +11843,7 @@ function CliApp() {
11451
11843
  console.log("Type /help for available commands");
11452
11844
  }
11453
11845
  };
11846
+ const handleCommand = reportCommandErrors(runCommand, (message) => console.error(message));
11454
11847
  /**
11455
11848
  * Handle saving config from the interactive editor
11456
11849
  */
@@ -11462,7 +11855,7 @@ function CliApp() {
11462
11855
  let newFeatureRegistry = state.featureRegistry;
11463
11856
  if (featuresChanged && state.agent) {
11464
11857
  state.featureRegistry?.disposeAll();
11465
- 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);
11466
11859
  const oldFeatureToolNames = new Set(state.featureRegistry?.getAllToolNames() ?? []);
11467
11860
  const baseTools = state.agent.getTools().filter((t) => !oldFeatureToolNames.has(t.toolSchema.name));
11468
11861
  const rebuilt = await buildFeatureRegistry({
@@ -11479,7 +11872,7 @@ function CliApp() {
11479
11872
  const rebuiltRegistry = rebuilt.registry;
11480
11873
  newFeatureRegistry = rebuiltRegistry;
11481
11874
  rewireReservedNames(state, rebuiltRegistry);
11482
- 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`);
11483
11876
  if (state.wsManager && newFeatureRegistry.hasModules) newFeatureRegistry.registerAllWsHandlers(state.wsManager);
11484
11877
  const newFeatureTools = newFeatureRegistry.getAllTools();
11485
11878
  state.agent.setTools([...baseTools, ...newFeatureTools]);
@@ -11547,12 +11940,16 @@ function CliApp() {
11547
11940
  isBusy: () => useCliStore.getState().isThinking,
11548
11941
  saveModel: async (modelId) => {
11549
11942
  if (!state.config) throw new Error("no CLI config is loaded");
11550
- 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);
11551
11948
  setState((prev) => prev.config ? {
11552
11949
  ...prev,
11553
11950
  config: {
11554
11951
  ...prev.config,
11555
- defaultModel: modelId
11952
+ ...patch
11556
11953
  }
11557
11954
  } : prev);
11558
11955
  },
@@ -11588,6 +11985,8 @@ function CliApp() {
11588
11985
  await state.configStore.trustProject();
11589
11986
  console.log("\n✅ Folder trusted. Loading its config, agents, skills and MCP servers.\n");
11590
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.`);
11591
11990
  } finally {
11592
11991
  setState((prev) => ({
11593
11992
  ...prev,
@@ -11672,29 +12071,47 @@ function CliApp() {
11672
12071
  }))
11673
12072
  });
11674
12073
  }
11675
- if (state.showEnvironmentPicker) return /* @__PURE__ */ React.createElement(EnvironmentPicker, { onSelect: (choice) => {
11676
- (async () => {
11677
- try {
11678
- const result = await state.configStore.switchApiEnvironment(choice.target);
11679
- setState((prev) => ({
11680
- ...prev,
11681
- showEnvironmentPicker: false
11682
- }));
11683
- console.log(`\n✅ Connecting to ${result.envName} (${result.url})\n`);
11684
- init().catch((err) => {
11685
- console.error("\n❌ Initialization failed:", err.message, "\n");
11686
- exit();
11687
- });
11688
- } 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 () => {
11689
12086
  setState((prev) => ({
11690
12087
  ...prev,
11691
12088
  showEnvironmentPicker: false
11692
12089
  }));
11693
- console.error(`\n❌ Failed to save endpoint: ${err instanceof Error ? err.message : String(err)}\n`);
11694
- exit();
11695
- }
11696
- })();
11697
- } });
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
+ });
11698
12115
  if (state.showLoginFlow) {
11699
12116
  const endpoint = resolveApiEndpoint(state.config?.apiConfig);
11700
12117
  if (endpoint.status === "unconfigured") return /* @__PURE__ */ React.createElement(Box, {
@@ -11709,8 +12126,21 @@ function CliApp() {
11709
12126
  ...prev,
11710
12127
  showLoginFlow: false
11711
12128
  }));
11712
- console.log("\n✅ Login successful! Initializing CLI...\n");
11713
- 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) => {
11714
12144
  console.error("\n❌ Initialization failed:", err.message, "\n");
11715
12145
  exit();
11716
12146
  });
@@ -11721,9 +12151,14 @@ function CliApp() {
11721
12151
  showLoginFlow: false
11722
12152
  }));
11723
12153
  console.error(`\n❌ Login failed: ${error.message}`);
12154
+ if (localSessionRunning) {
12155
+ console.log(`${LOCAL_SESSION_CONTINUES}\n`);
12156
+ return;
12157
+ }
11724
12158
  console.log("Run b4m again when you're ready to authenticate.\n");
11725
12159
  exit();
11726
- }
12160
+ },
12161
+ onCancel: backToLocalSession
11727
12162
  });
11728
12163
  }
11729
12164
  if (!isInitialized) return /* @__PURE__ */ React.createElement(Box, {
@@ -11742,6 +12177,7 @@ function CliApp() {
11742
12177
  onBashCommand: handleBashCommand,
11743
12178
  onImageDetected: handleImageDetected,
11744
12179
  commandHistory,
12180
+ onHistoryEntry: (entry) => setCommandHistory(state.commandHistoryStore.add(entry)),
11745
12181
  commands: allCommands,
11746
12182
  config: state.config,
11747
12183
  availableModels: state.availableModels,