@bike4mind/cli 4.9.0 → 5.0.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 (33) hide show
  1. package/dist/{AgentHistoryStore-jktM0SmD.mjs → AgentHistoryStore-C3hJOgpM.mjs} +374 -676
  2. package/dist/{ApiClient-CczpydlW.mjs → ApiClient-CeuIcSY8.mjs} +3 -3
  3. package/dist/{BubblewrapRuntime-aGfDSJPY.mjs → BubblewrapRuntime-BF5wXaNS.mjs} +2 -2
  4. package/dist/ConfigStore--dPqdX3O.mjs +2 -0
  5. package/dist/{ConfigStore-CO6kREaL.mjs → ConfigStore-nr0ebq4v.mjs} +6 -7
  6. package/dist/{Logger-CHKCF5hd.mjs → Logger-CovZt7LL.mjs} +2159 -1032
  7. package/dist/{RemoteSkillSource-D_F99yBR.mjs → RemoteSkillSource-HqoLRV56.mjs} +2 -6
  8. package/dist/{SandboxOrchestrator-ULWvuUct.mjs → SandboxOrchestrator-DTz_5Zub.mjs} +1 -1
  9. package/dist/{SandboxRuntimeAdapter-DpDSET-A.mjs → SandboxRuntimeAdapter-CC5KlbZ8.mjs} +2 -2
  10. package/dist/{SandboxRuntimeAdapter-FpZRkE6D.mjs → SandboxRuntimeAdapter-X0HAkbpW.mjs} +1 -1
  11. package/dist/{SeatbeltRuntime-C0GJ3nnY.mjs → SeatbeltRuntime-zdxVqGZ3.mjs} +2 -2
  12. package/dist/{WorkItemsClient-aCxMV_Wm.mjs → WorkItemsClient-lKJCPP0j.mjs} +3 -4
  13. package/dist/{buildToolSearch-CbLeZ5wP.mjs → buildToolSearch-BlOSK4m3.mjs} +2 -2
  14. package/dist/commands/acpCommand.mjs +7 -8
  15. package/dist/commands/apiCommand.mjs +1 -1
  16. package/dist/commands/doctorCommand.mjs +2 -2
  17. package/dist/commands/envCommand.mjs +1 -1
  18. package/dist/commands/headlessCommand.mjs +11 -12
  19. package/dist/commands/mcpCommand.mjs +3 -3
  20. package/dist/commands/mirrorCommand.mjs +2 -2
  21. package/dist/commands/modelsCommand.mjs +4 -4
  22. package/dist/commands/pluginCommand.mjs +1 -1
  23. package/dist/commands/skillsCommand.mjs +4 -4
  24. package/dist/commands/updateCommand.mjs +2 -2
  25. package/dist/{dist-BOxr8LQA.mjs → dist-BrBjZ6Cv.mjs} +5442 -186
  26. package/dist/{fit-BHDTSpfd.mjs → fit-vnmP4Dfc.mjs} +3 -3
  27. package/dist/index.mjs +455 -455
  28. package/dist/{modelServers-CVufZd1f.mjs → modelServers-CjSlPFsg.mjs} +1 -1
  29. package/dist/{package-TACInPbw.mjs → package-BTvxFRbB.mjs} +1 -1
  30. package/dist/{serve-OywSzShu.mjs → serve-BLBhPkyw.mjs} +301 -155
  31. package/dist/{updateChecker-5v_8LhXy.mjs → updateChecker-uDIZuEZg.mjs} +1 -1
  32. package/package.json +10 -43
  33. 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-C3hJOgpM.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-nr0ebq4v.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-BrBjZ6Cv.mjs";
6
+ import { C as CREDIT_DEDUCT_TRANSACTION_TYPES, Et as isEarlyStop, Rt as planLeaves, T as ChatModels, Zt as tokenEstimateMultiplier, an as DELEGATION_PAYLOAD_SCHEMA_NAME, cn as actorKindSchema, in as ACTOR_COLOR_SLOTS, ln as delegationPayloadSchema, n as SESSION_ID_PATTERN, on as actorColorIndex, r as isValidSessionId, sn as actorKindMarker, t as logger, un as selfClaimedActorKindSchema, zt as planProgress } from "./Logger-CovZt7LL.mjs";
7
+ import { a as rewireReservedNames, i as mergeCommands, n as COMMANDS, t as RemoteSkillSource } from "./RemoteSkillSource-HqoLRV56.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-lKJCPP0j.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-CeuIcSY8.mjs";
12
+ import { t as version } from "./package-BTvxFRbB.mjs";
13
+ import { a as NotifyingLlmBackend, i as deferredToolRegistry, n as buildAgent, r as buildSupportingStores, t as buildToolSearch } from "./buildToolSearch-BlOSK4m3.mjs";
14
+ import { s as getStartupUpdateStatus } from "./updateChecker-uDIZuEZg.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;
@@ -5947,27 +6364,6 @@ var TavernService = class {
5947
6364
  async abortHeartbeats() {
5948
6365
  await this.apiClient.post("/api/tavern/abort-heartbeats", { abort: true });
5949
6366
  }
5950
- async getQuestPlan(planId) {
5951
- return this.apiClient.get(`/api/quest-master-plans/${encodeURIComponent(planId)}`);
5952
- }
5953
- async updateReviewGate(planId, questId, subQuestId, reviewStatus, reviewNote) {
5954
- return this.apiClient.post(`/api/quest-master-plans/${encodeURIComponent(planId)}/review-gate`, {
5955
- questId,
5956
- subQuestId,
5957
- reviewStatus,
5958
- reviewNote
5959
- });
5960
- }
5961
- async updateSubQuestProgress(planId, questId, subQuestId, updates) {
5962
- return this.apiClient.post(`/api/quest-master-plans/${encodeURIComponent(planId)}/subquest-progress`, {
5963
- questId,
5964
- subQuestId,
5965
- ...updates
5966
- });
5967
- }
5968
- async updateHandoff(planId, handoff) {
5969
- return this.apiClient.post(`/api/quest-master-plans/${encodeURIComponent(planId)}/handoff`, handoff);
5970
- }
5971
6367
  };
5972
6368
  //#endregion
5973
6369
  //#region src/features/tavern/types.ts
@@ -6155,89 +6551,6 @@ z$1.object({
6155
6551
  error: z$1.string().optional()
6156
6552
  }))
6157
6553
  });
6158
- /** Sub-quest within a quest */
6159
- const SubQuestSchema = z$1.object({
6160
- id: z$1.string(),
6161
- title: z$1.string(),
6162
- status: z$1.enum(SUBQUEST_STATUS_VALUES),
6163
- questId: z$1.string().optional(),
6164
- startedAt: z$1.number().optional(),
6165
- evidence: z$1.string().optional(),
6166
- reviewGate: z$1.boolean().optional(),
6167
- reviewStatus: z$1.enum(REVIEW_GATE_STATUS_VALUES).optional(),
6168
- reviewNote: z$1.string().optional()
6169
- });
6170
- /** Quest containing sub-quests */
6171
- const QuestDataSchema = z$1.object({
6172
- id: z$1.string(),
6173
- title: z$1.string(),
6174
- description: z$1.string(),
6175
- complexity: z$1.string(),
6176
- subQuests: z$1.array(SubQuestSchema)
6177
- });
6178
- /** Handoff state for session continuity */
6179
- const HandoffSchema = z$1.object({
6180
- summary: z$1.string(),
6181
- nextSteps: z$1.array(z$1.string()),
6182
- pendingDecisions: z$1.array(z$1.string()),
6183
- blockers: z$1.array(z$1.string()),
6184
- lastUpdatedBy: z$1.string(),
6185
- updatedAt: z$1.string()
6186
- });
6187
- z$1.object({
6188
- id: z$1.string(),
6189
- notebookId: z$1.string(),
6190
- goal: z$1.string(),
6191
- quests: z$1.array(QuestDataSchema),
6192
- state: z$1.enum([
6193
- "draft",
6194
- "active",
6195
- "paused",
6196
- "completed",
6197
- "archived"
6198
- ]).optional(),
6199
- handoff: HandoffSchema.optional(),
6200
- metrics: z$1.object({
6201
- totalTimeSpent: z$1.number(),
6202
- completionRate: z$1.number(),
6203
- subQuestsCompleted: z$1.number(),
6204
- subQuestsTotal: z$1.number(),
6205
- lastProgress: z$1.string().optional()
6206
- }).optional()
6207
- });
6208
- z$1.object({
6209
- planId: z$1.string(),
6210
- questId: z$1.string(),
6211
- subQuestId: z$1.string(),
6212
- reviewStatus: z$1.enum(REVIEW_GATE_STATUS_VALUES),
6213
- reviewNote: z$1.string().optional()
6214
- });
6215
- z$1.object({
6216
- planId: z$1.string(),
6217
- questId: z$1.string(),
6218
- subQuestId: z$1.string(),
6219
- status: z$1.enum(SUBQUEST_STATUS_VALUES).optional(),
6220
- evidence: z$1.string().optional(),
6221
- timeSpent: z$1.number().optional()
6222
- });
6223
- z$1.object({
6224
- planId: z$1.string(),
6225
- summary: z$1.string(),
6226
- nextSteps: z$1.array(z$1.string()),
6227
- pendingDecisions: z$1.array(z$1.string()),
6228
- blockers: z$1.array(z$1.string())
6229
- });
6230
- z$1.object({
6231
- success: z$1.boolean(),
6232
- plan: z$1.unknown().optional(),
6233
- metrics: z$1.object({
6234
- totalTimeSpent: z$1.number(),
6235
- completionRate: z$1.number(),
6236
- subQuestsCompleted: z$1.number(),
6237
- subQuestsTotal: z$1.number(),
6238
- lastProgress: z$1.string().optional()
6239
- }).optional()
6240
- });
6241
6554
  //#endregion
6242
6555
  //#region src/features/tavern/TavernActivityStream.ts
6243
6556
  /**
@@ -6272,29 +6585,6 @@ var TavernActivityStream = class {
6272
6585
  };
6273
6586
  //#endregion
6274
6587
  //#region src/features/tavern/tavernTools.ts
6275
- const GetQuestPlanParamsSchema = z$1.object({ plan_id: z$1.string().min(1) });
6276
- const UpdateReviewGateParamsSchema = z$1.object({
6277
- plan_id: z$1.string().min(1),
6278
- quest_id: z$1.string().min(1),
6279
- sub_quest_id: z$1.string().min(1),
6280
- review_status: z$1.enum(REVIEW_GATE_STATUS_VALUES),
6281
- review_note: z$1.string().optional()
6282
- });
6283
- const UpdateQuestProgressParamsSchema = z$1.object({
6284
- plan_id: z$1.string().min(1),
6285
- quest_id: z$1.string().min(1),
6286
- sub_quest_id: z$1.string().min(1),
6287
- status: z$1.enum(SUBQUEST_STATUS_VALUES).optional(),
6288
- evidence: z$1.string().optional(),
6289
- time_spent: z$1.number().min(0).optional()
6290
- });
6291
- const WriteHandoffParamsSchema = z$1.object({
6292
- plan_id: z$1.string().min(1),
6293
- summary: z$1.string().min(1),
6294
- next_steps: z$1.array(z$1.string()),
6295
- pending_decisions: z$1.array(z$1.string()),
6296
- blockers: z$1.array(z$1.string())
6297
- });
6298
6588
  /**
6299
6589
  * Factory that creates ICompletionOptionTools[] for the Tavern feature.
6300
6590
  * Each tool is a pure adapter: schema + delegation to the service.
@@ -6315,11 +6605,7 @@ function createTavernTools(service) {
6315
6605
  createToggleHeartbeatsTool(service),
6316
6606
  createTriggerHeartbeatTool(service),
6317
6607
  createAbortHeartbeatsTool(service),
6318
- createStatusTool(service),
6319
- createGetQuestPlanTool(service),
6320
- createUpdateReviewGateTool(service),
6321
- createUpdateQuestProgressTool(service),
6322
- createWriteHandoffTool(service)
6608
+ createStatusTool(service)
6323
6609
  ];
6324
6610
  }
6325
6611
  function createListAgentsTool(service) {
@@ -6848,177 +7134,6 @@ function createStatusTool(service) {
6848
7134
  }
6849
7135
  };
6850
7136
  }
6851
- function createGetQuestPlanTool(service) {
6852
- return {
6853
- toolSchema: {
6854
- name: "tavern_get_quest_plan",
6855
- description: "Fetch a quest master plan by ID. Returns the full plan with all quests, sub-quests, review gate status, handoff state, and progress metrics. Use this to check which sub-quests have review gates and their current status.",
6856
- parameters: {
6857
- type: "object",
6858
- properties: { plan_id: {
6859
- type: "string",
6860
- description: "The MongoDB ObjectId of the quest master plan"
6861
- } },
6862
- required: ["plan_id"]
6863
- }
6864
- },
6865
- toolFn: async (params) => {
6866
- const { plan_id } = GetQuestPlanParamsSchema.parse(params);
6867
- const result = await service.getQuestPlan(plan_id);
6868
- return JSON.stringify(result);
6869
- }
6870
- };
6871
- }
6872
- function createUpdateReviewGateTool(service) {
6873
- return {
6874
- toolSchema: {
6875
- name: "tavern_update_review_gate",
6876
- description: "Approve or reject a review gate on a sub-quest. Review gates are human approval checkpoints — when a sub-quest has reviewGate: true, the AI must stop and wait for human approval before proceeding.",
6877
- parameters: {
6878
- type: "object",
6879
- properties: {
6880
- plan_id: {
6881
- type: "string",
6882
- description: "The MongoDB ObjectId of the quest master plan"
6883
- },
6884
- quest_id: {
6885
- type: "string",
6886
- description: "The ID of the parent quest"
6887
- },
6888
- sub_quest_id: {
6889
- type: "string",
6890
- description: "The ID of the sub-quest with the review gate"
6891
- },
6892
- review_status: {
6893
- type: "string",
6894
- description: "The review decision",
6895
- enum: [...REVIEW_GATE_STATUS_VALUES]
6896
- },
6897
- review_note: {
6898
- type: "string",
6899
- description: "Optional note explaining the review decision"
6900
- }
6901
- },
6902
- required: [
6903
- "plan_id",
6904
- "quest_id",
6905
- "sub_quest_id",
6906
- "review_status"
6907
- ]
6908
- }
6909
- },
6910
- toolFn: async (params) => {
6911
- const { plan_id, quest_id, sub_quest_id, review_status, review_note } = UpdateReviewGateParamsSchema.parse(params);
6912
- const result = await service.updateReviewGate(plan_id, quest_id, sub_quest_id, review_status, review_note);
6913
- return JSON.stringify(result);
6914
- }
6915
- };
6916
- }
6917
- function createUpdateQuestProgressTool(service) {
6918
- return {
6919
- toolSchema: {
6920
- name: "tavern_update_quest_progress",
6921
- description: "Update a sub-quest's progress. Set status to track completion, add evidence of what was accomplished, and optionally record time spent. Setting status to \"in_progress\" auto-resumes a paused plan.",
6922
- parameters: {
6923
- type: "object",
6924
- properties: {
6925
- plan_id: {
6926
- type: "string",
6927
- description: "The MongoDB ObjectId of the quest master plan"
6928
- },
6929
- quest_id: {
6930
- type: "string",
6931
- description: "The ID of the parent quest"
6932
- },
6933
- sub_quest_id: {
6934
- type: "string",
6935
- description: "The ID of the sub-quest to update"
6936
- },
6937
- status: {
6938
- type: "string",
6939
- description: "New status for the sub-quest",
6940
- enum: [...SUBQUEST_STATUS_VALUES]
6941
- },
6942
- evidence: {
6943
- type: "string",
6944
- description: "Evidence of completion — links to artifacts, descriptions of output, or references to results"
6945
- },
6946
- time_spent: {
6947
- type: "number",
6948
- description: "Time spent on this sub-quest in milliseconds"
6949
- }
6950
- },
6951
- required: [
6952
- "plan_id",
6953
- "quest_id",
6954
- "sub_quest_id"
6955
- ]
6956
- }
6957
- },
6958
- toolFn: async (params) => {
6959
- const { plan_id, quest_id, sub_quest_id, status, evidence, time_spent } = UpdateQuestProgressParamsSchema.parse(params);
6960
- const updates = {};
6961
- if (status !== void 0) updates.status = status;
6962
- if (evidence !== void 0) updates.evidence = evidence;
6963
- if (time_spent !== void 0) updates.timeSpent = time_spent;
6964
- const result = await service.updateSubQuestProgress(plan_id, quest_id, sub_quest_id, updates);
6965
- return JSON.stringify(result);
6966
- }
6967
- };
6968
- }
6969
- function createWriteHandoffTool(service) {
6970
- return {
6971
- toolSchema: {
6972
- name: "tavern_write_handoff",
6973
- description: "Write a handoff state for session continuity. Called when ending a session so the next session can resume with full context. Includes a summary of progress, next steps, pending decisions, and blockers.",
6974
- parameters: {
6975
- type: "object",
6976
- properties: {
6977
- plan_id: {
6978
- type: "string",
6979
- description: "The MongoDB ObjectId of the quest master plan"
6980
- },
6981
- summary: {
6982
- type: "string",
6983
- description: "Summary of what was accomplished in this session"
6984
- },
6985
- next_steps: {
6986
- type: "array",
6987
- items: { type: "string" },
6988
- description: "List of next steps for the following session"
6989
- },
6990
- pending_decisions: {
6991
- type: "array",
6992
- items: { type: "string" },
6993
- description: "Decisions that still need to be made"
6994
- },
6995
- blockers: {
6996
- type: "array",
6997
- items: { type: "string" },
6998
- description: "Current blockers preventing progress"
6999
- }
7000
- },
7001
- required: [
7002
- "plan_id",
7003
- "summary",
7004
- "next_steps",
7005
- "pending_decisions",
7006
- "blockers"
7007
- ]
7008
- }
7009
- },
7010
- toolFn: async (params) => {
7011
- const { plan_id, summary, next_steps, pending_decisions, blockers } = WriteHandoffParamsSchema.parse(params);
7012
- const result = await service.updateHandoff(plan_id, {
7013
- summary,
7014
- nextSteps: next_steps,
7015
- pendingDecisions: pending_decisions,
7016
- blockers
7017
- });
7018
- return JSON.stringify(result);
7019
- }
7020
- };
7021
- }
7022
7137
  //#endregion
7023
7138
  //#region src/features/tavern/TavernModule.ts
7024
7139
  /** Icons for heartbeat log actions shown in /tavern command */
@@ -7082,23 +7197,9 @@ Available actions:
7082
7197
  - **tavern_trigger_heartbeat**: Manually trigger a heartbeat cycle
7083
7198
  - **tavern_abort_heartbeats**: Emergency stop all in-flight heartbeats
7084
7199
  - **tavern_status**: Quick overview of agents, quests, and gates — good for situational awareness
7085
- - **tavern_get_quest_plan**: Fetch a quest master plan with review gate status and handoff state
7086
- - **tavern_update_review_gate**: Approve or reject a review gate on a sub-quest
7087
- - **tavern_update_quest_progress**: Update sub-quest status and record evidence of completion
7088
- - **tavern_write_handoff**: Write session handoff for continuity across sessions
7089
7200
 
7090
7201
  When the user mentions talking to agents, checking the quest board, or managing the tavern, use these tools.
7091
- Agents have personalities, moods, quests, and memories — they are autonomous entities, not chatbots.
7092
-
7093
- ## Quest Workflow (Review Gates)
7094
- When working on a quest plan with review gates (reviewGate: true on sub-quests), you MUST:
7095
- 1. Check review gate status with tavern_get_quest_plan before proceeding past a gated step
7096
- 2. If the next sub-quest has reviewGate: true and reviewStatus is not 'approved', STOP and inform the user
7097
- 3. Record evidence of completion with tavern_update_quest_progress when finishing a sub-quest
7098
- 4. Write a handoff with tavern_write_handoff before ending a session with an active quest plan
7099
-
7100
- ## Session Handoff & Resume
7101
- When the user runs /quest resume <plan_id>, read the handoff context and continue from where the previous session left off. The handoff contains: summary of prior work, next steps, pending decisions, and blockers.`;
7202
+ Agents have personalities, moods, quests, and memories - they are autonomous entities, not chatbots.`;
7102
7203
  }
7103
7204
  getCommands() {
7104
7205
  return [{
@@ -7123,95 +7224,6 @@ When the user runs /quest resume <plan_id>, read the handoff context and continu
7123
7224
  }
7124
7225
  console.log("");
7125
7226
  }
7126
- }, {
7127
- name: "quest",
7128
- description: "Quest workflow commands: review gates, resume from handoff",
7129
- execute: async (args) => {
7130
- const subCommand = args[0];
7131
- if (subCommand === "resume") {
7132
- const planId = args[1];
7133
- if (!planId) {
7134
- console.log("\nUsage: /quest resume <plan_id>");
7135
- console.log(" Loads the quest plan and displays the session handoff for continuity.\n");
7136
- return;
7137
- }
7138
- try {
7139
- const plan = await this.service.getQuestPlan(planId);
7140
- console.log(`\nQuest Plan: ${plan.goal}`);
7141
- console.log(`State: ${plan.state ?? "unknown"}`);
7142
- if (plan.metrics) {
7143
- const pct = Math.round(plan.metrics.completionRate * 100);
7144
- console.log(`Progress: ${plan.metrics.subQuestsCompleted}/${plan.metrics.subQuestsTotal} sub-quests (${pct}%)`);
7145
- }
7146
- if (!plan.handoff) {
7147
- console.log("\n No handoff found — this plan has no saved session context.");
7148
- console.log(" The AI can still read the plan via tavern_get_quest_plan.\n");
7149
- return;
7150
- }
7151
- const { handoff } = plan;
7152
- console.log(`\nSession Handoff (${new Date(handoff.updatedAt).toLocaleString()}):`);
7153
- console.log(`\n Summary: ${handoff.summary}`);
7154
- if (handoff.nextSteps.length > 0) {
7155
- console.log("\n Next Steps:");
7156
- for (const step of handoff.nextSteps) console.log(` \u2022 ${step}`);
7157
- }
7158
- if (handoff.pendingDecisions.length > 0) {
7159
- console.log("\n Pending Decisions:");
7160
- for (const decision of handoff.pendingDecisions) console.log(` \u2753 ${decision}`);
7161
- }
7162
- if (handoff.blockers.length > 0) {
7163
- console.log("\n Blockers:");
7164
- for (const blocker of handoff.blockers) console.log(` \u{1F6D1} ${blocker}`);
7165
- }
7166
- console.log("");
7167
- } catch (error) {
7168
- const message = error instanceof Error ? error.message : String(error);
7169
- console.log(`\nError fetching quest plan: ${message}\n`);
7170
- }
7171
- return;
7172
- }
7173
- if (subCommand === "review") {
7174
- const planId = args[1];
7175
- if (!planId) {
7176
- console.log("\nUsage: /quest review <plan_id>");
7177
- console.log(" Fetches the quest plan and shows sub-quests with pending review gates.\n");
7178
- return;
7179
- }
7180
- try {
7181
- const plan = await this.service.getQuestPlan(planId);
7182
- const pendingGates = [];
7183
- for (const quest of plan.quests) for (const sq of quest.subQuests) if (sq.reviewGate) pendingGates.push({
7184
- questTitle: quest.title,
7185
- questId: quest.id,
7186
- subQuestTitle: sq.title,
7187
- subQuestId: sq.id,
7188
- status: sq.reviewStatus ?? "pending"
7189
- });
7190
- if (pendingGates.length === 0) {
7191
- console.log(`\nQuest Plan: ${plan.goal}`);
7192
- console.log(" No review gates configured in this plan.\n");
7193
- return;
7194
- }
7195
- console.log(`\nQuest Plan: ${plan.goal}`);
7196
- console.log(`State: ${plan.state ?? "unknown"}\n`);
7197
- console.log("Review Gates:");
7198
- for (const gate of pendingGates) {
7199
- const icon = gate.status === "approved" ? "✅" : gate.status === "rejected" ? "❌" : "⏸️";
7200
- console.log(` ${icon} [${gate.status}] ${gate.questTitle} > ${gate.subQuestTitle}`);
7201
- console.log(` quest_id: ${gate.questId} sub_quest_id: ${gate.subQuestId}`);
7202
- }
7203
- console.log("\n To approve: ask the AI to approve a review gate, or use tavern_update_review_gate tool.\n");
7204
- } catch (error) {
7205
- const message = error instanceof Error ? error.message : String(error);
7206
- console.log(`\nError fetching quest plan: ${message}\n`);
7207
- }
7208
- return;
7209
- }
7210
- console.log("\nUsage:");
7211
- console.log(" /quest review <plan_id> — Show review gates and their status");
7212
- console.log(" /quest resume <plan_id> — Load handoff and resume from where you left off");
7213
- console.log("");
7214
- }
7215
7227
  }];
7216
7228
  }
7217
7229
  registerWsHandlers(wsManager) {
@@ -8168,7 +8180,7 @@ var BridgePresence = class {
8168
8180
  const gen = this.generation;
8169
8181
  const startOpts = this.startOpts;
8170
8182
  if (!await this.gateEgress(gen, "announce")) return false;
8171
- const instanceId = v4();
8183
+ const instanceId = crypto.randomUUID();
8172
8184
  const workspaceName = this.pendingWorkspaceName;
8173
8185
  const capabilities = this.pendingCapabilities;
8174
8186
  const source = this.pendingSource;
@@ -9078,18 +9090,6 @@ function settlePendingPrompts() {
9078
9090
  }
9079
9091
  //#endregion
9080
9092
  //#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
9093
  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
9094
  /** The feedback text the model sees for `steers`, or null when there are none. */
9095
9095
  function formatSteerFeedback(steers) {
@@ -9111,7 +9111,7 @@ function deliverSteers(signal) {
9111
9111
  if (!feedback) return null;
9112
9112
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
9113
9113
  const steerMessages = steers.map((text) => ({
9114
- id: v4(),
9114
+ id: crypto.randomUUID(),
9115
9115
  role: "user",
9116
9116
  content: text,
9117
9117
  timestamp,
@@ -9282,14 +9282,14 @@ async function runHeldTurn(message, ctx, peer) {
9282
9282
  messages: [
9283
9283
  ...activeSession.messages,
9284
9284
  {
9285
- id: v4(),
9285
+ id: crypto.randomUUID(),
9286
9286
  role: "user",
9287
9287
  content: message,
9288
9288
  timestamp,
9289
9289
  metadata: { peer }
9290
9290
  },
9291
9291
  {
9292
- id: v4(),
9292
+ id: crypto.randomUUID(),
9293
9293
  role: "assistant",
9294
9294
  content: error,
9295
9295
  timestamp,
@@ -9363,14 +9363,14 @@ async function runHeldTurn(message, ctx, peer) {
9363
9363
  userMessageContent = message;
9364
9364
  }
9365
9365
  const userMessage = {
9366
- id: v4(),
9366
+ id: crypto.randomUUID(),
9367
9367
  role: "user",
9368
9368
  content: userMessageContent,
9369
9369
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9370
9370
  ...peer ? { metadata: { peer } } : {}
9371
9371
  };
9372
9372
  const pendingAssistantMessage = {
9373
- id: v4(),
9373
+ id: crypto.randomUUID(),
9374
9374
  role: "assistant",
9375
9375
  content: "...",
9376
9376
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -9518,7 +9518,7 @@ async function runHeldTurn(message, ctx, peer) {
9518
9518
  const currentSession = useCliStore.getState().session;
9519
9519
  if (currentSession && !replaced()) {
9520
9520
  const cancelMessage = {
9521
- id: v4(),
9521
+ id: crypto.randomUUID(),
9522
9522
  role: "assistant",
9523
9523
  content: "⚠️ Operation cancelled by user",
9524
9524
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -9543,7 +9543,7 @@ async function runHeldTurn(message, ctx, peer) {
9543
9543
  const currentSession = useCliStore.getState().session;
9544
9544
  if (currentSession) {
9545
9545
  const failedMessage = {
9546
- id: pendingAssistantId ?? v4(),
9546
+ id: pendingAssistantId ?? crypto.randomUUID(),
9547
9547
  role: "assistant",
9548
9548
  content: `Peer turn failed: ${rawMessage}`,
9549
9549
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11437,7 +11437,7 @@ async function createFreshSession(ctx) {
11437
11437
  const model = currentSession?.model || ctx.defaultModel || ChatModels.CLAUDE_5_5_SONNET;
11438
11438
  const clearPinnedId = process.env.B4M_SESSION_ID || process.env.B4M_RESUME_ID;
11439
11439
  const newSession = {
11440
- id: clearPinnedId ? currentSession?.id ?? clearPinnedId : v4(),
11440
+ id: clearPinnedId ? currentSession?.id ?? clearPinnedId : crypto.randomUUID(),
11441
11441
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
11442
11442
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
11443
11443
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12058,7 +12058,7 @@ function CliApp() {
12058
12058
  }
12059
12059
  newSession = resumed;
12060
12060
  } else newSession = {
12061
- id: pinnedSessionId || v4(),
12061
+ id: pinnedSessionId || crypto.randomUUID(),
12062
12062
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
12063
12063
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
12064
12064
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12257,7 +12257,7 @@ function CliApp() {
12257
12257
  const workItemTools = config.preferences.enableWorkItemTools && !apiClient.signedOut ? createWorkItemTools(new WorkItemsClient(apiClient)) : [];
12258
12258
  const peerTools = wrapTools(createPeerTools(() => peerServiceRef.current, async (target, text) => {
12259
12259
  return (await reviewGateFn({
12260
- id: v4(),
12260
+ id: crypto.randomUUID(),
12261
12261
  description: `Send this peer message to ${JSON.stringify(target)}? It may start model usage in the recipient.\n${JSON.stringify(text)}`
12262
12262
  })).decision === "approved";
12263
12263
  }), cliWrapDeps);
@@ -12522,13 +12522,13 @@ function CliApp() {
12522
12522
  messageContent = multimodalMessage.content;
12523
12523
  }
12524
12524
  const userMessage = {
12525
- id: v4(),
12525
+ id: crypto.randomUUID(),
12526
12526
  role: "user",
12527
12527
  content: userMessageContent,
12528
12528
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
12529
12529
  };
12530
12530
  const pendingAssistantMessage = {
12531
- id: v4(),
12531
+ id: crypto.randomUUID(),
12532
12532
  role: "assistant",
12533
12533
  content: "...",
12534
12534
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12840,7 +12840,7 @@ function CliApp() {
12840
12840
  ...prev,
12841
12841
  abortController
12842
12842
  }));
12843
- const pendingId = v4();
12843
+ const pendingId = crypto.randomUUID();
12844
12844
  try {
12845
12845
  const pendingAssistantMessage = {
12846
12846
  id: pendingId,
@@ -12869,7 +12869,7 @@ function CliApp() {
12869
12869
  if (!currentSession || !stillThisSession()) return;
12870
12870
  const richContent = reconstructTurnBlocks(result.steps, result.finalAnswer);
12871
12871
  const continuationMessage = {
12872
- id: v4(),
12872
+ id: crypto.randomUUID(),
12873
12873
  role: "assistant",
12874
12874
  content: "---\n\n**Background Agent Results:**\n\n" + result.finalAnswer,
12875
12875
  ...richContent ? { richContent } : {},
@@ -12936,13 +12936,13 @@ function CliApp() {
12936
12936
  const session = useCliStore.getState().session;
12937
12937
  if (!session || session.id !== sessionId) return;
12938
12938
  const userMessage = {
12939
- id: v4(),
12939
+ id: crypto.randomUUID(),
12940
12940
  role: "user",
12941
12941
  content: `$ ${command}`,
12942
12942
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
12943
12943
  };
12944
12944
  const assistantMessage = {
12945
- id: v4(),
12945
+ id: crypto.randomUUID(),
12946
12946
  role: "assistant",
12947
12947
  content: isError ? `\u274c Error:\n${output}` : output.trim() || "(no output)",
12948
12948
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -13166,7 +13166,7 @@ function CliApp() {
13166
13166
  if (!state.agent) return;
13167
13167
  if (session.messages.length < 4) return;
13168
13168
  if (session.metadata.workflow?.handoff) return;
13169
- const promptId = v4();
13169
+ const promptId = crypto.randomUUID();
13170
13170
  let timer;
13171
13171
  if (!await new Promise((resolve) => {
13172
13172
  let settled = false;