@bike4mind/cli 4.9.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 (32) hide show
  1. package/dist/{AgentHistoryStore-jktM0SmD.mjs → AgentHistoryStore-CjGVgxLR.mjs} +186 -586
  2. package/dist/{ApiClient-CczpydlW.mjs → ApiClient-SVXSI3HI.mjs} +3 -3
  3. package/dist/{BubblewrapRuntime-aGfDSJPY.mjs → BubblewrapRuntime-CTc_KPnd.mjs} +2 -2
  4. package/dist/{ConfigStore-CO6kREaL.mjs → ConfigStore-B2Dy-PT9.mjs} +6 -7
  5. package/dist/ConfigStore-zlY0PikB.mjs +2 -0
  6. package/dist/{Logger-CHKCF5hd.mjs → Logger-7MmrU5w6.mjs} +1667 -946
  7. package/dist/{SandboxOrchestrator-ULWvuUct.mjs → SandboxOrchestrator-CeDwd6Fj.mjs} +1 -1
  8. package/dist/{SandboxRuntimeAdapter-FpZRkE6D.mjs → SandboxRuntimeAdapter-CFEIywKt.mjs} +1 -1
  9. package/dist/{SandboxRuntimeAdapter-DpDSET-A.mjs → SandboxRuntimeAdapter-CjNDzYSf.mjs} +2 -2
  10. package/dist/{SeatbeltRuntime-C0GJ3nnY.mjs → SeatbeltRuntime-CQItj-F1.mjs} +2 -2
  11. package/dist/{WorkItemsClient-aCxMV_Wm.mjs → WorkItemsClient-C9_pjHCo.mjs} +3 -4
  12. package/dist/{buildToolSearch-CbLeZ5wP.mjs → buildToolSearch-8xyBwXRx.mjs} +2 -2
  13. package/dist/commands/acpCommand.mjs +6 -7
  14. package/dist/commands/apiCommand.mjs +1 -1
  15. package/dist/commands/doctorCommand.mjs +2 -2
  16. package/dist/commands/envCommand.mjs +1 -1
  17. package/dist/commands/headlessCommand.mjs +10 -11
  18. package/dist/commands/mcpCommand.mjs +3 -3
  19. package/dist/commands/mirrorCommand.mjs +2 -2
  20. package/dist/commands/modelsCommand.mjs +4 -4
  21. package/dist/commands/pluginCommand.mjs +1 -1
  22. package/dist/commands/skillsCommand.mjs +3 -3
  23. package/dist/commands/updateCommand.mjs +2 -2
  24. package/dist/{dist-BOxr8LQA.mjs → dist-DHgMhdzV.mjs} +5443 -217
  25. package/dist/{fit-BHDTSpfd.mjs → fit-D8Quui6j.mjs} +3 -3
  26. package/dist/index.mjs +453 -48
  27. package/dist/{modelServers-CVufZd1f.mjs → modelServers-JsKBm7Wn.mjs} +1 -1
  28. package/dist/{package-TACInPbw.mjs → package-r_xumsGY.mjs} +1 -1
  29. package/dist/{serve-OywSzShu.mjs → serve-BM9PKMLH.mjs} +301 -155
  30. package/dist/{updateChecker-5v_8LhXy.mjs → updateChecker-BOqaLeZU.mjs} +1 -1
  31. package/package.json +10 -42
  32. package/dist/ConfigStore-BAJ4hIHa.mjs +0 -2
package/dist/index.mjs CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import { $ as SIGNED_OUT_BANNER, A as createTodoStore, At as searchFiles, B as isConnectionDrop, C as formatBlockersOutput, Ct as processFileReferences, D as createGetFileStructureTool, Dt as SessionStore, E as formatDecisionsOutput, Et as CommandHistoryStore, F as createCoordinateTaskTool, G as ALWAYS_DENIED_FOR_AGENTS, H as PermissionManager, I as createResumeAgentTool, J as DEFAULT_RETRY_CONFIG, K as DEFAULT_AGENT_MODEL, L as createBackgroundAgentTools, M as resetTodoStore, Mt as COMPACTION_SUMMARY_MARKER, N as createSkillTool, O as createWorkItemTools, Ot as searchCommands, P as parseAgentConfig, Pt as MAX_PASTE_SIZE, Q as NoLocalModelsError, R as createAgentDelegateTool, S as createBlockerTools, St as CustomCommandStore, T as createDecisionStore, Tt as CheckpointStore, U as buildCliToolList, V as substituteArguments, X as LOCAL_SESSION_CONTINUES, Y as DEFAULT_THOROUGHNESS, Z as LOGGED_OUT_RESTART, _t as wrapTools, at as loginBlocked, b as formatReviewGatesOutput, c as checkSavedSignIn, ct as signInUncheckedMessage, dt as buildSystemPrompt, et as SIGN_IN_DURING_TURN, f as buildLlmBackend, ft as buildSkillsPromptSection, gt as findIterationBoundary, j as createWriteTodosTool, jt as warmFileCache, k as createFindDefinitionTool, kt as formatFileSize, l as settleSignInRefresh, lt as signedOutCommandMessage, q as DEFAULT_MAX_ITERATIONS, rt as SIGN_IN_HINT, s as buildSandbox, st as signInUncheckedLoginMessage, tt as SIGN_IN_EXPIRED, u as startupMode, ut as signedOutNoMatchMessage, v as createReviewGateStore, vt as getProcessHooks, w as createDecisionLogTool, wt as hasFileReferences, x as createBlockerStore, xt as getPlanModeFilePath, y as createReviewGateTool, yt as setWebSocketToolExecutor, z as FallbackLlmBackend } from "./AgentHistoryStore-jktM0SmD.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-CO6kREaL.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
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-BOxr8LQA.mjs";
6
- import { $t as tokenEstimateMultiplier, Bt as planProgress, C as CREDIT_DEDUCT_TRANSACTION_TYPES, Dt as isEarlyStop, T as ChatModels, 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, zt as planLeaves } from "./Logger-CHKCF5hd.mjs";
7
- import { a as rewireReservedNames, i as mergeCommands, t as RemoteSkillSource } from "./RemoteSkillSource-D_F99yBR.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-aCxMV_Wm.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-CczpydlW.mjs";
12
- import { t as version } from "./package-TACInPbw.mjs";
13
- import { a as NotifyingLlmBackend, i as deferredToolRegistry, n as buildAgent, r as buildSupportingStores, t as buildToolSearch } from "./buildToolSearch-CbLeZ5wP.mjs";
14
- import { s as getStartupUpdateStatus } from "./updateChecker-5v_8LhXy.mjs";
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
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
17
  import { formatWithOptions, promisify } from "node:util";
@@ -19,12 +19,12 @@ import { randomBytes } from "crypto";
19
19
  import { constants, existsSync, promises, readFileSync, statSync } from "fs";
20
20
  import { homedir } from "os";
21
21
  import path, { basename, extname, join } from "path";
22
- import { v4 } from "uuid";
23
22
  import * as path$2 from "node:path";
24
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";
25
24
  import { constants as constants$1, promises as promises$1 } from "node:fs";
26
25
  import { z as z$1 } from "zod";
27
26
  import axios, { isAxiosError } from "axios";
27
+ import Fuse from "fuse.js";
28
28
  import Spinner from "ink-spinner";
29
29
  import { useShallow } from "zustand/react/shallow";
30
30
  import wrapAnsi from "wrap-ansi";
@@ -37,7 +37,6 @@ import { marked } from "marked";
37
37
  import { highlight } from "cli-highlight";
38
38
  import { chmod, lstat, mkdir, mkdtemp, open, opendir, realpath, rename, rm, rmdir } from "node:fs/promises";
39
39
  import SelectInput from "ink-select-input";
40
- import jwt from "jsonwebtoken";
41
40
  import open$1 from "open";
42
41
  import { execFile as execFile$1 } from "node:child_process";
43
42
  import { createConnection, createServer } from "node:net";
@@ -468,6 +467,33 @@ function FileAutocomplete({ files, selectedIndex, query }) {
468
467
  }));
469
468
  }
470
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
471
497
  //#region src/utils/imageDetector.ts
472
498
  /**
473
499
  * Detects pasted images and dropped files from terminal input
@@ -3559,6 +3585,25 @@ async function copyToClipboard(text, deps = {}) {
3559
3585
  return (isSshSession(env) ? sentFirst : sendOsc52()) ? "terminal" : "failed";
3560
3586
  }
3561
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
3562
3607
  //#region src/components/LoginFlow.tsx
3563
3608
  /**
3564
3609
  * Only https URLs (and http on localhost for dev) may be handed to the OS opener.
@@ -3662,7 +3707,7 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
3662
3707
  const tokens = await oauth.waitForAuthorization(deviceFlowResponse.device_code, deviceFlowResponse.interval, (message) => setStatusMessage(message), abort.signal);
3663
3708
  if (abort.signal.aborted) return;
3664
3709
  tokenIssued.current = true;
3665
- const userId = jwt.decode(tokens.access_token)?.id || "";
3710
+ const userId = decodeJwtUserId(tokens.access_token);
3666
3711
  const expiresAt = new Date(Date.now() + tokens.expires_in * 1e3).toISOString();
3667
3712
  await configStore.withRefreshLock(() => configStore.setAuthTokens({
3668
3713
  accessToken: tokens.access_token,
@@ -4307,7 +4352,7 @@ function isInjectedContinuity(message) {
4307
4352
  */
4308
4353
  function injectHandoffMessage(messages, handoff) {
4309
4354
  return [{
4310
- id: v4(),
4355
+ id: crypto.randomUUID(),
4311
4356
  role: "user",
4312
4357
  content: buildHandoffSystemMessage(handoff),
4313
4358
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -4337,7 +4382,7 @@ function injectWorkflowStateMessage(messages, workflow) {
4337
4382
  });
4338
4383
  if (!text) return withoutPriorInjections;
4339
4384
  return [{
4340
- id: v4(),
4385
+ id: crypto.randomUUID(),
4341
4386
  role: "user",
4342
4387
  content: `${WORKFLOW_STATE_MARKER}\n\n${text}`,
4343
4388
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -4599,14 +4644,14 @@ function buildCompactionPrompt(messages, options = {}) {
4599
4644
  */
4600
4645
  function createCompactedSession(originalSession, summary, preservedMessages, preserveId = false) {
4601
4646
  const summaryMessage = {
4602
- id: v4(),
4647
+ id: crypto.randomUUID(),
4603
4648
  role: "user",
4604
4649
  content: `${COMPACTION_SUMMARY_MARKER}\n\n${summary}`,
4605
4650
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
4606
4651
  };
4607
4652
  const handoff = originalSession.metadata.workflow?.handoff;
4608
4653
  const handoffMessage = handoff ? {
4609
- id: v4(),
4654
+ id: crypto.randomUUID(),
4610
4655
  role: "user",
4611
4656
  content: buildHandoffSystemMessage(handoff),
4612
4657
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -4617,7 +4662,7 @@ function createCompactedSession(originalSession, summary, preservedMessages, pre
4617
4662
  ...preservedMessages
4618
4663
  ] : [summaryMessage, ...preservedMessages];
4619
4664
  return {
4620
- id: preserveId ? originalSession.id : v4(),
4665
+ id: preserveId ? originalSession.id : crypto.randomUUID(),
4621
4666
  name: `${originalSession.name} (compacted)`,
4622
4667
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4623
4668
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -5298,6 +5343,378 @@ Unlike agent_delegate (which uses pre-defined agents), this tool lets you compos
5298
5343
  };
5299
5344
  }
5300
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
5301
5718
  //#region src/diagnostics/checkers.ts
5302
5719
  const CHECK_TIMEOUT_MS = 12e4;
5303
5720
  const MAX_OUTPUT_BYTES = 16777216;
@@ -8168,7 +8585,7 @@ var BridgePresence = class {
8168
8585
  const gen = this.generation;
8169
8586
  const startOpts = this.startOpts;
8170
8587
  if (!await this.gateEgress(gen, "announce")) return false;
8171
- const instanceId = v4();
8588
+ const instanceId = crypto.randomUUID();
8172
8589
  const workspaceName = this.pendingWorkspaceName;
8173
8590
  const capabilities = this.pendingCapabilities;
8174
8591
  const source = this.pendingSource;
@@ -9078,18 +9495,6 @@ function settlePendingPrompts() {
9078
9495
  }
9079
9496
  //#endregion
9080
9497
  //#region src/session/steering.ts
9081
- /**
9082
- * Steering: user input submitted while a turn runs joins that turn at its next
9083
- * model request instead of waiting for the turn to end.
9084
- *
9085
- * Delivery rides the agent's `drainFeedback` hook (see AgentRunOptions), which
9086
- * fires after a tool batch resolves or when the model answers with iterations
9087
- * left, and is never called once the run is aborted. A drain call is therefore
9088
- * the delivery point: the steers leave the queue and enter the session in one
9089
- * synchronous step, so each one is delivered exactly once - to the model and
9090
- * the transcript together - or stays queued for the host to run as a follow-up
9091
- * turn (turnController.ts) or restore to the input on cancel (index.tsx ESC).
9092
- */
9093
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.";
9094
9499
  /** The feedback text the model sees for `steers`, or null when there are none. */
9095
9500
  function formatSteerFeedback(steers) {
@@ -9111,7 +9516,7 @@ function deliverSteers(signal) {
9111
9516
  if (!feedback) return null;
9112
9517
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
9113
9518
  const steerMessages = steers.map((text) => ({
9114
- id: v4(),
9519
+ id: crypto.randomUUID(),
9115
9520
  role: "user",
9116
9521
  content: text,
9117
9522
  timestamp,
@@ -9282,14 +9687,14 @@ async function runHeldTurn(message, ctx, peer) {
9282
9687
  messages: [
9283
9688
  ...activeSession.messages,
9284
9689
  {
9285
- id: v4(),
9690
+ id: crypto.randomUUID(),
9286
9691
  role: "user",
9287
9692
  content: message,
9288
9693
  timestamp,
9289
9694
  metadata: { peer }
9290
9695
  },
9291
9696
  {
9292
- id: v4(),
9697
+ id: crypto.randomUUID(),
9293
9698
  role: "assistant",
9294
9699
  content: error,
9295
9700
  timestamp,
@@ -9363,14 +9768,14 @@ async function runHeldTurn(message, ctx, peer) {
9363
9768
  userMessageContent = message;
9364
9769
  }
9365
9770
  const userMessage = {
9366
- id: v4(),
9771
+ id: crypto.randomUUID(),
9367
9772
  role: "user",
9368
9773
  content: userMessageContent,
9369
9774
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9370
9775
  ...peer ? { metadata: { peer } } : {}
9371
9776
  };
9372
9777
  const pendingAssistantMessage = {
9373
- id: v4(),
9778
+ id: crypto.randomUUID(),
9374
9779
  role: "assistant",
9375
9780
  content: "...",
9376
9781
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -9518,7 +9923,7 @@ async function runHeldTurn(message, ctx, peer) {
9518
9923
  const currentSession = useCliStore.getState().session;
9519
9924
  if (currentSession && !replaced()) {
9520
9925
  const cancelMessage = {
9521
- id: v4(),
9926
+ id: crypto.randomUUID(),
9522
9927
  role: "assistant",
9523
9928
  content: "⚠️ Operation cancelled by user",
9524
9929
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -9543,7 +9948,7 @@ async function runHeldTurn(message, ctx, peer) {
9543
9948
  const currentSession = useCliStore.getState().session;
9544
9949
  if (currentSession) {
9545
9950
  const failedMessage = {
9546
- id: pendingAssistantId ?? v4(),
9951
+ id: pendingAssistantId ?? crypto.randomUUID(),
9547
9952
  role: "assistant",
9548
9953
  content: `Peer turn failed: ${rawMessage}`,
9549
9954
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11437,7 +11842,7 @@ async function createFreshSession(ctx) {
11437
11842
  const model = currentSession?.model || ctx.defaultModel || ChatModels.CLAUDE_5_5_SONNET;
11438
11843
  const clearPinnedId = process.env.B4M_SESSION_ID || process.env.B4M_RESUME_ID;
11439
11844
  const newSession = {
11440
- id: clearPinnedId ? currentSession?.id ?? clearPinnedId : v4(),
11845
+ id: clearPinnedId ? currentSession?.id ?? clearPinnedId : crypto.randomUUID(),
11441
11846
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
11442
11847
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
11443
11848
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12058,7 +12463,7 @@ function CliApp() {
12058
12463
  }
12059
12464
  newSession = resumed;
12060
12465
  } else newSession = {
12061
- id: pinnedSessionId || v4(),
12466
+ id: pinnedSessionId || crypto.randomUUID(),
12062
12467
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
12063
12468
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
12064
12469
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12257,7 +12662,7 @@ function CliApp() {
12257
12662
  const workItemTools = config.preferences.enableWorkItemTools && !apiClient.signedOut ? createWorkItemTools(new WorkItemsClient(apiClient)) : [];
12258
12663
  const peerTools = wrapTools(createPeerTools(() => peerServiceRef.current, async (target, text) => {
12259
12664
  return (await reviewGateFn({
12260
- id: v4(),
12665
+ id: crypto.randomUUID(),
12261
12666
  description: `Send this peer message to ${JSON.stringify(target)}? It may start model usage in the recipient.\n${JSON.stringify(text)}`
12262
12667
  })).decision === "approved";
12263
12668
  }), cliWrapDeps);
@@ -12522,13 +12927,13 @@ function CliApp() {
12522
12927
  messageContent = multimodalMessage.content;
12523
12928
  }
12524
12929
  const userMessage = {
12525
- id: v4(),
12930
+ id: crypto.randomUUID(),
12526
12931
  role: "user",
12527
12932
  content: userMessageContent,
12528
12933
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
12529
12934
  };
12530
12935
  const pendingAssistantMessage = {
12531
- id: v4(),
12936
+ id: crypto.randomUUID(),
12532
12937
  role: "assistant",
12533
12938
  content: "...",
12534
12939
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12840,7 +13245,7 @@ function CliApp() {
12840
13245
  ...prev,
12841
13246
  abortController
12842
13247
  }));
12843
- const pendingId = v4();
13248
+ const pendingId = crypto.randomUUID();
12844
13249
  try {
12845
13250
  const pendingAssistantMessage = {
12846
13251
  id: pendingId,
@@ -12869,7 +13274,7 @@ function CliApp() {
12869
13274
  if (!currentSession || !stillThisSession()) return;
12870
13275
  const richContent = reconstructTurnBlocks(result.steps, result.finalAnswer);
12871
13276
  const continuationMessage = {
12872
- id: v4(),
13277
+ id: crypto.randomUUID(),
12873
13278
  role: "assistant",
12874
13279
  content: "---\n\n**Background Agent Results:**\n\n" + result.finalAnswer,
12875
13280
  ...richContent ? { richContent } : {},
@@ -12936,13 +13341,13 @@ function CliApp() {
12936
13341
  const session = useCliStore.getState().session;
12937
13342
  if (!session || session.id !== sessionId) return;
12938
13343
  const userMessage = {
12939
- id: v4(),
13344
+ id: crypto.randomUUID(),
12940
13345
  role: "user",
12941
13346
  content: `$ ${command}`,
12942
13347
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
12943
13348
  };
12944
13349
  const assistantMessage = {
12945
- id: v4(),
13350
+ id: crypto.randomUUID(),
12946
13351
  role: "assistant",
12947
13352
  content: isError ? `\u274c Error:\n${output}` : output.trim() || "(no output)",
12948
13353
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -13166,7 +13571,7 @@ function CliApp() {
13166
13571
  if (!state.agent) return;
13167
13572
  if (session.messages.length < 4) return;
13168
13573
  if (session.metadata.workflow?.handoff) return;
13169
- const promptId = v4();
13574
+ const promptId = crypto.randomUUID();
13170
13575
  let timer;
13171
13576
  if (!await new Promise((resolve) => {
13172
13577
  let settled = false;