@bike4mind/cli 4.8.0 → 4.10.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 (39) hide show
  1. package/README.md +21 -0
  2. package/bin/bike4mind-cli.mjs +342 -239
  3. package/dist/{AgentHistoryStore-Bvmcy2kf.mjs → AgentHistoryStore-CjGVgxLR.mjs} +305 -644
  4. package/dist/{ApiClient-Yp2LPlX3.mjs → ApiClient-SVXSI3HI.mjs} +3 -3
  5. package/dist/{BubblewrapRuntime-OI4qFPNB.mjs → BubblewrapRuntime-CTc_KPnd.mjs} +2 -2
  6. package/dist/{ConfigStore-CP1W86Ui.mjs → ConfigStore-B2Dy-PT9.mjs} +7 -8
  7. package/dist/ConfigStore-zlY0PikB.mjs +2 -0
  8. package/dist/{Logger-3RbeTZ9o.mjs → Logger-7MmrU5w6.mjs} +4845 -1126
  9. package/dist/{SandboxOrchestrator-lpxVEFO7.mjs → SandboxOrchestrator-CeDwd6Fj.mjs} +1 -1
  10. package/dist/{SandboxRuntimeAdapter-u6c_IrjP.mjs → SandboxRuntimeAdapter-CFEIywKt.mjs} +1 -1
  11. package/dist/{SandboxRuntimeAdapter-C3xICJtQ.mjs → SandboxRuntimeAdapter-CjNDzYSf.mjs} +2 -2
  12. package/dist/{SeatbeltRuntime-Ccd_QbjX.mjs → SeatbeltRuntime-CQItj-F1.mjs} +2 -2
  13. package/dist/{WorkItemsClient-D4sFGL9X.mjs → WorkItemsClient-C9_pjHCo.mjs} +3 -4
  14. package/dist/{buildToolSearch-CqHKSLtG.mjs → buildToolSearch-8xyBwXRx.mjs} +2 -2
  15. package/dist/commands/acpCommand.mjs +6 -7
  16. package/dist/commands/apiCommand.mjs +1 -1
  17. package/dist/commands/doctorCommand.mjs +2 -2
  18. package/dist/commands/envCommand.mjs +1 -1
  19. package/dist/commands/headlessCommand.mjs +10 -11
  20. package/dist/commands/hostCommand.mjs +1 -1
  21. package/dist/commands/mcpCommand.mjs +3 -3
  22. package/dist/commands/mirrorCommand.mjs +2 -2
  23. package/dist/commands/modelsCommand.mjs +4 -4
  24. package/dist/commands/pluginCommand.mjs +1 -1
  25. package/dist/commands/skillsCommand.mjs +3 -3
  26. package/dist/commands/updateCommand.mjs +2 -2
  27. package/dist/dist-DHgMhdzV.mjs +10138 -0
  28. package/dist/{fit-BOnDsgbk.mjs → fit-D8Quui6j.mjs} +3 -3
  29. package/dist/index.mjs +732 -69
  30. package/dist/{modelServers-B7zI5XnO.mjs → modelServers-JsKBm7Wn.mjs} +1 -1
  31. package/dist/{package-WlxLVpUb.mjs → package-r_xumsGY.mjs} +1 -1
  32. package/dist/{serve-DpsV0mag.mjs → serve-BM9PKMLH.mjs} +873 -60
  33. package/dist/{store-xeJRhBtO.mjs → store-CmOg7JIt.mjs} +2 -0
  34. package/dist/store-OGMXhD4A.mjs +2 -0
  35. package/dist/{updateChecker-Boq0RruU.mjs → updateChecker-BOqaLeZU.mjs} +1 -1
  36. package/package.json +12 -44
  37. package/dist/ConfigStore-Bo4od3Eu.mjs +0 -2
  38. package/dist/dist-BPhZ0dCz.mjs +0 -4776
  39. package/dist/store-Bpdo9Syo.mjs +0 -2
package/dist/index.mjs CHANGED
@@ -1,34 +1,35 @@
1
1
  #!/usr/bin/env node
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, gt as wrapTools, 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-Bvmcy2kf.mjs";
3
- import { a as selectLiveSubagentTokens, i as selectLiveSubagentCredits, n as selectActiveBackgroundShells, o as useCliStore, r as selectCompletedBackgroundShells, t as selectActiveBackgroundAgents } from "./store-xeJRhBtO.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-CP1W86Ui.mjs";
5
- import { a as extractErrorMessage$1 } from "./dist-BPhZ0dCz.mjs";
6
- import { C as CREDIT_DEDUCT_TRANSACTION_TYPES, Jt as actorColorIndex, Kt as ACTOR_COLOR_SLOTS, Q as SUBQUEST_STATUS_VALUES, Qt as selfClaimedActorKindSchema, T as ChatModels, Xt as actorKindSchema, Y as REVIEW_GATE_STATUS_VALUES, Yt as actorKindMarker, Zt as delegationPayloadSchema, _t as isEarlyStop, n as SESSION_ID_PATTERN, qt as DELEGATION_PAYLOAD_SCHEMA_NAME, r as isValidSessionId, t as logger, zt as tokenEstimateMultiplier } from "./Logger-3RbeTZ9o.mjs";
7
- import { a as rewireReservedNames, i as mergeCommands, t as RemoteSkillSource } from "./RemoteSkillSource-D_F99yBR.mjs";
2
+ import { $ as signInUncheckedMessage, A as FallbackLlmBackend, B as DEFAULT_THOROUGHNESS, C as resetTodoStore, D as createResumeAgentTool, E as createCoordinateTaskTool, G as SIGN_IN_DURING_TURN, H as LOGGED_OUT_RESTART, I as ALWAYS_DENIED_FOR_AGENTS, J as SIGN_IN_HINT, K as SIGN_IN_EXPIRED, L as DEFAULT_AGENT_MODEL, M as substituteArguments, N as PermissionManager, O as createBackgroundAgentTools, P as buildCliToolList, Q as signInUncheckedLoginMessage, R as DEFAULT_MAX_ITERATIONS, S as createWriteTodosTool, St as COMPACTION_SUMMARY_MARKER, T as parseAgentConfig, U as NoLocalModelsError, V as LOCAL_SESSION_CONTINUES, W as SIGNED_OUT_BANNER, X as loginBlocked, _t as CommandHistoryStore, b as createFindDefinitionTool, bt as searchFiles, c as checkSavedSignIn, ct as wrapTools, et as signedOutCommandMessage, f as buildLlmBackend, ft as getPlanModeFilePath, gt as CheckpointStore, ht as hasFileReferences, j as isConnectionDrop, k as createAgentDelegateTool, l as settleSignInRefresh, lt as getProcessHooks, mt as processFileReferences, nt as buildSystemPrompt, pt as CustomCommandStore, rt as buildSkillsPromptSection, s as buildSandbox, st as findIterationBoundary, tt as signedOutNoMatchMessage, u as startupMode, ut as setWebSocketToolExecutor, v as createGetFileStructureTool, vt as SessionStore, w as createSkillTool, wt as MAX_PASTE_SIZE, x as createTodoStore, xt as warmFileCache, y as createWorkItemTools, yt as formatFileSize, z as DEFAULT_RETRY_CONFIG } from "./AgentHistoryStore-CjGVgxLR.mjs";
3
+ 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-B2Dy-PT9.mjs";
4
+ import { a as selectLiveSubagentTokens, i as selectLiveSubagentCredits, n as selectActiveBackgroundShells, o as useCliStore, r as selectCompletedBackgroundShells, t as selectActiveBackgroundAgents } from "./store-CmOg7JIt.mjs";
5
+ import { a as extractErrorMessage$1 } from "./dist-DHgMhdzV.mjs";
6
+ import { $t as tokenEstimateMultiplier, Bt as planLeaves, C as CREDIT_DEDUCT_TRANSACTION_TYPES, Ot as isEarlyStop, T as ChatModels, Vt as planProgress, cn as actorColorIndex, dn as delegationPayloadSchema, fn as selfClaimedActorKindSchema, it as REVIEW_GATE_STATUS_VALUES, ln as actorKindMarker, n as SESSION_ID_PATTERN, on as ACTOR_COLOR_SLOTS, r as isValidSessionId, sn as DELEGATION_PAYLOAD_SCHEMA_NAME, st as SUBQUEST_STATUS_VALUES, t as logger, un as actorKindSchema } from "./Logger-7MmrU5w6.mjs";
7
+ import { a as rewireReservedNames, i as mergeCommands, n as COMMANDS, t as RemoteSkillSource } from "./RemoteSkillSource-D_F99yBR.mjs";
8
8
  import { r as isFeatureEnabled, t as PluginStore } from "./PluginStore-DwvOJ-G3.mjs";
9
- import { i as getTokenCounter, n as ConversationContext, r as reconstructTurnBlocks, t as WorkItemsClient } from "./WorkItemsClient-D4sFGL9X.mjs";
9
+ import { i as getTokenCounter, n as ConversationContext, r as reconstructTurnBlocks, t as WorkItemsClient } from "./WorkItemsClient-C9_pjHCo.mjs";
10
10
  import { t as getShellSessionManager } from "./ShellSessionManager-6o8KZzl1-vrbPAUTq.mjs";
11
- import { r as OAuthClient, t as ApiClient } from "./ApiClient-Yp2LPlX3.mjs";
12
- import { t as version } from "./package-WlxLVpUb.mjs";
13
- import { a as NotifyingLlmBackend, i as deferredToolRegistry, n as buildAgent, r as buildSupportingStores, t as buildToolSearch } from "./buildToolSearch-CqHKSLtG.mjs";
14
- import { s as getStartupUpdateStatus } from "./updateChecker-Boq0RruU.mjs";
15
- import React, { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
11
+ import { r as OAuthClient, t as ApiClient } from "./ApiClient-SVXSI3HI.mjs";
12
+ import { t as version } from "./package-r_xumsGY.mjs";
13
+ import { a as NotifyingLlmBackend, i as deferredToolRegistry, n as buildAgent, r as buildSupportingStores, t as buildToolSearch } from "./buildToolSearch-8xyBwXRx.mjs";
14
+ import { s as getStartupUpdateStatus } from "./updateChecker-BOqaLeZU.mjs";
15
+ import React, { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
16
16
  import { Box, Static, Text, measureElement, render, useApp, useInput, usePaste, useStdin, useStdout } from "ink";
17
+ import { formatWithOptions, promisify } from "node:util";
17
18
  import { randomBytes } from "crypto";
18
19
  import { constants, existsSync, promises, readFileSync, statSync } from "fs";
19
20
  import { homedir } from "os";
20
21
  import path, { basename, extname, join } from "path";
21
- import { v4 } from "uuid";
22
22
  import * as path$2 from "node:path";
23
23
  import path$1, { dirname as dirname$1, isAbsolute as isAbsolute$1, join as join$1, parse, relative, resolve as resolve$1 } from "node:path";
24
24
  import { constants as constants$1, promises as promises$1 } from "node:fs";
25
25
  import { z as z$1 } from "zod";
26
26
  import axios, { isAxiosError } from "axios";
27
+ import Fuse from "fuse.js";
27
28
  import Spinner from "ink-spinner";
28
29
  import { useShallow } from "zustand/react/shallow";
30
+ import wrapAnsi from "wrap-ansi";
29
31
  import TextInput from "ink-text-input";
30
32
  import { createHash as createHash$1, createHmac as createHmac$1, randomBytes as randomBytes$1, randomUUID as randomUUID$1, timingSafeEqual } from "node:crypto";
31
- import { promisify } from "node:util";
32
33
  import { homedir as homedir$1, tmpdir } from "node:os";
33
34
  import { execFile, spawn } from "child_process";
34
35
  import { promisify as promisify$1 } from "util";
@@ -36,7 +37,6 @@ import { marked } from "marked";
36
37
  import { highlight } from "cli-highlight";
37
38
  import { chmod, lstat, mkdir, mkdtemp, open, opendir, realpath, rename, rm, rmdir } from "node:fs/promises";
38
39
  import SelectInput from "ink-select-input";
39
- import jwt from "jsonwebtoken";
40
40
  import open$1 from "open";
41
41
  import { execFile as execFile$1 } from "node:child_process";
42
42
  import { createConnection, createServer } from "node:net";
@@ -44,6 +44,74 @@ import { pathToFileURL } from "url";
44
44
  import WebSocket from "ws";
45
45
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
46
46
  import { StringDecoder } from "node:string_decoder";
47
+ //#region src/components/FullscreenOutput.tsx
48
+ const OutputContext = createContext("");
49
+ const METHODS = [
50
+ "log",
51
+ "info",
52
+ "warn",
53
+ "error",
54
+ "debug"
55
+ ];
56
+ function FullscreenOutput({ children, onOutput }) {
57
+ const [output, setOutput] = useState("");
58
+ useLayoutEffect(() => {
59
+ let captured = "";
60
+ const originals = METHODS.map((method) => [method, console[method]]);
61
+ for (const method of METHODS) console[method] = (...args) => {
62
+ const text = formatWithOptions({ colors: false }, ...args);
63
+ captured = `${captured}${captured ? "\n" : ""}${text}`.slice(-65536);
64
+ onOutput(captured);
65
+ setOutput(captured);
66
+ };
67
+ return () => {
68
+ for (const [method, original] of originals) console[method] = original;
69
+ };
70
+ }, [onOutput]);
71
+ return /* @__PURE__ */ React.createElement(OutputContext.Provider, { value: output }, children);
72
+ }
73
+ function useFullscreenOutput() {
74
+ return useContext(OutputContext);
75
+ }
76
+ //#endregion
77
+ //#region src/fullscreen.ts
78
+ function fullscreenEnabled(requested = process.env.B4M_FULLSCREEN === "1", stdout = process.stdout, stdin = process.stdin) {
79
+ return requested && !!stdout.isTTY && !!stdin.isTTY;
80
+ }
81
+ function renderFullscreen(node, stdout = process.stdout, stdin = process.stdin) {
82
+ let capturedOutput = "";
83
+ const onOutput = (output) => {
84
+ capturedOutput = output;
85
+ };
86
+ const frameStream = new Proxy(stdout, { get(target, key) {
87
+ if (key === "write") return (chunk, callback) => {
88
+ if (chunk === "") return target.write("", callback);
89
+ if (chunk === "\x1B[?1049l") {
90
+ const diagnostics = capturedOutput ? sanitizeTerminalText(capturedOutput) + "\n" : "";
91
+ capturedOutput = "";
92
+ return target.write(chunk + diagnostics, callback);
93
+ }
94
+ if (/^(?:\u001b\[\?[0-9;]+[hl])+$/.test(chunk)) return target.write(chunk, callback);
95
+ if (chunk === "\n") return target.write("", callback);
96
+ return target.write("\x1B[H\x1B[2J" + chunk, callback);
97
+ };
98
+ const value = Reflect.get(target, key, target);
99
+ return typeof value === "function" ? value.bind(target) : value;
100
+ } });
101
+ return render(React.createElement(FullscreenOutput, {
102
+ onOutput,
103
+ children: node
104
+ }), {
105
+ stdout: frameStream,
106
+ stdin,
107
+ debug: true,
108
+ interactive: true,
109
+ alternateScreen: true,
110
+ exitOnCtrlC: false,
111
+ patchConsole: false
112
+ });
113
+ }
114
+ //#endregion
47
115
  //#region src/components/StatusBar.tsx
48
116
  const StatusBar = React.memo(function StatusBar({ isBashMode, model, tokenUsage, creditsUsage, subagentTokenUsage, subagentCreditsUsage, subagentActive = false }) {
49
117
  const interactionMode = useCliStore((state) => state.interactionMode);
@@ -399,6 +467,33 @@ function FileAutocomplete({ files, selectedIndex, query }) {
399
467
  }));
400
468
  }
401
469
  //#endregion
470
+ //#region src/utils/fuzzySearch.ts
471
+ /**
472
+ * Fuzzy search options for command matching
473
+ */
474
+ const fuseOptions = {
475
+ keys: [{
476
+ name: "name",
477
+ weight: .7
478
+ }, {
479
+ name: "description",
480
+ weight: .3
481
+ }],
482
+ threshold: .4,
483
+ includeScore: true,
484
+ minMatchCharLength: 1
485
+ };
486
+ /**
487
+ * Search commands using fuzzy matching
488
+ * @param query - The search query (without the leading /)
489
+ * @param commands - Optional custom commands array (defaults to built-in COMMANDS)
490
+ * @returns Array of matching commands, sorted by relevance
491
+ */
492
+ function searchCommands(query, commands = COMMANDS) {
493
+ if (!query || query.trim() === "") return commands;
494
+ return new Fuse(commands, fuseOptions).search(query).map((result) => result.item);
495
+ }
496
+ //#endregion
402
497
  //#region src/utils/imageDetector.ts
403
498
  /**
404
499
  * Detects pasted images and dropped files from terminal input
@@ -1077,6 +1172,87 @@ function BackgroundShellStatus() {
1077
1172
  session
1078
1173
  })));
1079
1174
  }
1175
+ const GLYPH = {
1176
+ completed: { symbol: "✓" },
1177
+ in_progress: {
1178
+ symbol: "●",
1179
+ color: "cyan"
1180
+ },
1181
+ pending: { symbol: "○" },
1182
+ cancelled: {
1183
+ symbol: "✕",
1184
+ color: "gray"
1185
+ }
1186
+ };
1187
+ const flatten = (items) => items.flatMap((item) => [{
1188
+ item,
1189
+ indent: false
1190
+ }, ...(item.children ?? []).map((child) => ({
1191
+ item: child,
1192
+ indent: true
1193
+ }))]);
1194
+ /** Rows the expanded block occupies for a given cap, so App can take them off the live budget. */
1195
+ function expandedPlanRows(items, maxRows) {
1196
+ return Math.min(flatten(items).length, Math.max(0, maxRows));
1197
+ }
1198
+ const oneLine = (text) => sanitizeTerminalText(text).replace(/\s+/g, " ");
1199
+ function Row({ item, indent }) {
1200
+ const { symbol, color } = GLYPH[item.status];
1201
+ const label = oneLine(item.status === "in_progress" ? item.activeForm ?? item.content : item.content);
1202
+ return /* @__PURE__ */ React.createElement(Box, { marginLeft: indent ? 2 : 0 }, /* @__PURE__ */ React.createElement(Text, { wrap: "truncate-end" }, /* @__PURE__ */ React.createElement(Text, {
1203
+ color,
1204
+ dimColor: item.status === "completed"
1205
+ }, symbol, " "), /* @__PURE__ */ React.createElement(Text, {
1206
+ color: item.status === "in_progress" ? "cyan" : void 0,
1207
+ dimColor: item.status !== "in_progress",
1208
+ strikethrough: item.status === "completed" || item.status === "cancelled"
1209
+ }, label)));
1210
+ }
1211
+ /** Leaf the summary and the expanded window both centre on: first in progress, else first pending. */
1212
+ const currentLeaf = (items) => {
1213
+ const live = planLeaves(items);
1214
+ return live.find((item) => item.status === "in_progress") ?? live.find((item) => item.status === "pending");
1215
+ };
1216
+ /** Plan above the prompt: list while a turn runs (capped to `maxRows`), `n/m - current` once it ends. */
1217
+ function PlanBlock({ maxRows = 8 }) {
1218
+ const items = useCliStore((state) => state.plan);
1219
+ const active = useCliStore((state) => state.isThinking || state.turnInFlight);
1220
+ if (items.length === 0) return null;
1221
+ if (!active) {
1222
+ if (planLeaves(items).every((item) => item.status === "completed")) return null;
1223
+ const { done, total } = planProgress({
1224
+ version: 1,
1225
+ source: "write_todos",
1226
+ items,
1227
+ updatedAt: 0
1228
+ });
1229
+ const current = currentLeaf(items);
1230
+ return /* @__PURE__ */ React.createElement(Text, {
1231
+ dimColor: true,
1232
+ wrap: "truncate-end"
1233
+ }, done, "/", total, current ? ` - ${oneLine(current.content)}` : "");
1234
+ }
1235
+ const rows = flatten(items);
1236
+ const budget = Math.max(0, maxRows);
1237
+ if (budget === 0) return null;
1238
+ let shown = rows;
1239
+ let hidden = 0;
1240
+ if (rows.length > budget) {
1241
+ const target = currentLeaf(items);
1242
+ const anchor = Math.max(0, rows.findIndex((row) => row.item === target));
1243
+ if (budget === 1) shown = [rows[anchor]];
1244
+ else {
1245
+ const visible = budget - 1;
1246
+ const start = Math.min(Math.max(0, anchor - (visible > 1 ? 1 : 0)), rows.length - visible);
1247
+ shown = rows.slice(start, start + visible);
1248
+ hidden = rows.length - visible;
1249
+ }
1250
+ }
1251
+ return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, shown.map((row) => /* @__PURE__ */ React.createElement(Row, {
1252
+ key: row.item.id,
1253
+ ...row
1254
+ })), hidden > 0 && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "+", hidden, " more"));
1255
+ }
1080
1256
  //#endregion
1081
1257
  //#region src/components/CompletedGroupNotification.tsx
1082
1258
  /** Time to display notifications before clearing (ms) */
@@ -1163,7 +1339,7 @@ function withSessionScope(items, scope) {
1163
1339
  * Displays when a tool needs permission before execution.
1164
1340
  * Waits indefinitely for user response (like Claude Code).
1165
1341
  */
1166
- function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrusted, sessionScope, kind, onResponse }) {
1342
+ function PermissionPrompt({ viewport, toolName, toolDescription, args, preview, canBeTrusted, sessionScope, kind, onResponse }) {
1167
1343
  const isSandboxEscalation = kind === "sandbox-escalation";
1168
1344
  const hideArgs = TOOLS_WITH_HIDDEN_ARGS$1.has(toolName);
1169
1345
  const baseItems = isSandboxEscalation ? [
@@ -1213,6 +1389,15 @@ function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrust
1213
1389
  const items = isSandboxEscalation || sessionScope === void 0 ? baseItems : withSessionScope(baseItems, sessionScope);
1214
1390
  const [selectedIndex, setSelectedIndex] = useState(0);
1215
1391
  const [responded, setResponded] = useState(false);
1392
+ const [previewOffset, setPreviewOffset] = useState(0);
1393
+ const details = viewport ? wrapAnsi(escapeTerminalControlChars([
1394
+ `Tool: ${toolName}`,
1395
+ toolDescription,
1396
+ `Arguments: ${typeof args === "string" ? args : JSON.stringify(args, null, 2)}`,
1397
+ preview ? `Preview:\n${preview}` : ""
1398
+ ].filter(Boolean).join("\n")), Math.max(1, viewport.columns), { hard: true }).split("\n") : [];
1399
+ const detailRows = Math.max(1, (viewport?.rows ?? 24) - items.length - 4);
1400
+ const detailStart = Math.min(previewOffset, Math.max(0, details.length - detailRows));
1216
1401
  const handleSelect = useCallback(() => {
1217
1402
  if (responded) return;
1218
1403
  setResponded(true);
@@ -1234,6 +1419,10 @@ function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrust
1234
1419
  ]);
1235
1420
  useInput((input, key) => {
1236
1421
  if (responded) return;
1422
+ if (viewport && (key.pageUp || key.pageDown)) {
1423
+ setPreviewOffset(Math.max(0, Math.min(details.length - detailRows, detailStart + (key.pageUp ? -detailRows : detailRows))));
1424
+ return;
1425
+ }
1237
1426
  const num = parseInt(input, 10);
1238
1427
  if (num >= 1 && num <= items.length) {
1239
1428
  handleSelectIndex(num - 1);
@@ -1258,6 +1447,24 @@ function PermissionPrompt({ toolName, toolDescription, args, preview, canBeTrust
1258
1447
  const borderColor = isSandboxBlock ? "red" : "yellow";
1259
1448
  const headerColor = isSandboxBlock ? "red" : "yellow";
1260
1449
  const headerText = isSandboxBlock ? "🛑 Sandbox Blocked" : "⚠️ Permission Required";
1450
+ if (viewport) return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, /* @__PURE__ */ React.createElement(Text, {
1451
+ bold: true,
1452
+ color: headerColor,
1453
+ wrap: "truncate"
1454
+ }, "Permission Required: ", escapeTerminalControlChars(toolName)), /* @__PURE__ */ React.createElement(Text, {
1455
+ dimColor: true,
1456
+ wrap: "truncate"
1457
+ }, "PgUp/PgDn: details ", detailStart + 1, "-", Math.min(details.length, detailStart + detailRows), "/", details.length), details.slice(detailStart, detailStart + detailRows).map((line, index) => /* @__PURE__ */ React.createElement(Text, {
1458
+ key: index,
1459
+ wrap: "truncate"
1460
+ }, line || " ")), items.map((item, index) => /* @__PURE__ */ React.createElement(Text, {
1461
+ key: item.value,
1462
+ wrap: "truncate",
1463
+ color: index === selectedIndex ? "cyan" : void 0
1464
+ }, index + 1, ". ", item.label)), /* @__PURE__ */ React.createElement(Text, {
1465
+ dimColor: true,
1466
+ wrap: "truncate"
1467
+ }, "1-", items.length, ", y/n, or Up/Down + Enter: decide"));
1261
1468
  return /* @__PURE__ */ React.createElement(Box, {
1262
1469
  flexDirection: "column",
1263
1470
  borderStyle: "bold",
@@ -2610,6 +2817,40 @@ const MessageItem = React.memo(function MessageItem({ message, showThoughts = tr
2610
2817
  }, (message.metadata.tokenUsage?.total || message.metadata.creditsUsed) && /* @__PURE__ */ React.createElement(Text, { dimColor: true }, "(", message.metadata.tokenUsage?.total ? `${message.metadata.tokenUsage.total.toLocaleString()} tokens` : "", message.metadata.creditsUsed && message.metadata.creditsUsed > 0 ? (message.metadata.tokenUsage?.total ? " • " : "") + `used ${message.metadata.creditsUsed.toLocaleString()} ${message.metadata.creditsUsed === 1 ? "credit" : "credits"}` : "", ")")));
2611
2818
  });
2612
2819
  //#endregion
2820
+ //#region src/components/FullscreenHistory.tsx
2821
+ function FullscreenHistory({ messages, rows, columns }) {
2822
+ const [selected, setSelected] = useState(Math.max(0, messages.length - 1));
2823
+ const [offset, setOffset] = useState(0);
2824
+ const index = Math.min(selected, Math.max(0, messages.length - 1));
2825
+ const message = messages[index];
2826
+ const lines = useMemo(() => {
2827
+ if (!message) return ["No completed messages yet."];
2828
+ const steps = message.metadata?.steps?.map((step) => JSON.stringify(step)).join("\n");
2829
+ const transcript = [message.content, steps].filter(Boolean).join("\n\n");
2830
+ return wrapAnsi(sanitizeTerminalText(transcript), Math.max(1, columns), { hard: true }).split("\n");
2831
+ }, [message, columns]);
2832
+ const pageRows = Math.max(1, rows - 3);
2833
+ const start = Math.min(offset, Math.max(0, lines.length - pageRows));
2834
+ useInput((_input, key) => {
2835
+ if (key.leftArrow || key.rightArrow) {
2836
+ setSelected(Math.max(0, Math.min(messages.length - 1, index + (key.leftArrow ? -1 : 1))));
2837
+ setOffset(0);
2838
+ }
2839
+ if (key.upArrow || key.pageUp) setOffset(Math.max(0, start - (key.pageUp ? pageRows : 1)));
2840
+ if (key.downArrow || key.pageDown) setOffset(Math.min(Math.max(0, lines.length - pageRows), start + (key.pageDown ? pageRows : 1)));
2841
+ });
2842
+ return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, /* @__PURE__ */ React.createElement(Text, {
2843
+ bold: true,
2844
+ wrap: "truncate"
2845
+ }, "History ", messages.length ? index + 1 : 0, "/", messages.length, " ", message?.role), /* @__PURE__ */ React.createElement(Text, {
2846
+ dimColor: true,
2847
+ wrap: "truncate"
2848
+ }, "Left/Right: message | Up/Down/PgUp/PgDn: lines | Ctrl+O: back"), lines.slice(start, start + pageRows).map((line, i) => /* @__PURE__ */ React.createElement(Text, {
2849
+ key: i,
2850
+ wrap: "truncate"
2851
+ }, line || " ")));
2852
+ }
2853
+ //#endregion
2613
2854
  //#region src/components/App.tsx
2614
2855
  /**
2615
2856
  * Live-frame rows reserved for everything outside the step trace and any open
@@ -2630,7 +2871,7 @@ const LIVE_CHROME_ROWS = 10;
2630
2871
  /** Shown under the queued-message rows; mirrors the routing in handleSubmit and the ESC handler in index.tsx. */
2631
2872
  const QUEUE_HINT = "Enter steers this turn · Tab queues for next turn · Esc cancels and restores to input";
2632
2873
  const PEER_QUEUE_HINT = "Enter and Tab queue your next turn · Peer work does not receive your input";
2633
- function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPermissionResponse, onUserQuestionResponse, onReviewGateResponse, onImageDetected, commandHistory = [], onHistoryEntry, commands = [], config, availableModels = [], pluginDescriptors = [], onSaveConfig, prefillInput, onPrefillConsumed, mcpManager }) {
2874
+ function App({ fullscreen = false, onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPermissionResponse, onUserQuestionResponse, onReviewGateResponse, onImageDetected, commandHistory = [], onHistoryEntry, commands = [], config, availableModels = [], pluginDescriptors = [], onSaveConfig, prefillInput, onPrefillConsumed, mcpManager }) {
2634
2875
  const messages = useCliStore(useShallow((state) => state.session?.messages || []));
2635
2876
  const pendingMessages = useCliStore((state) => state.pendingMessages);
2636
2877
  const messageQueue = useCliStore((state) => state.messageQueue);
@@ -2695,8 +2936,23 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2695
2936
  useInput(() => setPromptInputTick((tick) => tick + 1), { isActive: promptKey !== "" });
2696
2937
  const promptRows = promptKey === "" ? 0 : measuredPrompt?.key === promptKey ? measuredPrompt.rows : Infinity;
2697
2938
  const [terminalCols, terminalRows] = useStdoutDimensions();
2939
+ const fullscreenOutput = useFullscreenOutput();
2940
+ const historyMessages = React.useMemo(() => fullscreenOutput ? [...messages, {
2941
+ id: "fullscreen-output",
2942
+ role: "assistant",
2943
+ content: "Command output (most recent 64K characters)\n\n" + fullscreenOutput,
2944
+ timestamp: ""
2945
+ }] : messages, [messages, fullscreenOutput]);
2946
+ const [browsingHistory, setBrowsingHistory] = useState(false);
2947
+ useInput((input, key) => {
2948
+ if (key.ctrl && input === "o") setBrowsingHistory((value) => !value);
2949
+ }, { isActive: fullscreen && !promptKey && !showConfigEditor && !showMcpViewer });
2698
2950
  const queueRows = messageQueue.length > 0 ? messageQueue.length + 1 : 0;
2699
- const liveRows = Math.max(0, terminalRows - LIVE_CHROME_ROWS - queueRows - promptRows);
2951
+ const budgetRows = Math.max(0, terminalRows - LIVE_CHROME_ROWS - queueRows - promptRows);
2952
+ const planActive = useCliStore((state) => state.isThinking || state.turnInFlight);
2953
+ const plan = useCliStore((state) => state.plan);
2954
+ const planMaxRows = Math.min(8, Math.floor(budgetRows / 2));
2955
+ const liveRows = budgetRows - (planActive ? expandedPlanRows(plan, planMaxRows) : 0);
2700
2956
  const handleSubmit = React.useCallback(async (input, options) => {
2701
2957
  const trimmed = input.trim();
2702
2958
  if (!trimmed) return;
@@ -2754,13 +3010,36 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2754
3010
  config,
2755
3011
  mcpManager,
2756
3012
  onClose: () => setShowMcpViewer(false)
2757
- })) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Static, { items: messages }, (message) => /* @__PURE__ */ React.createElement(Box, {
3013
+ })) : /* @__PURE__ */ React.createElement(React.Fragment, null, fullscreen && browsingHistory && !promptKey && /* @__PURE__ */ React.createElement(FullscreenHistory, {
3014
+ messages: historyMessages,
3015
+ rows: terminalRows,
3016
+ columns: terminalCols
3017
+ }), fullscreen && permissionPrompt && /* @__PURE__ */ React.createElement(PermissionPrompt, {
3018
+ key: permissionPrompt.id,
3019
+ viewport: {
3020
+ rows: terminalRows,
3021
+ columns: terminalCols
3022
+ },
3023
+ toolName: permissionPrompt.toolName,
3024
+ args: permissionPrompt.args,
3025
+ preview: permissionPrompt.preview,
3026
+ canBeTrusted: permissionPrompt.canBeTrusted,
3027
+ sessionScope: permissionPrompt.sessionScope,
3028
+ kind: permissionPrompt.kind,
3029
+ onResponse: (response) => onPermissionResponse(response, permissionPrompt.id)
3030
+ }), /* @__PURE__ */ React.createElement(Box, {
3031
+ flexDirection: "column",
3032
+ display: fullscreen && (browsingHistory && !promptKey || permissionPrompt) ? "none" : "flex"
3033
+ }, !fullscreen && /* @__PURE__ */ React.createElement(Static, { items: messages }, (message) => /* @__PURE__ */ React.createElement(Box, {
2758
3034
  key: message.id,
2759
3035
  flexDirection: "column"
2760
3036
  }, /* @__PURE__ */ React.createElement(MessageItem, {
2761
3037
  message,
2762
3038
  showThoughts
2763
- }))), /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, pendingMessages.map((message) => /* @__PURE__ */ React.createElement(Box, {
3039
+ }))), fullscreen && /* @__PURE__ */ React.createElement(Text, {
3040
+ dimColor: true,
3041
+ wrap: "truncate"
3042
+ }, "Ctrl+O: history (", messages.length, " messages", fullscreenOutput ? ", command output" : "", ")"), fullscreen && fullscreenOutput && /* @__PURE__ */ React.createElement(Text, { wrap: "truncate" }, fullscreenOutput.trimEnd().slice(fullscreenOutput.trimEnd().lastIndexOf("\n") + 1)), /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, pendingMessages.map((message) => /* @__PURE__ */ React.createElement(Box, {
2764
3043
  key: message.id,
2765
3044
  flexDirection: "column"
2766
3045
  }, /* @__PURE__ */ React.createElement(MessageItem, {
@@ -2770,7 +3049,7 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2770
3049
  })))), /* @__PURE__ */ React.createElement(Box, {
2771
3050
  ref: promptRef,
2772
3051
  flexDirection: "column"
2773
- }, permissionPrompt && /* @__PURE__ */ React.createElement(Box, {
3052
+ }, permissionPrompt && !fullscreen && /* @__PURE__ */ React.createElement(Box, {
2774
3053
  key: permissionPrompt.id,
2775
3054
  flexDirection: "column",
2776
3055
  paddingX: 1
@@ -2806,7 +3085,7 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2806
3085
  const target = exitHandoffPrompt;
2807
3086
  setExitHandoffPrompt(null);
2808
3087
  target.resolve(generate);
2809
- } }))), !permissionPrompt && !userQuestionPrompt && !reviewGatePrompt && !exitHandoffPrompt && /* @__PURE__ */ React.createElement(AgentThinking, null), /* @__PURE__ */ React.createElement(BackgroundAgentStatus, null), /* @__PURE__ */ React.createElement(BackgroundShellStatus, null), /* @__PURE__ */ React.createElement(CompletedGroupNotification, null), exitRequested && /* @__PURE__ */ React.createElement(Box, {
3088
+ } }))), !permissionPrompt && !userQuestionPrompt && !reviewGatePrompt && !exitHandoffPrompt && /* @__PURE__ */ React.createElement(AgentThinking, null), /* @__PURE__ */ React.createElement(PlanBlock, { maxRows: planMaxRows }), /* @__PURE__ */ React.createElement(BackgroundAgentStatus, null), /* @__PURE__ */ React.createElement(BackgroundShellStatus, null), /* @__PURE__ */ React.createElement(CompletedGroupNotification, null), exitRequested && /* @__PURE__ */ React.createElement(Box, {
2810
3089
  paddingX: 1,
2811
3090
  marginBottom: 1
2812
3091
  }, /* @__PURE__ */ React.createElement(Text, {
@@ -2844,7 +3123,7 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2844
3123
  onSubmit: handleSubmit,
2845
3124
  onBashCommand,
2846
3125
  onImageDetected,
2847
- disabled: !!permissionPrompt || !!userQuestionPrompt || !!reviewGatePrompt || !!exitHandoffPrompt,
3126
+ disabled: fullscreen && browsingHistory || !!permissionPrompt || !!userQuestionPrompt || !!reviewGatePrompt || !!exitHandoffPrompt,
2848
3127
  history: commandHistory,
2849
3128
  onHistoryEntry,
2850
3129
  commands,
@@ -2859,7 +3138,7 @@ function App({ onMessage, onBackgroundCompletion, onCommand, onBashCommand, onPe
2859
3138
  subagentTokenUsage: subagentTokens,
2860
3139
  subagentCreditsUsage: subagentCost,
2861
3140
  subagentActive
2862
- }))));
3141
+ })))));
2863
3142
  }
2864
3143
  //#endregion
2865
3144
  //#region src/components/TrustLocationSelector.tsx
@@ -3306,6 +3585,25 @@ async function copyToClipboard(text, deps = {}) {
3306
3585
  return (isSshSession(env) ? sentFirst : sendOsc52()) ? "terminal" : "failed";
3307
3586
  }
3308
3587
  //#endregion
3588
+ //#region src/utils/jwtUserId.ts
3589
+ const JWT_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;
3590
+ function parseSegment(segment) {
3591
+ return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
3592
+ }
3593
+ /** Reads the `id` claim without verifying the signature; '' when the token is malformed or has no string id. */
3594
+ function decodeJwtUserId(token) {
3595
+ if (!JWT_SHAPE.test(token)) return "";
3596
+ const [header, payload] = token.split(".");
3597
+ try {
3598
+ if (!parseSegment(header)) return "";
3599
+ const claims = parseSegment(payload);
3600
+ const id = claims !== null && typeof claims === "object" ? claims.id : void 0;
3601
+ return typeof id === "string" ? id : "";
3602
+ } catch {
3603
+ return "";
3604
+ }
3605
+ }
3606
+ //#endregion
3309
3607
  //#region src/components/LoginFlow.tsx
3310
3608
  /**
3311
3609
  * Only https URLs (and http on localhost for dev) may be handed to the OS opener.
@@ -3409,7 +3707,7 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
3409
3707
  const tokens = await oauth.waitForAuthorization(deviceFlowResponse.device_code, deviceFlowResponse.interval, (message) => setStatusMessage(message), abort.signal);
3410
3708
  if (abort.signal.aborted) return;
3411
3709
  tokenIssued.current = true;
3412
- const userId = jwt.decode(tokens.access_token)?.id || "";
3710
+ const userId = decodeJwtUserId(tokens.access_token);
3413
3711
  const expiresAt = new Date(Date.now() + tokens.expires_in * 1e3).toISOString();
3414
3712
  await configStore.withRefreshLock(() => configStore.setAuthTokens({
3415
3713
  accessToken: tokens.access_token,
@@ -3773,7 +4071,7 @@ function renderWorkflowReminder(state, options = {}) {
3773
4071
  const openBlockers = state.blockers.filter((b) => b.status === "open");
3774
4072
  const recentDecisions = state.decisions.slice(-5);
3775
4073
  let elided = state.decisions.length - recentDecisions.length;
3776
- const todoLines = openTodos.map((t, i) => `${i + 1}. [${t.status}] ${elide(t.description)}`);
4074
+ const todoLines = openTodos.map((t, i) => `${i + 1}. [${t.status}] ${elide(t.content)}`);
3777
4075
  const blockerLines = openBlockers.map((b) => `- ${elide(b.description)}`);
3778
4076
  const decisionLines = recentDecisions.map((d) => `- ${elide(d.summary)} (rationale: ${elide(d.rationale, 100)})`);
3779
4077
  if (todoLines.length === 0 && blockerLines.length === 0 && decisionLines.length === 0) return {
@@ -4054,7 +4352,7 @@ function isInjectedContinuity(message) {
4054
4352
  */
4055
4353
  function injectHandoffMessage(messages, handoff) {
4056
4354
  return [{
4057
- id: v4(),
4355
+ id: crypto.randomUUID(),
4058
4356
  role: "user",
4059
4357
  content: buildHandoffSystemMessage(handoff),
4060
4358
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -4084,7 +4382,7 @@ function injectWorkflowStateMessage(messages, workflow) {
4084
4382
  });
4085
4383
  if (!text) return withoutPriorInjections;
4086
4384
  return [{
4087
- id: v4(),
4385
+ id: crypto.randomUUID(),
4088
4386
  role: "user",
4089
4387
  content: `${WORKFLOW_STATE_MARKER}\n\n${text}`,
4090
4388
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -4116,13 +4414,13 @@ function buildLocalHandoff(session, workflowOverride) {
4116
4414
  const openTodos = todos.filter((t) => t.status === "pending" || t.status === "in_progress");
4117
4415
  const currentTask = todos.find((t) => t.status === "in_progress");
4118
4416
  const parts = [`Local handoff for session "${session.name}" (${session.messages.length} messages, model ${session.model}).`, `${decisions.length} decisions, ${openBlockers.length} open blockers, ${openTodos.length} open todos.`];
4119
- if (currentTask) parts.push(`Current task: ${currentTask.description}.`);
4417
+ if (currentTask) parts.push(`Current task: ${currentTask.content}.`);
4120
4418
  if (decisions.length > 0) parts.push(`Latest decision: ${decisions[decisions.length - 1].summary}.`);
4121
4419
  parts.push("Generated from session state without an LLM call; no narrative synthesis.");
4122
4420
  return {
4123
4421
  summary: parts.join(" "),
4124
4422
  keyFindings: decisions.map((d) => `${d.summary} (rationale: ${d.rationale})`),
4125
- nextSteps: [...openTodos.map((t) => t.description), ...openBlockers.map((b) => `Resolve blocker: ${b.description}`)],
4423
+ nextSteps: [...openTodos.map((t) => t.content), ...openBlockers.map((b) => `Resolve blocker: ${b.description}`)],
4126
4424
  pendingDecisions: [],
4127
4425
  blockers: openBlockers.map((b) => b.description),
4128
4426
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -4346,14 +4644,14 @@ function buildCompactionPrompt(messages, options = {}) {
4346
4644
  */
4347
4645
  function createCompactedSession(originalSession, summary, preservedMessages, preserveId = false) {
4348
4646
  const summaryMessage = {
4349
- id: v4(),
4647
+ id: crypto.randomUUID(),
4350
4648
  role: "user",
4351
4649
  content: `${COMPACTION_SUMMARY_MARKER}\n\n${summary}`,
4352
4650
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
4353
4651
  };
4354
4652
  const handoff = originalSession.metadata.workflow?.handoff;
4355
4653
  const handoffMessage = handoff ? {
4356
- id: v4(),
4654
+ id: crypto.randomUUID(),
4357
4655
  role: "user",
4358
4656
  content: buildHandoffSystemMessage(handoff),
4359
4657
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -4364,7 +4662,7 @@ function createCompactedSession(originalSession, summary, preservedMessages, pre
4364
4662
  ...preservedMessages
4365
4663
  ] : [summaryMessage, ...preservedMessages];
4366
4664
  return {
4367
- id: preserveId ? originalSession.id : v4(),
4665
+ id: preserveId ? originalSession.id : crypto.randomUUID(),
4368
4666
  name: `${originalSession.name} (compacted)`,
4369
4667
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4370
4668
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -5045,6 +5343,378 @@ Unlike agent_delegate (which uses pre-defined agents), this tool lets you compos
5045
5343
  };
5046
5344
  }
5047
5345
  //#endregion
5346
+ //#region src/tools/decisionLogTool.ts
5347
+ /**
5348
+ * Validate log_decision parameters
5349
+ * @throws Error if validation fails
5350
+ */
5351
+ function validateParams$1(args) {
5352
+ const params = args;
5353
+ if (typeof params.summary !== "string" || params.summary.trim() === "") throw new Error("log_decision: summary must be a non-empty string");
5354
+ if (typeof params.rationale !== "string" || params.rationale.trim() === "") throw new Error("log_decision: rationale must be a non-empty string");
5355
+ if (params.alternatives !== void 0) {
5356
+ if (!Array.isArray(params.alternatives)) throw new Error("log_decision: alternatives must be an array of strings");
5357
+ for (const alt of params.alternatives) if (typeof alt !== "string") throw new Error("log_decision: each alternative must be a string");
5358
+ }
5359
+ if (params.context !== void 0 && typeof params.context !== "string") throw new Error("log_decision: context must be a string");
5360
+ return {
5361
+ summary: params.summary.trim(),
5362
+ rationale: params.rationale.trim(),
5363
+ alternatives: params.alternatives,
5364
+ context: typeof params.context === "string" ? params.context.trim() : void 0
5365
+ };
5366
+ }
5367
+ /**
5368
+ * Format decisions for display output
5369
+ */
5370
+ function formatDecisionsOutput(decisions) {
5371
+ if (decisions.length === 0) return "No decisions logged in this session.";
5372
+ return decisions.map((decision, index) => {
5373
+ const lines = [`${index + 1}. **${decision.summary}**`, ` Rationale: ${decision.rationale}`];
5374
+ if (decision.alternatives && decision.alternatives.length > 0) lines.push(` Alternatives considered: ${decision.alternatives.join(", ")}`);
5375
+ if (decision.context) lines.push(` Context: ${decision.context}`);
5376
+ const timestamp = new Date(decision.timestamp).toLocaleTimeString();
5377
+ lines.push(` Logged at: ${timestamp}`);
5378
+ return lines.join("\n");
5379
+ }).join("\n\n");
5380
+ }
5381
+ /**
5382
+ * Create the log_decision tool.
5383
+ *
5384
+ * Allows the AI to record significant decisions with rationale during a session.
5385
+ * Decisions are persisted in the session's workflow state for audit trail
5386
+ * and cross-session continuity.
5387
+ */
5388
+ function createDecisionLogTool(store) {
5389
+ return {
5390
+ toolFn: async (args) => {
5391
+ const params = validateParams$1(args);
5392
+ const decision = {
5393
+ id: crypto.randomUUID(),
5394
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5395
+ summary: params.summary,
5396
+ rationale: params.rationale,
5397
+ alternatives: params.alternatives,
5398
+ context: params.context
5399
+ };
5400
+ store.decisions.push(decision);
5401
+ if (store.onUpdate) store.onUpdate(store.decisions);
5402
+ return `Decision logged (#${store.decisions.length}): ${decision.summary}`;
5403
+ },
5404
+ toolSchema: {
5405
+ name: "log_decision",
5406
+ description: `Record a significant decision with its rationale for audit trail and session continuity.
5407
+
5408
+ **When to use:**
5409
+ - Architecture or design choices (e.g., "chose Zustand over Redux because...")
5410
+ - Scope narrowing or direction changes in research
5411
+ - Trade-off decisions between viable alternatives
5412
+ - Interpretation of ambiguous requirements
5413
+
5414
+ **When NOT to use:**
5415
+ - Routine operations (reading files, running tests)
5416
+ - Trivial choices that wouldn't matter to someone resuming this work
5417
+ - Implementation details that are obvious from the code
5418
+
5419
+ Log decisions that would matter if someone needed to understand WHY you did something.`,
5420
+ parameters: {
5421
+ type: "object",
5422
+ properties: {
5423
+ summary: {
5424
+ type: "string",
5425
+ description: "What was decided — a clear, concise statement"
5426
+ },
5427
+ rationale: {
5428
+ type: "string",
5429
+ description: "Why this decision was made — the reasoning behind it"
5430
+ },
5431
+ alternatives: {
5432
+ type: "array",
5433
+ items: { type: "string" },
5434
+ description: "What alternatives were considered (optional)"
5435
+ },
5436
+ context: {
5437
+ type: "string",
5438
+ description: "What triggered this decision — the situation or constraint (optional)"
5439
+ }
5440
+ },
5441
+ required: ["summary", "rationale"]
5442
+ }
5443
+ }
5444
+ };
5445
+ }
5446
+ /**
5447
+ * Create a new empty DecisionStore
5448
+ */
5449
+ function createDecisionStore(onUpdate) {
5450
+ return {
5451
+ decisions: [],
5452
+ onUpdate
5453
+ };
5454
+ }
5455
+ //#endregion
5456
+ //#region src/tools/blockerTool.ts
5457
+ /**
5458
+ * Format blockers for display output
5459
+ */
5460
+ function formatBlockersOutput(blockers) {
5461
+ if (blockers.length === 0) return "No blockers tracked in this session.";
5462
+ const open = blockers.filter((b) => b.status === "open");
5463
+ const resolved = blockers.filter((b) => b.status === "resolved");
5464
+ const lines = [];
5465
+ if (open.length > 0) {
5466
+ lines.push(`**Open blockers (${open.length}):**`);
5467
+ for (const blocker of open) lines.push(` - [${blocker.id.slice(0, 8)}] ${blocker.description}`);
5468
+ }
5469
+ if (resolved.length > 0) {
5470
+ if (open.length > 0) lines.push("");
5471
+ lines.push(`**Resolved blockers (${resolved.length}):**`);
5472
+ for (const blocker of resolved) {
5473
+ lines.push(` - [${blocker.id.slice(0, 8)}] ${blocker.description}`);
5474
+ lines.push(` Resolution: ${blocker.resolution ?? "(no resolution recorded)"}`);
5475
+ }
5476
+ }
5477
+ return lines.join("\n");
5478
+ }
5479
+ /**
5480
+ * Create the track_blocker and resolve_blocker tools.
5481
+ *
5482
+ * Allows the AI to track what's blocking progress and record resolutions.
5483
+ * Blockers are persisted in the session's workflow state for audit trail
5484
+ * and cross-session continuity.
5485
+ */
5486
+ function createBlockerTools(store) {
5487
+ return [{
5488
+ toolFn: async (args) => {
5489
+ const params = args;
5490
+ if (typeof params.description !== "string" || params.description.trim() === "") throw new Error("track_blocker: description must be a non-empty string");
5491
+ const blocker = {
5492
+ id: crypto.randomUUID(),
5493
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
5494
+ description: params.description.trim(),
5495
+ status: "open"
5496
+ };
5497
+ store.blockers.push(blocker);
5498
+ if (store.onUpdate) store.onUpdate(store.blockers);
5499
+ const openCount = store.blockers.filter((b) => b.status === "open").length;
5500
+ return `Blocker tracked [${blocker.id.slice(0, 8)}]: ${blocker.description}\n(${openCount} open blocker${openCount === 1 ? "" : "s"})`;
5501
+ },
5502
+ toolSchema: {
5503
+ name: "track_blocker",
5504
+ description: `Track something that is blocking progress.
5505
+
5506
+ **When to use:**
5507
+ - Missing information or unclear requirements
5508
+ - External dependencies (waiting on API access, credentials, data)
5509
+ - Technical constraints discovered during work
5510
+ - Ambiguous requirements that need human clarification
5511
+
5512
+ **When NOT to use:**
5513
+ - Normal challenges that are part of the work
5514
+ - Things you can resolve immediately`,
5515
+ parameters: {
5516
+ type: "object",
5517
+ properties: { description: {
5518
+ type: "string",
5519
+ description: "What is blocking progress — be specific about what is needed to unblock"
5520
+ } },
5521
+ required: ["description"]
5522
+ }
5523
+ }
5524
+ }, {
5525
+ toolFn: async (args) => {
5526
+ const params = args;
5527
+ if (typeof params.blocker_id !== "string" || params.blocker_id.trim() === "") throw new Error("resolve_blocker: blocker_id must be a non-empty string");
5528
+ if (typeof params.resolution !== "string" || params.resolution.trim() === "") throw new Error("resolve_blocker: resolution must be a non-empty string");
5529
+ const blockerId = params.blocker_id.trim();
5530
+ const blocker = store.blockers.find((b) => b.id === blockerId || b.id.startsWith(blockerId));
5531
+ if (!blocker) {
5532
+ const openBlockers = store.blockers.filter((b) => b.status === "open");
5533
+ if (openBlockers.length === 0) return "No open blockers to resolve.";
5534
+ return `Blocker not found. Open blockers:\n${openBlockers.map((b) => ` [${b.id.slice(0, 8)}] ${b.description}`).join("\n")}`;
5535
+ }
5536
+ if (blocker.status === "resolved") return `Blocker [${blocker.id.slice(0, 8)}] is already resolved.`;
5537
+ blocker.status = "resolved";
5538
+ blocker.resolvedAt = (/* @__PURE__ */ new Date()).toISOString();
5539
+ blocker.resolution = params.resolution.trim();
5540
+ if (store.onUpdate) store.onUpdate(store.blockers);
5541
+ const openCount = store.blockers.filter((b) => b.status === "open").length;
5542
+ return `Blocker resolved [${blocker.id.slice(0, 8)}]: ${blocker.resolution}\n(${openCount} open blocker${openCount === 1 ? "" : "s"} remaining)`;
5543
+ },
5544
+ toolSchema: {
5545
+ name: "resolve_blocker",
5546
+ description: `Mark a blocker as resolved with a description of how it was resolved.
5547
+
5548
+ Use the blocker ID (or its first 8 characters) from the track_blocker output.`,
5549
+ parameters: {
5550
+ type: "object",
5551
+ properties: {
5552
+ blocker_id: {
5553
+ type: "string",
5554
+ description: "The ID of the blocker to resolve (full ID or first 8 characters)"
5555
+ },
5556
+ resolution: {
5557
+ type: "string",
5558
+ description: "How the blocker was resolved"
5559
+ }
5560
+ },
5561
+ required: ["blocker_id", "resolution"]
5562
+ }
5563
+ }
5564
+ }];
5565
+ }
5566
+ /**
5567
+ * Create a new empty BlockerStore
5568
+ */
5569
+ function createBlockerStore(onUpdate) {
5570
+ return {
5571
+ blockers: [],
5572
+ onUpdate
5573
+ };
5574
+ }
5575
+ //#endregion
5576
+ //#region src/tools/reviewGateTool.ts
5577
+ const MAX_DESCRIPTION_LENGTH = 2e3;
5578
+ const MAX_RECOMMENDATION_LENGTH = 1e3;
5579
+ const MAX_OPTION_LENGTH = 500;
5580
+ const MAX_OPTIONS_COUNT = 10;
5581
+ /**
5582
+ * Validate request_review_gate parameters
5583
+ * @throws Error if validation fails
5584
+ */
5585
+ function validateParams(args) {
5586
+ const params = args;
5587
+ if (typeof params.description !== "string" || params.description.trim() === "") throw new Error("request_review_gate: description must be a non-empty string");
5588
+ if (params.description.length > MAX_DESCRIPTION_LENGTH) throw new Error(`request_review_gate: description must be ${MAX_DESCRIPTION_LENGTH} characters or fewer`);
5589
+ if (params.options !== void 0) {
5590
+ if (!Array.isArray(params.options)) throw new Error("request_review_gate: options must be an array of strings");
5591
+ if (params.options.length > MAX_OPTIONS_COUNT) throw new Error(`request_review_gate: options must contain ${MAX_OPTIONS_COUNT} entries or fewer`);
5592
+ for (const opt of params.options) {
5593
+ if (typeof opt !== "string") throw new Error("request_review_gate: each option must be a string");
5594
+ if (opt.length > MAX_OPTION_LENGTH) throw new Error(`request_review_gate: each option must be ${MAX_OPTION_LENGTH} characters or fewer`);
5595
+ }
5596
+ }
5597
+ if (params.recommendation !== void 0) {
5598
+ if (typeof params.recommendation !== "string") throw new Error("request_review_gate: recommendation must be a string");
5599
+ if (params.recommendation.length > MAX_RECOMMENDATION_LENGTH) throw new Error(`request_review_gate: recommendation must be ${MAX_RECOMMENDATION_LENGTH} characters or fewer`);
5600
+ }
5601
+ const options = params.options?.map((o) => o.trim()).filter((o) => o.length > 0);
5602
+ return {
5603
+ description: params.description.trim(),
5604
+ options: options && options.length > 0 ? options : void 0,
5605
+ recommendation: typeof params.recommendation === "string" ? params.recommendation.trim() : void 0
5606
+ };
5607
+ }
5608
+ /**
5609
+ * Format review gates for display output
5610
+ */
5611
+ function formatReviewGatesOutput(gates) {
5612
+ if (gates.length === 0) return "No review gates recorded in this session.";
5613
+ return gates.map((gate, index) => {
5614
+ const lines = [`${index + 1}. **${gate.description}**`, ` Status: ${gate.status}`];
5615
+ if (gate.recommendation) lines.push(` Recommendation: ${gate.recommendation}`);
5616
+ if (gate.options && gate.options.length > 0) {
5617
+ lines.push(" Options:");
5618
+ for (const opt of gate.options) lines.push(` • ${opt}`);
5619
+ }
5620
+ if (gate.userNote) lines.push(` Note: ${gate.userNote}`);
5621
+ const requested = new Date(gate.timestamp).toLocaleTimeString();
5622
+ lines.push(` Requested at: ${requested}`);
5623
+ if (gate.resolvedAt) {
5624
+ const resolved = new Date(gate.resolvedAt).toLocaleTimeString();
5625
+ lines.push(` Resolved at: ${resolved}`);
5626
+ }
5627
+ return lines.join("\n");
5628
+ }).join("\n\n");
5629
+ }
5630
+ /**
5631
+ * Create the request_review_gate tool.
5632
+ *
5633
+ * Pauses agent execution and prompts the user for explicit approval at a
5634
+ * significant decision point. The agent halts until the user responds.
5635
+ *
5636
+ * Decisions are persisted in the session's workflow state (`reviewGates`)
5637
+ * for audit trail and cross-session continuity.
5638
+ */
5639
+ function createReviewGateTool(store, requestReviewFn) {
5640
+ return {
5641
+ toolFn: async (args) => {
5642
+ const params = validateParams(args);
5643
+ const id = crypto.randomUUID();
5644
+ const requestedAt = (/* @__PURE__ */ new Date()).toISOString();
5645
+ const response = await requestReviewFn({
5646
+ id,
5647
+ description: params.description,
5648
+ options: params.options,
5649
+ recommendation: params.recommendation
5650
+ });
5651
+ const trimmedNote = response.note?.trim();
5652
+ const entry = {
5653
+ id,
5654
+ timestamp: requestedAt,
5655
+ description: params.description,
5656
+ status: response.decision,
5657
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
5658
+ userNote: trimmedNote && trimmedNote.length > 0 ? trimmedNote : void 0,
5659
+ options: params.options,
5660
+ recommendation: params.recommendation
5661
+ };
5662
+ store.reviewGates.push(entry);
5663
+ if (store.onUpdate) store.onUpdate(store.reviewGates);
5664
+ const verdict = response.decision === "approved" ? "APPROVED" : "REJECTED";
5665
+ const noteText = entry.userNote ? `\nUser note: ${entry.userNote}` : "";
5666
+ return `Review gate ${verdict} [${id.slice(0, 8)}]: ${params.description}${noteText}`;
5667
+ },
5668
+ toolSchema: {
5669
+ name: "request_review_gate",
5670
+ description: `Pause execution and request explicit human approval at a significant decision point.
5671
+
5672
+ Review gates protect meaning. Stop before crossing decisions that affect interpretation, evidence, cost, credentials, platform, or public commitment.
5673
+
5674
+ **When to use:**
5675
+ - Synthesizing findings before narrowing research scope
5676
+ - Hard-to-reverse decisions (refactors, architectural pivots, dependency swaps)
5677
+ - Decisions affecting cost, credentials, or external commitments
5678
+ - Major direction changes after exploration
5679
+
5680
+ **When NOT to use:**
5681
+ - Routine operations (reading files, running tests, listing directories)
5682
+ - Operations already covered by the standard permission system (file edits, bash commands)
5683
+ - Trivial choices that wouldn't matter to someone resuming this work
5684
+
5685
+ The agent will pause until the user explicitly approves or rejects. The user may attach an optional note to their decision (e.g., to redirect or clarify scope). Treat a rejection as a hard stop — re-plan rather than retry.`,
5686
+ parameters: {
5687
+ type: "object",
5688
+ properties: {
5689
+ description: {
5690
+ type: "string",
5691
+ description: "Clear explanation of what the user is being asked to approve, including relevant context"
5692
+ },
5693
+ options: {
5694
+ type: "array",
5695
+ items: { type: "string" },
5696
+ description: "Optional list of alternatives the user can choose between"
5697
+ },
5698
+ recommendation: {
5699
+ type: "string",
5700
+ description: "Optional recommendation from the AI on the preferred path and why"
5701
+ }
5702
+ },
5703
+ required: ["description"]
5704
+ }
5705
+ }
5706
+ };
5707
+ }
5708
+ /**
5709
+ * Create a new empty ReviewGateStore
5710
+ */
5711
+ function createReviewGateStore(onUpdate) {
5712
+ return {
5713
+ reviewGates: [],
5714
+ onUpdate
5715
+ };
5716
+ }
5717
+ //#endregion
5048
5718
  //#region src/diagnostics/checkers.ts
5049
5719
  const CHECK_TIMEOUT_MS = 12e4;
5050
5720
  const MAX_OUTPUT_BYTES = 16777216;
@@ -7915,7 +8585,7 @@ var BridgePresence = class {
7915
8585
  const gen = this.generation;
7916
8586
  const startOpts = this.startOpts;
7917
8587
  if (!await this.gateEgress(gen, "announce")) return false;
7918
- const instanceId = v4();
8588
+ const instanceId = crypto.randomUUID();
7919
8589
  const workspaceName = this.pendingWorkspaceName;
7920
8590
  const capabilities = this.pendingCapabilities;
7921
8591
  const source = this.pendingSource;
@@ -8825,18 +9495,6 @@ function settlePendingPrompts() {
8825
9495
  }
8826
9496
  //#endregion
8827
9497
  //#region src/session/steering.ts
8828
- /**
8829
- * Steering: user input submitted while a turn runs joins that turn at its next
8830
- * model request instead of waiting for the turn to end.
8831
- *
8832
- * Delivery rides the agent's `drainFeedback` hook (see AgentRunOptions), which
8833
- * fires after a tool batch resolves or when the model answers with iterations
8834
- * left, and is never called once the run is aborted. A drain call is therefore
8835
- * the delivery point: the steers leave the queue and enter the session in one
8836
- * synchronous step, so each one is delivered exactly once - to the model and
8837
- * the transcript together - or stays queued for the host to run as a follow-up
8838
- * turn (turnController.ts) or restore to the input on cancel (index.tsx ESC).
8839
- */
8840
9498
  const STEER_PREAMBLE = "The user sent the following while you were working. Take it into account before you continue, and change course if it asks you to.";
8841
9499
  /** The feedback text the model sees for `steers`, or null when there are none. */
8842
9500
  function formatSteerFeedback(steers) {
@@ -8858,7 +9516,7 @@ function deliverSteers(signal) {
8858
9516
  if (!feedback) return null;
8859
9517
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
8860
9518
  const steerMessages = steers.map((text) => ({
8861
- id: v4(),
9519
+ id: crypto.randomUUID(),
8862
9520
  role: "user",
8863
9521
  content: text,
8864
9522
  timestamp,
@@ -9029,14 +9687,14 @@ async function runHeldTurn(message, ctx, peer) {
9029
9687
  messages: [
9030
9688
  ...activeSession.messages,
9031
9689
  {
9032
- id: v4(),
9690
+ id: crypto.randomUUID(),
9033
9691
  role: "user",
9034
9692
  content: message,
9035
9693
  timestamp,
9036
9694
  metadata: { peer }
9037
9695
  },
9038
9696
  {
9039
- id: v4(),
9697
+ id: crypto.randomUUID(),
9040
9698
  role: "assistant",
9041
9699
  content: error,
9042
9700
  timestamp,
@@ -9110,14 +9768,14 @@ async function runHeldTurn(message, ctx, peer) {
9110
9768
  userMessageContent = message;
9111
9769
  }
9112
9770
  const userMessage = {
9113
- id: v4(),
9771
+ id: crypto.randomUUID(),
9114
9772
  role: "user",
9115
9773
  content: userMessageContent,
9116
9774
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9117
9775
  ...peer ? { metadata: { peer } } : {}
9118
9776
  };
9119
9777
  const pendingAssistantMessage = {
9120
- id: v4(),
9778
+ id: crypto.randomUUID(),
9121
9779
  role: "assistant",
9122
9780
  content: "...",
9123
9781
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -9265,7 +9923,7 @@ async function runHeldTurn(message, ctx, peer) {
9265
9923
  const currentSession = useCliStore.getState().session;
9266
9924
  if (currentSession && !replaced()) {
9267
9925
  const cancelMessage = {
9268
- id: v4(),
9926
+ id: crypto.randomUUID(),
9269
9927
  role: "assistant",
9270
9928
  content: "⚠️ Operation cancelled by user",
9271
9929
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -9290,7 +9948,7 @@ async function runHeldTurn(message, ctx, peer) {
9290
9948
  const currentSession = useCliStore.getState().session;
9291
9949
  if (currentSession) {
9292
9950
  const failedMessage = {
9293
- id: pendingAssistantId ?? v4(),
9951
+ id: pendingAssistantId ?? crypto.randomUUID(),
9294
9952
  role: "assistant",
9295
9953
  content: `Peer turn failed: ${rawMessage}`,
9296
9954
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11184,7 +11842,7 @@ async function createFreshSession(ctx) {
11184
11842
  const model = currentSession?.model || ctx.defaultModel || ChatModels.CLAUDE_5_5_SONNET;
11185
11843
  const clearPinnedId = process.env.B4M_SESSION_ID || process.env.B4M_RESUME_ID;
11186
11844
  const newSession = {
11187
- id: clearPinnedId ? currentSession?.id ?? clearPinnedId : v4(),
11845
+ id: clearPinnedId ? currentSession?.id ?? clearPinnedId : crypto.randomUUID(),
11188
11846
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
11189
11847
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
11190
11848
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11200,7 +11858,7 @@ async function createFreshSession(ctx) {
11200
11858
  logger.debug("=== New Session Started via /clear ===");
11201
11859
  ctx.decisionStore.decisions = [];
11202
11860
  ctx.blockerStore.blockers = [];
11203
- ctx.todoStore.todos = [];
11861
+ resetTodoStore(ctx.todoStore);
11204
11862
  ctx.checkpointStore?.setSessionId(newSession.id);
11205
11863
  useCliStore.getState().setSession(newSession);
11206
11864
  useCliStore.getState().clearPendingMessages();
@@ -11235,6 +11893,7 @@ async function resumeSession(ctx, selected) {
11235
11893
  await logger.initialize(loadedSession.id);
11236
11894
  logger.debug("=== Session Resumed ===");
11237
11895
  ctx.checkpointStore?.setSessionId(loadedSession.id);
11896
+ resetTodoStore(ctx.todoStore);
11238
11897
  const handoff = loadedSession.metadata.workflow?.handoff;
11239
11898
  const messagesForState = handoff ? injectHandoffMessage(loadedSession.messages, handoff) : injectWorkflowStateMessage(loadedSession.messages, loadedSession.metadata.workflow);
11240
11899
  const sessionForState = {
@@ -11488,7 +12147,7 @@ function CliApp() {
11488
12147
  const mcpApprovalResolvedRef = useRef(false);
11489
12148
  const detectedOllamaRef = useRef(null);
11490
12149
  const initGenerationRef = useRef(0);
11491
- const todoStoreRef = useRef(createTodoStore());
12150
+ const todoStoreRef = useRef(createTodoStore((items) => useCliStore.getState().setPlan(items)));
11492
12151
  const decisionStoreRef = useRef(createDecisionStore());
11493
12152
  const blockerStoreRef = useRef(createBlockerStore());
11494
12153
  const reviewGateStoreRef = useRef(createReviewGateStore());
@@ -11804,7 +12463,7 @@ function CliApp() {
11804
12463
  }
11805
12464
  newSession = resumed;
11806
12465
  } else newSession = {
11807
- id: pinnedSessionId || v4(),
12466
+ id: pinnedSessionId || crypto.randomUUID(),
11808
12467
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
11809
12468
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
11810
12469
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11964,7 +12623,7 @@ function CliApp() {
11964
12623
  }) : toolSearchLlm;
11965
12624
  const notifyingLlm = new NotifyingLlmBackend(llmWithFallback, backgroundManager);
11966
12625
  const todoStore = todoStoreRef.current;
11967
- todoStore.todos = [];
12626
+ resetTodoStore(todoStore);
11968
12627
  const writeTodosTool = createWriteTodosTool(todoStore);
11969
12628
  const decisionLogTool = createDecisionLogTool(decisionStoreRef.current);
11970
12629
  const blockerTools = createBlockerTools(blockerStoreRef.current);
@@ -12003,7 +12662,7 @@ function CliApp() {
12003
12662
  const workItemTools = config.preferences.enableWorkItemTools && !apiClient.signedOut ? createWorkItemTools(new WorkItemsClient(apiClient)) : [];
12004
12663
  const peerTools = wrapTools(createPeerTools(() => peerServiceRef.current, async (target, text) => {
12005
12664
  return (await reviewGateFn({
12006
- id: v4(),
12665
+ id: crypto.randomUUID(),
12007
12666
  description: `Send this peer message to ${JSON.stringify(target)}? It may start model usage in the recipient.\n${JSON.stringify(text)}`
12008
12667
  })).decision === "approved";
12009
12668
  }), cliWrapDeps);
@@ -12268,13 +12927,13 @@ function CliApp() {
12268
12927
  messageContent = multimodalMessage.content;
12269
12928
  }
12270
12929
  const userMessage = {
12271
- id: v4(),
12930
+ id: crypto.randomUUID(),
12272
12931
  role: "user",
12273
12932
  content: userMessageContent,
12274
12933
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
12275
12934
  };
12276
12935
  const pendingAssistantMessage = {
12277
- id: v4(),
12936
+ id: crypto.randomUUID(),
12278
12937
  role: "assistant",
12279
12938
  content: "...",
12280
12939
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12586,7 +13245,7 @@ function CliApp() {
12586
13245
  ...prev,
12587
13246
  abortController
12588
13247
  }));
12589
- const pendingId = v4();
13248
+ const pendingId = crypto.randomUUID();
12590
13249
  try {
12591
13250
  const pendingAssistantMessage = {
12592
13251
  id: pendingId,
@@ -12615,7 +13274,7 @@ function CliApp() {
12615
13274
  if (!currentSession || !stillThisSession()) return;
12616
13275
  const richContent = reconstructTurnBlocks(result.steps, result.finalAnswer);
12617
13276
  const continuationMessage = {
12618
- id: v4(),
13277
+ id: crypto.randomUUID(),
12619
13278
  role: "assistant",
12620
13279
  content: "---\n\n**Background Agent Results:**\n\n" + result.finalAnswer,
12621
13280
  ...richContent ? { richContent } : {},
@@ -12682,13 +13341,13 @@ function CliApp() {
12682
13341
  const session = useCliStore.getState().session;
12683
13342
  if (!session || session.id !== sessionId) return;
12684
13343
  const userMessage = {
12685
- id: v4(),
13344
+ id: crypto.randomUUID(),
12686
13345
  role: "user",
12687
13346
  content: `$ ${command}`,
12688
13347
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
12689
13348
  };
12690
13349
  const assistantMessage = {
12691
- id: v4(),
13350
+ id: crypto.randomUUID(),
12692
13351
  role: "assistant",
12693
13352
  content: isError ? `\u274c Error:\n${output}` : output.trim() || "(no output)",
12694
13353
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -12912,7 +13571,7 @@ function CliApp() {
12912
13571
  if (!state.agent) return;
12913
13572
  if (session.messages.length < 4) return;
12914
13573
  if (session.metadata.workflow?.handoff) return;
12915
- const promptId = v4();
13574
+ const promptId = crypto.randomUUID();
12916
13575
  let timer;
12917
13576
  if (!await new Promise((resolve) => {
12918
13577
  let settled = false;
@@ -13373,8 +14032,10 @@ function CliApp() {
13373
14032
  }
13374
14033
  case "clear":
13375
14034
  case "new": {
13376
- console.clear();
13377
- renderBanner();
14035
+ if (!fullscreenEnabled()) {
14036
+ console.clear();
14037
+ renderBanner();
14038
+ }
13378
14039
  const newSession = await createFreshSession(buildLifecycleContext());
13379
14040
  console.log("New session started.");
13380
14041
  console.log(`\n📝 Session: ${newSession.name} | 🤖 Model: ${newSession.model} | 📊 Tokens: 0\n`);
@@ -14442,6 +15103,7 @@ function CliApp() {
14442
15103
  }));
14443
15104
  const allCommands = mergeCommands(state.customCommandStore.getAllCommands(), featureCommandDefs);
14444
15105
  return /* @__PURE__ */ React.createElement(App, {
15106
+ fullscreen: fullscreenEnabled(),
14445
15107
  onMessage: handleMessage,
14446
15108
  onBackgroundCompletion: handleBackgroundCompletion,
14447
15109
  onCommand: handleCommand,
@@ -14496,6 +15158,7 @@ const cachedUpdate = await getStartupUpdateStatus(version);
14496
15158
  if (cachedUpdate?.updateAvailable) console.log(`\x1b[33m \u2b06 Update available: v${cachedUpdate.currentVersion} \u2192 v${cachedUpdate.latestVersion} (run: b4m update)\x1b[0m\n`);
14497
15159
  if (import.meta.url.includes("/src/") || process.env.NODE_ENV === "development") logger.debug("🔧 Running in development mode (using TypeScript source)\n");
14498
15160
  warmFileCache();
14499
- render(/* @__PURE__ */ React.createElement(CliApp, null), { exitOnCtrlC: false });
15161
+ if (fullscreenEnabled()) renderFullscreen(/* @__PURE__ */ React.createElement(CliApp, null));
15162
+ else render(/* @__PURE__ */ React.createElement(CliApp, null), { exitOnCtrlC: false });
14500
15163
  //#endregion
14501
15164
  export {};