@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
@@ -1,17 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { C as NotAuthenticatedError, D as sanitizeTerminalText, d as sandboxedCommandArg, l as commandTextOf, p as writePathOf, s as loadContextFiles, u as isReadOnlyTool, w as SessionRevokedError } from "./ConfigStore-CO6kREaL.mjs";
3
- import { a as extractErrorMessage, d as BaseStorage, f as isPrivateIP, l as OllamaBackend, n as B4mStreamEndedError, o as getSettingsMap, p as Logger, r as createClient, s as getSettingsValue, t as B4mApiError, u as OpenAICompatibleBackend } from "./dist-BOxr8LQA.mjs";
4
- import { At as isPlaceholderImageSigningSecret, B as LOW_CONFIDENCE_COMPLETION_MODES, Ct as getMcpProviderMetadata, G as NotFoundError, Ht as reasoningChannelOf, I as ExpectedToolError, Jt as signImageUrl, Kt as secureParameters, M as DecisionTextPartSchema, Mt as isRetryableError, N as DecisionsRequestSchema, Rt as obfuscateApiKey, T as ChatModels, Tt as googleMapsSearchUrl, U as McpServerName, V as MODEL_DECLINED_MESSAGE, Y as PermissionDeniedError, Yt as splitEquals, a as htmlFirstH1, an as withholdsReasoning, at as SEARCH_RESULT_CARDS_LANGUAGE, bt as fromCliTodos, ft as WORK_ITEM_STATUSES, gt as createReasoningWithholder, h as ApiKeyType, i as htmlErrorTitle, in as withRetry, jt as isProviderRefusalStopReason, kt as isExpectedToolError, lt as UnprocessableEntityError, n as SESSION_ID_PATTERN, o as escapeArtifactBodyJson, pn as frontmatterHasSourceStamp, pt as assertAuthOriginMatchesApiKey, r as isValidSessionId, t as logger, w as CUSTOM_MCP_DATA_NOTICE, x as CONFIDENCE_GATE_MODES, z as LOCATION_MAP_LANGUAGE } from "./Logger-CHKCF5hd.mjs";
5
- import { n as COMMANDS, r as isReservedCommandName } from "./RemoteSkillSource-D_F99yBR.mjs";
2
+ import { C as NotAuthenticatedError, D as sanitizeTerminalText, d as sandboxedCommandArg, l as commandTextOf, p as writePathOf, s as loadContextFiles, u as isReadOnlyTool, w as SessionRevokedError } from "./ConfigStore-B2Dy-PT9.mjs";
3
+ import { a as extractErrorMessage, d as BaseStorage, f as isPrivateIP, l as OllamaBackend, n as B4mStreamEndedError, o as getSettingsMap, p as Logger, r as createClient, s as getSettingsValue, t as B4mApiError, u as OpenAICompatibleBackend } from "./dist-DHgMhdzV.mjs";
4
+ import { At as isExpectedToolError, B as LOW_CONFIDENCE_COMPLETION_MODES, Et as googleMapsSearchUrl, G as NotFoundError, I as ExpectedToolError, Jt as signImageUrl, Kt as secureParameters, M as DecisionTextPartSchema, Mt as isProviderRefusalStopReason, N as DecisionsRequestSchema, Nt as isRetryableError, T as ChatModels, U as McpServerName, Ut as reasoningChannelOf, V as MODEL_DECLINED_MESSAGE, Y as PermissionDeniedError, Yt as splitEquals, _t as createReasoningWithholder, a as htmlFirstH1, an as withholdsReasoning, at as SEARCH_RESULT_CARDS_LANGUAGE, ft as WORK_ITEM_STATUSES, h as ApiKeyType, i as htmlErrorTitle, in as withRetry, jt as isPlaceholderImageSigningSecret, lt as UnprocessableEntityError, n as SESSION_ID_PATTERN, o as escapeArtifactBodyJson, pn as frontmatterHasSourceStamp, pt as assertAuthOriginMatchesApiKey, r as isValidSessionId, t as logger, w as CUSTOM_MCP_DATA_NOTICE, wt as getMcpProviderMetadata, x as CONFIDENCE_GATE_MODES, xt as fromCliTodos, z as LOCATION_MAP_LANGUAGE, zt as obfuscateApiKey } from "./Logger-7MmrU5w6.mjs";
5
+ import { r as isReservedCommandName } from "./RemoteSkillSource-D_F99yBR.mjs";
6
6
  import { n as isPathAllowed, t as assertPathAllowed } from "./pathValidation-BRqf4HFX-CHwtwp3O.mjs";
7
7
  import { n as isTerminalShellStatus, t as getShellSessionManager } from "./ShellSessionManager-6o8KZzl1-vrbPAUTq.mjs";
8
8
  import { d as detectRuntimes, m as modelBlobsOf } from "./dist-K7a9yOUb.mjs";
9
- import { A as serverRuntimeId, B as parseGenerationInput, Ct as withDefaultOllamaPort, F as GENERATION_FIELDS, H as parseModelContextSetting, I as LOCAL_OLLAMA_RUNTIME_ID, L as REASONING_EFFORT_SETTINGS, R as effortSent, S as desktopUserDataFile, V as parseLocalModelId, X as clean, a as needsCredential, f as serverFetch, i as loginHint, l as resolveServerTarget, m as unusableStatus, r as loadModelServers, y as SSH_PROBE_TIMEOUT_MS, z as localModelId } from "./modelServers-CVufZd1f.mjs";
9
+ import { A as serverRuntimeId, B as parseGenerationInput, Ct as withDefaultOllamaPort, F as GENERATION_FIELDS, H as parseModelContextSetting, I as LOCAL_OLLAMA_RUNTIME_ID, L as REASONING_EFFORT_SETTINGS, R as effortSent, S as desktopUserDataFile, V as parseLocalModelId, X as clean, a as needsCredential, f as serverFetch, i as loginHint, l as resolveServerTarget, m as unusableStatus, r as loadModelServers, y as SSH_PROBE_TIMEOUT_MS, z as localModelId } from "./modelServers-JsKBm7Wn.mjs";
10
10
  import { createHash, randomBytes } from "crypto";
11
11
  import { existsSync, lstatSync, promises, readdirSync, realpathSync, rmSync, statSync } from "fs";
12
12
  import os, { homedir } from "os";
13
13
  import path, { dirname, join } from "path";
14
- import { v4 } from "uuid";
15
14
  import path$1, * as path$2 from "node:path";
16
15
  import { promises as promises$1 } from "node:fs";
17
16
  import { AsyncFzf } from "fzf";
@@ -19,7 +18,6 @@ import ignore from "ignore";
19
18
  import fs, { mkdir, readFile, stat, writeFile } from "fs/promises";
20
19
  import { z as z$1 } from "zod";
21
20
  import { isAxiosError } from "axios";
22
- import Fuse from "fuse.js";
23
21
  import { execFile, spawn } from "child_process";
24
22
  import { promisify } from "util";
25
23
  import * as fsp from "node:fs/promises";
@@ -29,7 +27,6 @@ import * as turndownPluginGfm from "@joplin/turndown-plugin-gfm";
29
27
  import * as cheerio from "cheerio";
30
28
  import FirecrawlDefault, { FirecrawlError } from "@mendable/firecrawl-js";
31
29
  import { lookup } from "node:dns/promises";
32
- import "@aws-sdk/client-cloudwatch";
33
30
  import random from "lodash/random.js";
34
31
  import sum from "lodash/sum.js";
35
32
  import times from "lodash/times.js";
@@ -416,33 +413,6 @@ function isBinaryFile(filePath) {
416
413
  */
417
414
  const MAX_FILE_SIZE$3 = 10485760;
418
415
  //#endregion
419
- //#region src/utils/fuzzySearch.ts
420
- /**
421
- * Fuzzy search options for command matching
422
- */
423
- const fuseOptions = {
424
- keys: [{
425
- name: "name",
426
- weight: .7
427
- }, {
428
- name: "description",
429
- weight: .3
430
- }],
431
- threshold: .4,
432
- includeScore: true,
433
- minMatchCharLength: 1
434
- };
435
- /**
436
- * Search commands using fuzzy matching
437
- * @param query - The search query (without the leading /)
438
- * @param commands - Optional custom commands array (defaults to built-in COMMANDS)
439
- * @returns Array of matching commands, sorted by relevance
440
- */
441
- function searchCommands(query, commands = COMMANDS) {
442
- if (!query || query.trim() === "") return commands;
443
- return new Fuse(commands, fuseOptions).search(query).map((result) => result.item);
444
- }
445
- //#endregion
446
416
  //#region src/storage/SessionStore.ts
447
417
  /**
448
418
  * Manages conversation sessions stored as JSON files
@@ -478,7 +448,7 @@ var SessionStore = class {
478
448
  if (session.messages.length === 0) throw new Error("Cannot save session with no messages");
479
449
  await this.init();
480
450
  const filePath = this.sessionFilePath(session.id);
481
- const tempPath = `${filePath}.${v4()}.tmp`;
451
+ const tempPath = `${filePath}.${crypto.randomUUID()}.tmp`;
482
452
  try {
483
453
  await promises.writeFile(tempPath, JSON.stringify(session, null, 2), "utf-8");
484
454
  await promises.rename(tempPath, filePath);
@@ -500,7 +470,7 @@ var SessionStore = class {
500
470
  session.messages = session.messages.map((msg) => {
501
471
  if (!msg.id) return {
502
472
  ...msg,
503
- id: v4()
473
+ id: crypto.randomUUID()
504
474
  };
505
475
  return msg;
506
476
  });
@@ -532,7 +502,7 @@ var SessionStore = class {
532
502
  session.messages = session.messages.map((msg) => {
533
503
  if (!msg.id) return {
534
504
  ...msg,
535
- id: v4()
505
+ id: crypto.randomUUID()
536
506
  };
537
507
  return msg;
538
508
  });
@@ -2341,178 +2311,6 @@ const webFetchTool = {
2341
2311
  })
2342
2312
  };
2343
2313
  //#endregion
2344
- //#region ../../b4m-core/utils/dist/globMatches.mjs
2345
- /**
2346
- * Backtrack-free glob match where `*` is the only wildcard and every other character is a
2347
- * literal. Deliberately not a compiled RegExp: escaping the pattern still leaves `*` live as
2348
- * `.*`, and a chained-`*` pattern (`'*a'.repeat(12) + 'Z'`) then costs the regex engine
2349
- * exponential time - measured at over 120s of blocked event loop against a 40-char subject.
2350
- * This two-pointer walk is O(text * pattern) worst case with no backtracking stack, so a
2351
- * hostile pattern cannot outrun its input.
2352
- *
2353
- * Use this anywhere a user-supplied glob is matched against a name on a request path:
2354
- * lattice rule entity references, agent allowed/denied tool patterns. Reaching for
2355
- * `escapeRegex` instead does NOT close the hole - the whole point of these patterns is that
2356
- * `*` survives escaping.
2357
- *
2358
- * Import from the lightweight subpath (`@bike4mind/utils/globMatches`), NOT the package
2359
- * barrel, which eagerly evaluates `Logger`/embedding-model code.
2360
- *
2361
- * @example
2362
- * globMatches('mcp__github__create_issue', 'mcp__*__create_*') // true
2363
- * globMatches('a.b', 'a.b') // true - `.` is a literal here, not "any char"
2364
- * globMatches('axb', 'a.b') // false - same reason
2365
- */
2366
- function globMatches(text, pattern) {
2367
- let textIndex = 0;
2368
- let patternIndex = 0;
2369
- let lastStarPattern = -1;
2370
- let lastStarText = 0;
2371
- while (textIndex < text.length) if (patternIndex < pattern.length && pattern[patternIndex] === "*") {
2372
- lastStarPattern = patternIndex++;
2373
- lastStarText = textIndex;
2374
- } else if (patternIndex < pattern.length && pattern[patternIndex] === text[textIndex]) {
2375
- patternIndex++;
2376
- textIndex++;
2377
- } else if (lastStarPattern >= 0) {
2378
- patternIndex = lastStarPattern + 1;
2379
- textIndex = ++lastStarText;
2380
- } else return false;
2381
- while (patternIndex < pattern.length && pattern[patternIndex] === "*") patternIndex++;
2382
- return patternIndex === pattern.length;
2383
- }
2384
- //#endregion
2385
- //#region ../../b4m-core/utils/dist/normalizeId.mjs
2386
- /**
2387
- * Coerce an id-ish value to its primitive string form, or `undefined` when absent.
2388
- *
2389
- * Handles the three shapes a Mongo id arrives in across request layers: a plain string,
2390
- * a Mongo `ObjectId` (via `toHexString`), and a populated Mongoose document (`{ _id }` /
2391
- * `{ id }`). Plain `String()` is NOT enough - it turns a populated document into
2392
- * "[object Object]", which is exactly the silent-comparison trap that lets a value match a
2393
- * casting Mongo query yet fail an in-memory strict `===`/`!==`. Normalize both sides of any
2394
- * such comparison through this so the two never disagree.
2395
- */
2396
- function normalizeId(value) {
2397
- if (value == null) return void 0;
2398
- if (typeof value === "string") return value || void 0;
2399
- if (typeof value === "object") {
2400
- const obj = value;
2401
- if (typeof obj.toHexString === "function") return obj.toHexString() || void 0;
2402
- if (obj._id != null) return normalizeId(obj._id);
2403
- if (typeof obj.id === "string") return obj.id || void 0;
2404
- return;
2405
- }
2406
- return typeof value === "number" && Number.isFinite(value) ? String(value) : void 0;
2407
- }
2408
- //#endregion
2409
- //#region ../../b4m-core/services/dist/weather-DkuXq1cq.mjs
2410
- /**
2411
- * A user paying for themselves with no credit purchase and no active plan (own or an org seat):
2412
- * the paid signals the API key trust gate reads (userApiKeyService/trust.ts), plan read lazily as
2413
- * there. Org-paid spend is never free tier, since no org-level signal says whether the pool is funded.
2414
- */
2415
- async function isFreeTierHolder(holder) {
2416
- if (holder.organization || holder.user.lastCreditsPurchasedAt) return false;
2417
- return !await holder.activePlans.hasActivePlan(holder.user.id);
2418
- }
2419
- /**
2420
- * One request's or turn's view of `isOperationalBillingEnabled`: the settings and plan reads run
2421
- * at most once per holder, so repeated spend in the same unit of work does not repeat them. A
2422
- * rejected read is not kept. Never share one across requests: it would pin a stale answer.
2423
- */
2424
- function memoizeOperationalBillingCheck(db, logger) {
2425
- const memo = /* @__PURE__ */ new Map();
2426
- return (holder) => {
2427
- const key = holder ? `${holder.user.id}:${holder.organization?.id ?? ""}` : "";
2428
- let pending = memo.get(key);
2429
- if (!pending) {
2430
- pending = isOperationalBillingEnabled(db, logger, holder);
2431
- memo.set(key, pending);
2432
- pending.catch(() => memo.delete(key));
2433
- }
2434
- return pending;
2435
- };
2436
- }
2437
- /**
2438
- * Whether operational usage (auto-naming, summarization, tagging, embeddings for search and file
2439
- * indexing) actually debits credits. Requires `enforceCredits`, the platform-wide metering master
2440
- * switch (off on self-host). On top of it, `billOperationalUsage` opts every holder in; with it
2441
- * off, only a free-tier `holder` is billed. Without a `holder` the free-tier carve-out cannot
2442
- * apply, so the answer is the toggle alone.
2443
- *
2444
- * Shared by `recordOperationalUsage` (the settlement) and every credit pre-flight that guards a
2445
- * path settling through it, so the two provably agree on when a debit can happen. They MUST stay
2446
- * in sync, including passing the same holder: a pre-flight stricter than the settlement rejects
2447
- * work that would never have been billed, and a looser one leaves the gap the pre-flight exists
2448
- * to close.
2449
- *
2450
- * Owns the fetch rather than taking a settings map, so no caller can narrow it to the
2451
- * wrong keys: under `skipCache` a `names` list that omits a key reads `undefined` for
2452
- * it and silently gates billing OFF - turning a pre-flight into a no-op with no error
2453
- * anywhere. `skipCache` is required for the same reason: a long-lived host's process
2454
- * cache can lag another process's admin write until its TTL expires.
2455
- *
2456
- * Throws if the settings store or the plan read does: a caller that must not fail on a
2457
- * billing-store blip has to catch this and decide its own fallback.
2458
- */
2459
- async function isOperationalBillingEnabled(db, logger, holder) {
2460
- const settings = await getSettingsMap(db, {
2461
- logger,
2462
- names: ["billOperationalUsage", "enforceCredits"],
2463
- skipCache: true
2464
- });
2465
- if (!(getSettingsValue("enforceCredits", settings) ?? false)) return false;
2466
- if (getSettingsValue("billOperationalUsage", settings) ?? false) return true;
2467
- return holder ? isFreeTierHolder(holder) : false;
2468
- }
2469
- async function fetchWeatherData(db, params) {
2470
- const openWeatherKey = await (0, apiKeyService_exports.getOpenWeatherKey)({ db });
2471
- if (!openWeatherKey) throw new Error("OpenWeather API key is not configured.");
2472
- let response;
2473
- try {
2474
- response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${params.lat}&lon=${params.lon}&appid=${openWeatherKey}&units=${params.units || "imperial"}`);
2475
- } catch (err) {
2476
- throw new Error(`OpenWeather fetch failed: ${err instanceof Error ? err.message : String(err)}`);
2477
- }
2478
- if (!response.ok) throw new Error(`OpenWeather error: ${response.statusText}`);
2479
- const data = await response.json();
2480
- return `Right now it's ${data?.main?.temp}° in ${data?.name}, with ${data?.weather?.[0]?.description}.`;
2481
- }
2482
- const weatherTool = {
2483
- name: "weather_info",
2484
- implementation: (context) => ({
2485
- toolFn: async (value) => {
2486
- const params = value;
2487
- await context.onStart?.("weather_info", params);
2488
- return fetchWeatherData(context.db, params);
2489
- },
2490
- toolSchema: {
2491
- name: "weather_info",
2492
- description: "Get current weather info from the OpenWeather API using latitude and longitude",
2493
- parameters: {
2494
- type: "object",
2495
- properties: {
2496
- lat: {
2497
- type: "number",
2498
- description: "Latitude of the location"
2499
- },
2500
- lon: {
2501
- type: "number",
2502
- description: "Longitude of the location"
2503
- },
2504
- units: {
2505
- type: "string",
2506
- description: "Units: either \"imperial\" or \"metric\"",
2507
- enum: ["imperial", "metric"]
2508
- }
2509
- },
2510
- required: ["lat", "lon"]
2511
- }
2512
- }
2513
- })
2514
- };
2515
- //#endregion
2516
2314
  //#region ../../b4m-core/services/dist/prompts-CD7UjAcG.mjs
2517
2315
  /**
2518
2316
  * Teaches the `b4m_cards` fence, appended to a web_search result ONLY when that search actually
@@ -3624,6 +3422,119 @@ const webSearchTool = {
3624
3422
  }
3625
3423
  };
3626
3424
  //#endregion
3425
+ //#region ../../b4m-core/services/dist/weather-jxxOpyX5.mjs
3426
+ async function fetchWeatherData(db, params) {
3427
+ const openWeatherKey = await (0, apiKeyService_exports.getOpenWeatherKey)({ db });
3428
+ if (!openWeatherKey) throw new Error("OpenWeather API key is not configured.");
3429
+ let response;
3430
+ try {
3431
+ response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${params.lat}&lon=${params.lon}&appid=${openWeatherKey}&units=${params.units || "imperial"}`);
3432
+ } catch (err) {
3433
+ throw new Error(`OpenWeather fetch failed: ${err instanceof Error ? err.message : String(err)}`);
3434
+ }
3435
+ if (!response.ok) throw new Error(`OpenWeather error: ${response.statusText}`);
3436
+ const data = await response.json();
3437
+ return `Right now it's ${data?.main?.temp}° in ${data?.name}, with ${data?.weather?.[0]?.description}.`;
3438
+ }
3439
+ const weatherTool = {
3440
+ name: "weather_info",
3441
+ implementation: (context) => ({
3442
+ toolFn: async (value) => {
3443
+ const params = value;
3444
+ await context.onStart?.("weather_info", params);
3445
+ return fetchWeatherData(context.db, params);
3446
+ },
3447
+ toolSchema: {
3448
+ name: "weather_info",
3449
+ description: "Get current weather info from the OpenWeather API using latitude and longitude",
3450
+ parameters: {
3451
+ type: "object",
3452
+ properties: {
3453
+ lat: {
3454
+ type: "number",
3455
+ description: "Latitude of the location"
3456
+ },
3457
+ lon: {
3458
+ type: "number",
3459
+ description: "Longitude of the location"
3460
+ },
3461
+ units: {
3462
+ type: "string",
3463
+ description: "Units: either \"imperial\" or \"metric\"",
3464
+ enum: ["imperial", "metric"]
3465
+ }
3466
+ },
3467
+ required: ["lat", "lon"]
3468
+ }
3469
+ }
3470
+ })
3471
+ };
3472
+ //#endregion
3473
+ //#region ../../b4m-core/utils/dist/globMatches.mjs
3474
+ /**
3475
+ * Backtrack-free glob match where `*` is the only wildcard and every other character is a
3476
+ * literal. Deliberately not a compiled RegExp: escaping the pattern still leaves `*` live as
3477
+ * `.*`, and a chained-`*` pattern (`'*a'.repeat(12) + 'Z'`) then costs the regex engine
3478
+ * exponential time - measured at over 120s of blocked event loop against a 40-char subject.
3479
+ * This two-pointer walk is O(text * pattern) worst case with no backtracking stack, so a
3480
+ * hostile pattern cannot outrun its input.
3481
+ *
3482
+ * Use this anywhere a user-supplied glob is matched against a name on a request path:
3483
+ * lattice rule entity references, agent allowed/denied tool patterns. Reaching for
3484
+ * `escapeRegex` instead does NOT close the hole - the whole point of these patterns is that
3485
+ * `*` survives escaping.
3486
+ *
3487
+ * Import from the lightweight subpath (`@bike4mind/utils/globMatches`), NOT the package
3488
+ * barrel, which eagerly evaluates `Logger`/embedding-model code.
3489
+ *
3490
+ * @example
3491
+ * globMatches('mcp__github__create_issue', 'mcp__*__create_*') // true
3492
+ * globMatches('a.b', 'a.b') // true - `.` is a literal here, not "any char"
3493
+ * globMatches('axb', 'a.b') // false - same reason
3494
+ */
3495
+ function globMatches(text, pattern) {
3496
+ let textIndex = 0;
3497
+ let patternIndex = 0;
3498
+ let lastStarPattern = -1;
3499
+ let lastStarText = 0;
3500
+ while (textIndex < text.length) if (patternIndex < pattern.length && pattern[patternIndex] === "*") {
3501
+ lastStarPattern = patternIndex++;
3502
+ lastStarText = textIndex;
3503
+ } else if (patternIndex < pattern.length && pattern[patternIndex] === text[textIndex]) {
3504
+ patternIndex++;
3505
+ textIndex++;
3506
+ } else if (lastStarPattern >= 0) {
3507
+ patternIndex = lastStarPattern + 1;
3508
+ textIndex = ++lastStarText;
3509
+ } else return false;
3510
+ while (patternIndex < pattern.length && pattern[patternIndex] === "*") patternIndex++;
3511
+ return patternIndex === pattern.length;
3512
+ }
3513
+ //#endregion
3514
+ //#region ../../b4m-core/utils/dist/normalizeId.mjs
3515
+ /**
3516
+ * Coerce an id-ish value to its primitive string form, or `undefined` when absent.
3517
+ *
3518
+ * Handles the three shapes a Mongo id arrives in across request layers: a plain string,
3519
+ * a Mongo `ObjectId` (via `toHexString`), and a populated Mongoose document (`{ _id }` /
3520
+ * `{ id }`). Plain `String()` is NOT enough - it turns a populated document into
3521
+ * "[object Object]", which is exactly the silent-comparison trap that lets a value match a
3522
+ * casting Mongo query yet fail an in-memory strict `===`/`!==`. Normalize both sides of any
3523
+ * such comparison through this so the two never disagree.
3524
+ */
3525
+ function normalizeId(value) {
3526
+ if (value == null) return void 0;
3527
+ if (typeof value === "string") return value || void 0;
3528
+ if (typeof value === "object") {
3529
+ const obj = value;
3530
+ if (typeof obj.toHexString === "function") return obj.toHexString() || void 0;
3531
+ if (obj._id != null) return normalizeId(obj._id);
3532
+ if (typeof obj.id === "string") return obj.id || void 0;
3533
+ return;
3534
+ }
3535
+ return typeof value === "number" && Number.isFinite(value) ? String(value) : void 0;
3536
+ }
3537
+ //#endregion
3627
3538
  //#region ../../b4m-core/services/dist/latticeModelService-DTKpo_hV.mjs
3628
3539
  /**
3629
3540
  * The model's creator, compared through `normalizeId` on both sides.
@@ -3723,7 +3634,68 @@ async function getModelForWrite(user, modelId, deps) {
3723
3634
  return isModelOwner(model, user) ? model : null;
3724
3635
  }
3725
3636
  //#endregion
3726
- //#region ../../b4m-core/services/dist/toolGenerators-ByeEdDON.mjs
3637
+ //#region ../../b4m-core/services/dist/isOperationalBillingEnabled-CAzm2mhR.mjs
3638
+ /**
3639
+ * A user paying for themselves with no credit purchase and no active plan (own or an org seat):
3640
+ * the paid signals the API key trust gate reads (userApiKeyService/trust.ts), plan read lazily as
3641
+ * there. Org-paid spend is never free tier, since no org-level signal says whether the pool is funded.
3642
+ */
3643
+ async function isFreeTierHolder(holder) {
3644
+ if (holder.organization || holder.user.lastCreditsPurchasedAt) return false;
3645
+ return !await holder.activePlans.hasActivePlan(holder.user.id);
3646
+ }
3647
+ /**
3648
+ * One request's or turn's view of `isOperationalBillingEnabled`: the settings and plan reads run
3649
+ * at most once per holder, so repeated spend in the same unit of work does not repeat them. A
3650
+ * rejected read is not kept. Never share one across requests: it would pin a stale answer.
3651
+ */
3652
+ function memoizeOperationalBillingCheck(db, logger) {
3653
+ const memo = /* @__PURE__ */ new Map();
3654
+ return (holder) => {
3655
+ const key = holder ? `${holder.user.id}:${holder.organization?.id ?? ""}` : "";
3656
+ let pending = memo.get(key);
3657
+ if (!pending) {
3658
+ pending = isOperationalBillingEnabled(db, logger, holder);
3659
+ memo.set(key, pending);
3660
+ pending.catch(() => memo.delete(key));
3661
+ }
3662
+ return pending;
3663
+ };
3664
+ }
3665
+ /**
3666
+ * Whether operational usage (auto-naming, summarization, tagging, embeddings for search and file
3667
+ * indexing) actually debits credits. Requires `enforceCredits`, the platform-wide metering master
3668
+ * switch (off on self-host). On top of it, `billOperationalUsage` opts every holder in; with it
3669
+ * off, only a free-tier `holder` is billed. Without a `holder` the free-tier carve-out cannot
3670
+ * apply, so the answer is the toggle alone.
3671
+ *
3672
+ * Shared by `recordOperationalUsage` (the settlement) and every credit pre-flight that guards a
3673
+ * path settling through it, so the two provably agree on when a debit can happen. They MUST stay
3674
+ * in sync, including passing the same holder: a pre-flight stricter than the settlement rejects
3675
+ * work that would never have been billed, and a looser one leaves the gap the pre-flight exists
3676
+ * to close.
3677
+ *
3678
+ * Owns the fetch rather than taking a settings map, so no caller can narrow it to the
3679
+ * wrong keys: under `skipCache` a `names` list that omits a key reads `undefined` for
3680
+ * it and silently gates billing OFF - turning a pre-flight into a no-op with no error
3681
+ * anywhere. `skipCache` is required for the same reason: a long-lived host's process
3682
+ * cache can lag another process's admin write until its TTL expires.
3683
+ *
3684
+ * Throws if the settings store or the plan read does: a caller that must not fail on a
3685
+ * billing-store blip has to catch this and decide its own fallback.
3686
+ */
3687
+ async function isOperationalBillingEnabled(db, logger, holder) {
3688
+ const settings = await getSettingsMap(db, {
3689
+ logger,
3690
+ names: ["billOperationalUsage", "enforceCredits"],
3691
+ skipCache: true
3692
+ });
3693
+ if (!(getSettingsValue("enforceCredits", settings) ?? false)) return false;
3694
+ if (getSettingsValue("billOperationalUsage", settings) ?? false) return true;
3695
+ return holder ? isFreeTierHolder(holder) : false;
3696
+ }
3697
+ //#endregion
3698
+ //#region ../../b4m-core/services/dist/toolGenerators-Bh6zx8vU.mjs
3727
3699
  const diceRoll = async (parameters) => {
3728
3700
  if (!parameters?.sides || !parameters?.times) throw new Error("Tool dice roll: Missing required parameters");
3729
3701
  return sum(times(parameters.times, () => random(1, parameters.sides))).toString();
@@ -17374,378 +17346,6 @@ function createGetFileStructureTool(allowedDirectories) {
17374
17346
  };
17375
17347
  }
17376
17348
  //#endregion
17377
- //#region src/tools/decisionLogTool.ts
17378
- /**
17379
- * Validate log_decision parameters
17380
- * @throws Error if validation fails
17381
- */
17382
- function validateParams$1(args) {
17383
- const params = args;
17384
- if (typeof params.summary !== "string" || params.summary.trim() === "") throw new Error("log_decision: summary must be a non-empty string");
17385
- if (typeof params.rationale !== "string" || params.rationale.trim() === "") throw new Error("log_decision: rationale must be a non-empty string");
17386
- if (params.alternatives !== void 0) {
17387
- if (!Array.isArray(params.alternatives)) throw new Error("log_decision: alternatives must be an array of strings");
17388
- for (const alt of params.alternatives) if (typeof alt !== "string") throw new Error("log_decision: each alternative must be a string");
17389
- }
17390
- if (params.context !== void 0 && typeof params.context !== "string") throw new Error("log_decision: context must be a string");
17391
- return {
17392
- summary: params.summary.trim(),
17393
- rationale: params.rationale.trim(),
17394
- alternatives: params.alternatives,
17395
- context: typeof params.context === "string" ? params.context.trim() : void 0
17396
- };
17397
- }
17398
- /**
17399
- * Format decisions for display output
17400
- */
17401
- function formatDecisionsOutput(decisions) {
17402
- if (decisions.length === 0) return "No decisions logged in this session.";
17403
- return decisions.map((decision, index) => {
17404
- const lines = [`${index + 1}. **${decision.summary}**`, ` Rationale: ${decision.rationale}`];
17405
- if (decision.alternatives && decision.alternatives.length > 0) lines.push(` Alternatives considered: ${decision.alternatives.join(", ")}`);
17406
- if (decision.context) lines.push(` Context: ${decision.context}`);
17407
- const timestamp = new Date(decision.timestamp).toLocaleTimeString();
17408
- lines.push(` Logged at: ${timestamp}`);
17409
- return lines.join("\n");
17410
- }).join("\n\n");
17411
- }
17412
- /**
17413
- * Create the log_decision tool.
17414
- *
17415
- * Allows the AI to record significant decisions with rationale during a session.
17416
- * Decisions are persisted in the session's workflow state for audit trail
17417
- * and cross-session continuity.
17418
- */
17419
- function createDecisionLogTool(store) {
17420
- return {
17421
- toolFn: async (args) => {
17422
- const params = validateParams$1(args);
17423
- const decision = {
17424
- id: v4(),
17425
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
17426
- summary: params.summary,
17427
- rationale: params.rationale,
17428
- alternatives: params.alternatives,
17429
- context: params.context
17430
- };
17431
- store.decisions.push(decision);
17432
- if (store.onUpdate) store.onUpdate(store.decisions);
17433
- return `Decision logged (#${store.decisions.length}): ${decision.summary}`;
17434
- },
17435
- toolSchema: {
17436
- name: "log_decision",
17437
- description: `Record a significant decision with its rationale for audit trail and session continuity.
17438
-
17439
- **When to use:**
17440
- - Architecture or design choices (e.g., "chose Zustand over Redux because...")
17441
- - Scope narrowing or direction changes in research
17442
- - Trade-off decisions between viable alternatives
17443
- - Interpretation of ambiguous requirements
17444
-
17445
- **When NOT to use:**
17446
- - Routine operations (reading files, running tests)
17447
- - Trivial choices that wouldn't matter to someone resuming this work
17448
- - Implementation details that are obvious from the code
17449
-
17450
- Log decisions that would matter if someone needed to understand WHY you did something.`,
17451
- parameters: {
17452
- type: "object",
17453
- properties: {
17454
- summary: {
17455
- type: "string",
17456
- description: "What was decided — a clear, concise statement"
17457
- },
17458
- rationale: {
17459
- type: "string",
17460
- description: "Why this decision was made — the reasoning behind it"
17461
- },
17462
- alternatives: {
17463
- type: "array",
17464
- items: { type: "string" },
17465
- description: "What alternatives were considered (optional)"
17466
- },
17467
- context: {
17468
- type: "string",
17469
- description: "What triggered this decision — the situation or constraint (optional)"
17470
- }
17471
- },
17472
- required: ["summary", "rationale"]
17473
- }
17474
- }
17475
- };
17476
- }
17477
- /**
17478
- * Create a new empty DecisionStore
17479
- */
17480
- function createDecisionStore(onUpdate) {
17481
- return {
17482
- decisions: [],
17483
- onUpdate
17484
- };
17485
- }
17486
- //#endregion
17487
- //#region src/tools/blockerTool.ts
17488
- /**
17489
- * Format blockers for display output
17490
- */
17491
- function formatBlockersOutput(blockers) {
17492
- if (blockers.length === 0) return "No blockers tracked in this session.";
17493
- const open = blockers.filter((b) => b.status === "open");
17494
- const resolved = blockers.filter((b) => b.status === "resolved");
17495
- const lines = [];
17496
- if (open.length > 0) {
17497
- lines.push(`**Open blockers (${open.length}):**`);
17498
- for (const blocker of open) lines.push(` - [${blocker.id.slice(0, 8)}] ${blocker.description}`);
17499
- }
17500
- if (resolved.length > 0) {
17501
- if (open.length > 0) lines.push("");
17502
- lines.push(`**Resolved blockers (${resolved.length}):**`);
17503
- for (const blocker of resolved) {
17504
- lines.push(` - [${blocker.id.slice(0, 8)}] ${blocker.description}`);
17505
- lines.push(` Resolution: ${blocker.resolution ?? "(no resolution recorded)"}`);
17506
- }
17507
- }
17508
- return lines.join("\n");
17509
- }
17510
- /**
17511
- * Create the track_blocker and resolve_blocker tools.
17512
- *
17513
- * Allows the AI to track what's blocking progress and record resolutions.
17514
- * Blockers are persisted in the session's workflow state for audit trail
17515
- * and cross-session continuity.
17516
- */
17517
- function createBlockerTools(store) {
17518
- return [{
17519
- toolFn: async (args) => {
17520
- const params = args;
17521
- if (typeof params.description !== "string" || params.description.trim() === "") throw new Error("track_blocker: description must be a non-empty string");
17522
- const blocker = {
17523
- id: v4(),
17524
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
17525
- description: params.description.trim(),
17526
- status: "open"
17527
- };
17528
- store.blockers.push(blocker);
17529
- if (store.onUpdate) store.onUpdate(store.blockers);
17530
- const openCount = store.blockers.filter((b) => b.status === "open").length;
17531
- return `Blocker tracked [${blocker.id.slice(0, 8)}]: ${blocker.description}\n(${openCount} open blocker${openCount === 1 ? "" : "s"})`;
17532
- },
17533
- toolSchema: {
17534
- name: "track_blocker",
17535
- description: `Track something that is blocking progress.
17536
-
17537
- **When to use:**
17538
- - Missing information or unclear requirements
17539
- - External dependencies (waiting on API access, credentials, data)
17540
- - Technical constraints discovered during work
17541
- - Ambiguous requirements that need human clarification
17542
-
17543
- **When NOT to use:**
17544
- - Normal challenges that are part of the work
17545
- - Things you can resolve immediately`,
17546
- parameters: {
17547
- type: "object",
17548
- properties: { description: {
17549
- type: "string",
17550
- description: "What is blocking progress — be specific about what is needed to unblock"
17551
- } },
17552
- required: ["description"]
17553
- }
17554
- }
17555
- }, {
17556
- toolFn: async (args) => {
17557
- const params = args;
17558
- if (typeof params.blocker_id !== "string" || params.blocker_id.trim() === "") throw new Error("resolve_blocker: blocker_id must be a non-empty string");
17559
- if (typeof params.resolution !== "string" || params.resolution.trim() === "") throw new Error("resolve_blocker: resolution must be a non-empty string");
17560
- const blockerId = params.blocker_id.trim();
17561
- const blocker = store.blockers.find((b) => b.id === blockerId || b.id.startsWith(blockerId));
17562
- if (!blocker) {
17563
- const openBlockers = store.blockers.filter((b) => b.status === "open");
17564
- if (openBlockers.length === 0) return "No open blockers to resolve.";
17565
- return `Blocker not found. Open blockers:\n${openBlockers.map((b) => ` [${b.id.slice(0, 8)}] ${b.description}`).join("\n")}`;
17566
- }
17567
- if (blocker.status === "resolved") return `Blocker [${blocker.id.slice(0, 8)}] is already resolved.`;
17568
- blocker.status = "resolved";
17569
- blocker.resolvedAt = (/* @__PURE__ */ new Date()).toISOString();
17570
- blocker.resolution = params.resolution.trim();
17571
- if (store.onUpdate) store.onUpdate(store.blockers);
17572
- const openCount = store.blockers.filter((b) => b.status === "open").length;
17573
- return `Blocker resolved [${blocker.id.slice(0, 8)}]: ${blocker.resolution}\n(${openCount} open blocker${openCount === 1 ? "" : "s"} remaining)`;
17574
- },
17575
- toolSchema: {
17576
- name: "resolve_blocker",
17577
- description: `Mark a blocker as resolved with a description of how it was resolved.
17578
-
17579
- Use the blocker ID (or its first 8 characters) from the track_blocker output.`,
17580
- parameters: {
17581
- type: "object",
17582
- properties: {
17583
- blocker_id: {
17584
- type: "string",
17585
- description: "The ID of the blocker to resolve (full ID or first 8 characters)"
17586
- },
17587
- resolution: {
17588
- type: "string",
17589
- description: "How the blocker was resolved"
17590
- }
17591
- },
17592
- required: ["blocker_id", "resolution"]
17593
- }
17594
- }
17595
- }];
17596
- }
17597
- /**
17598
- * Create a new empty BlockerStore
17599
- */
17600
- function createBlockerStore(onUpdate) {
17601
- return {
17602
- blockers: [],
17603
- onUpdate
17604
- };
17605
- }
17606
- //#endregion
17607
- //#region src/tools/reviewGateTool.ts
17608
- const MAX_DESCRIPTION_LENGTH = 2e3;
17609
- const MAX_RECOMMENDATION_LENGTH = 1e3;
17610
- const MAX_OPTION_LENGTH = 500;
17611
- const MAX_OPTIONS_COUNT = 10;
17612
- /**
17613
- * Validate request_review_gate parameters
17614
- * @throws Error if validation fails
17615
- */
17616
- function validateParams(args) {
17617
- const params = args;
17618
- if (typeof params.description !== "string" || params.description.trim() === "") throw new Error("request_review_gate: description must be a non-empty string");
17619
- if (params.description.length > MAX_DESCRIPTION_LENGTH) throw new Error(`request_review_gate: description must be ${MAX_DESCRIPTION_LENGTH} characters or fewer`);
17620
- if (params.options !== void 0) {
17621
- if (!Array.isArray(params.options)) throw new Error("request_review_gate: options must be an array of strings");
17622
- if (params.options.length > MAX_OPTIONS_COUNT) throw new Error(`request_review_gate: options must contain ${MAX_OPTIONS_COUNT} entries or fewer`);
17623
- for (const opt of params.options) {
17624
- if (typeof opt !== "string") throw new Error("request_review_gate: each option must be a string");
17625
- if (opt.length > MAX_OPTION_LENGTH) throw new Error(`request_review_gate: each option must be ${MAX_OPTION_LENGTH} characters or fewer`);
17626
- }
17627
- }
17628
- if (params.recommendation !== void 0) {
17629
- if (typeof params.recommendation !== "string") throw new Error("request_review_gate: recommendation must be a string");
17630
- if (params.recommendation.length > MAX_RECOMMENDATION_LENGTH) throw new Error(`request_review_gate: recommendation must be ${MAX_RECOMMENDATION_LENGTH} characters or fewer`);
17631
- }
17632
- const options = params.options?.map((o) => o.trim()).filter((o) => o.length > 0);
17633
- return {
17634
- description: params.description.trim(),
17635
- options: options && options.length > 0 ? options : void 0,
17636
- recommendation: typeof params.recommendation === "string" ? params.recommendation.trim() : void 0
17637
- };
17638
- }
17639
- /**
17640
- * Format review gates for display output
17641
- */
17642
- function formatReviewGatesOutput(gates) {
17643
- if (gates.length === 0) return "No review gates recorded in this session.";
17644
- return gates.map((gate, index) => {
17645
- const lines = [`${index + 1}. **${gate.description}**`, ` Status: ${gate.status}`];
17646
- if (gate.recommendation) lines.push(` Recommendation: ${gate.recommendation}`);
17647
- if (gate.options && gate.options.length > 0) {
17648
- lines.push(" Options:");
17649
- for (const opt of gate.options) lines.push(` • ${opt}`);
17650
- }
17651
- if (gate.userNote) lines.push(` Note: ${gate.userNote}`);
17652
- const requested = new Date(gate.timestamp).toLocaleTimeString();
17653
- lines.push(` Requested at: ${requested}`);
17654
- if (gate.resolvedAt) {
17655
- const resolved = new Date(gate.resolvedAt).toLocaleTimeString();
17656
- lines.push(` Resolved at: ${resolved}`);
17657
- }
17658
- return lines.join("\n");
17659
- }).join("\n\n");
17660
- }
17661
- /**
17662
- * Create the request_review_gate tool.
17663
- *
17664
- * Pauses agent execution and prompts the user for explicit approval at a
17665
- * significant decision point. The agent halts until the user responds.
17666
- *
17667
- * Decisions are persisted in the session's workflow state (`reviewGates`)
17668
- * for audit trail and cross-session continuity.
17669
- */
17670
- function createReviewGateTool(store, requestReviewFn) {
17671
- return {
17672
- toolFn: async (args) => {
17673
- const params = validateParams(args);
17674
- const id = v4();
17675
- const requestedAt = (/* @__PURE__ */ new Date()).toISOString();
17676
- const response = await requestReviewFn({
17677
- id,
17678
- description: params.description,
17679
- options: params.options,
17680
- recommendation: params.recommendation
17681
- });
17682
- const trimmedNote = response.note?.trim();
17683
- const entry = {
17684
- id,
17685
- timestamp: requestedAt,
17686
- description: params.description,
17687
- status: response.decision,
17688
- resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
17689
- userNote: trimmedNote && trimmedNote.length > 0 ? trimmedNote : void 0,
17690
- options: params.options,
17691
- recommendation: params.recommendation
17692
- };
17693
- store.reviewGates.push(entry);
17694
- if (store.onUpdate) store.onUpdate(store.reviewGates);
17695
- const verdict = response.decision === "approved" ? "APPROVED" : "REJECTED";
17696
- const noteText = entry.userNote ? `\nUser note: ${entry.userNote}` : "";
17697
- return `Review gate ${verdict} [${id.slice(0, 8)}]: ${params.description}${noteText}`;
17698
- },
17699
- toolSchema: {
17700
- name: "request_review_gate",
17701
- description: `Pause execution and request explicit human approval at a significant decision point.
17702
-
17703
- Review gates protect meaning. Stop before crossing decisions that affect interpretation, evidence, cost, credentials, platform, or public commitment.
17704
-
17705
- **When to use:**
17706
- - Synthesizing findings before narrowing research scope
17707
- - Hard-to-reverse decisions (refactors, architectural pivots, dependency swaps)
17708
- - Decisions affecting cost, credentials, or external commitments
17709
- - Major direction changes after exploration
17710
-
17711
- **When NOT to use:**
17712
- - Routine operations (reading files, running tests, listing directories)
17713
- - Operations already covered by the standard permission system (file edits, bash commands)
17714
- - Trivial choices that wouldn't matter to someone resuming this work
17715
-
17716
- 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.`,
17717
- parameters: {
17718
- type: "object",
17719
- properties: {
17720
- description: {
17721
- type: "string",
17722
- description: "Clear explanation of what the user is being asked to approve, including relevant context"
17723
- },
17724
- options: {
17725
- type: "array",
17726
- items: { type: "string" },
17727
- description: "Optional list of alternatives the user can choose between"
17728
- },
17729
- recommendation: {
17730
- type: "string",
17731
- description: "Optional recommendation from the AI on the preferred path and why"
17732
- }
17733
- },
17734
- required: ["description"]
17735
- }
17736
- }
17737
- };
17738
- }
17739
- /**
17740
- * Create a new empty ReviewGateStore
17741
- */
17742
- function createReviewGateStore(onUpdate) {
17743
- return {
17744
- reviewGates: [],
17745
- onUpdate
17746
- };
17747
- }
17748
- //#endregion
17749
17349
  //#region src/utils/StreamLogger.ts
17750
17350
  /**
17751
17351
  * StreamLogger manages intelligent batching of SSE stream debug logs.
@@ -20061,8 +19661,8 @@ async function buildSandbox(input) {
20061
19661
  const { config, sessionId, permissionManager, checkpointStore } = input;
20062
19662
  const log = input.log ?? consoleLog;
20063
19663
  const [{ createSandboxRuntime }, { SandboxOrchestrator }, { DEFAULT_SANDBOX_CONFIG }, { ProxyManager }, { ViolationLogStore }] = await Promise.all([
20064
- import("./SandboxRuntimeAdapter-FpZRkE6D.mjs"),
20065
- import("./SandboxOrchestrator-ULWvuUct.mjs"),
19664
+ import("./SandboxRuntimeAdapter-CFEIywKt.mjs"),
19665
+ import("./SandboxOrchestrator-CeDwd6Fj.mjs"),
20066
19666
  import("./types-BFIvwByC.mjs"),
20067
19667
  import("./ProxyManager-TxEKlgdO.mjs"),
20068
19668
  import("./ViolationLogStore-byEhxa2A.mjs")
@@ -22177,4 +21777,4 @@ var AgentHistoryStore = class {
22177
21777
  }
22178
21778
  };
22179
21779
  //#endregion
22180
- export { SIGNED_OUT_BANNER as $, createTodoStore as A, searchFiles as At, isConnectionDrop as B, formatBlockersOutput as C, processFileReferences as Ct, createGetFileStructureTool as D, SessionStore as Dt, formatDecisionsOutput as E, CommandHistoryStore as Et, createCoordinateTaskTool as F, USAGE_CACHE_TTL as Ft, ALWAYS_DENIED_FOR_AGENTS as G, PermissionManager as H, createResumeAgentTool as I, DEFAULT_RETRY_CONFIG as J, DEFAULT_AGENT_MODEL as K, createBackgroundAgentTools as L, resetTodoStore as M, COMPACTION_SUMMARY_MARKER as Mt, createSkillTool as N, DEFAULT_SUBAGENT_HISTORY_TTL_MS as Nt, createWorkItemTools as O, searchCommands as Ot, parseAgentConfig as P, MAX_PASTE_SIZE as Pt, NoLocalModelsError as Q, createAgentDelegateTool as R, createBlockerTools as S, CustomCommandStore as St, createDecisionStore as T, CheckpointStore as Tt, buildCliToolList as U, substituteArguments as V, generateCliTools as W, LOCAL_SESSION_CONTINUES as X, DEFAULT_THOROUGHNESS as Y, LOGGED_OUT_RESTART as Z, createSseBackend as _, wrapTools as _t, loadProjectContext as a, loginBlocked as at, formatReviewGatesOutput as b, classifyCommandRisk as bt, checkSavedSignIn as c, signInUncheckedMessage as ct, attachLocalModels as d, buildSystemPrompt as dt, SIGN_IN_DURING_TURN as et, buildLlmBackend as f, buildSkillsPromptSection as ft, withSignedOutLocalDefault as g, findIterationBoundary as gt, resolveSignedOutHeadlessModel as h, createToolSearchTool as ht, buildProjectAgentStore as i, SignedOutCloudBackend as it, createWriteTodosTool as j, warmFileCache as jt, createFindDefinitionTool as k, formatFileSize as kt, settleSignInRefresh as l, signedOutCommandMessage as lt, resolveHeadlessModel as m, ReActAgent as mt, BackgroundAgentManager as n, SIGN_IN_EXPIRED_HEADLESS as nt, McpManager as o, signInUncheckedHeadlessMessage as ot, defaultLlmBackendDeps as p, DeferredToolRegistry as pt, DEFAULT_MAX_ITERATIONS as q, SubagentOrchestrator as r, SIGN_IN_HINT as rt, buildSandbox as s, signInUncheckedLoginMessage as st, AgentHistoryStore as t, SIGN_IN_EXPIRED as tt, startupMode as u, signedOutNoMatchMessage as ut, createReviewGateStore as v, getProcessHooks as vt, createDecisionLogTool as w, hasFileReferences as wt, createBlockerStore as x, getPlanModeFilePath as xt, createReviewGateTool as y, setWebSocketToolExecutor as yt, FallbackLlmBackend as z };
21780
+ export { signInUncheckedMessage as $, FallbackLlmBackend as A, DEFAULT_THOROUGHNESS as B, resetTodoStore as C, DEFAULT_SUBAGENT_HISTORY_TTL_MS as Ct, createResumeAgentTool as D, createCoordinateTaskTool as E, generateCliTools as F, SIGN_IN_DURING_TURN as G, LOGGED_OUT_RESTART as H, ALWAYS_DENIED_FOR_AGENTS as I, SIGN_IN_HINT as J, SIGN_IN_EXPIRED as K, DEFAULT_AGENT_MODEL as L, substituteArguments as M, PermissionManager as N, createBackgroundAgentTools as O, buildCliToolList as P, signInUncheckedLoginMessage as Q, DEFAULT_MAX_ITERATIONS as R, createWriteTodosTool as S, COMPACTION_SUMMARY_MARKER as St, parseAgentConfig as T, USAGE_CACHE_TTL as Tt, NoLocalModelsError as U, LOCAL_SESSION_CONTINUES as V, SIGNED_OUT_BANNER as W, loginBlocked as X, SignedOutCloudBackend as Y, signInUncheckedHeadlessMessage as Z, createSseBackend as _, CommandHistoryStore as _t, loadProjectContext as a, ReActAgent as at, createFindDefinitionTool as b, searchFiles as bt, checkSavedSignIn as c, wrapTools as ct, attachLocalModels as d, classifyCommandRisk as dt, signedOutCommandMessage as et, buildLlmBackend as f, getPlanModeFilePath as ft, withSignedOutLocalDefault as g, CheckpointStore as gt, resolveSignedOutHeadlessModel as h, hasFileReferences as ht, buildProjectAgentStore as i, DeferredToolRegistry as it, isConnectionDrop as j, createAgentDelegateTool as k, settleSignInRefresh as l, getProcessHooks as lt, resolveHeadlessModel as m, processFileReferences as mt, BackgroundAgentManager as n, buildSystemPrompt as nt, McpManager as o, createToolSearchTool as ot, defaultLlmBackendDeps as p, CustomCommandStore as pt, SIGN_IN_EXPIRED_HEADLESS as q, SubagentOrchestrator as r, buildSkillsPromptSection as rt, buildSandbox as s, findIterationBoundary as st, AgentHistoryStore as t, signedOutNoMatchMessage as tt, startupMode as u, setWebSocketToolExecutor as ut, createGetFileStructureTool as v, SessionStore as vt, createSkillTool as w, MAX_PASTE_SIZE as wt, createTodoStore as x, warmFileCache as xt, createWorkItemTools as y, formatFileSize as yt, DEFAULT_RETRY_CONFIG as z };