@bike4mind/cli 5.1.0 → 5.2.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-DrZ47hqO.mjs → AgentHistoryStore-dVWBO__c.mjs} +378 -17
  2. package/dist/{ApiClient-B8VxyNEM.mjs → ApiClient-ByJM2OpM.mjs} +3 -3
  3. package/dist/{BubblewrapRuntime-DotKnqtu.mjs → BubblewrapRuntime-BQICHr_L.mjs} +2 -2
  4. package/dist/ConfigStore-9rudXRh5.mjs +2 -0
  5. package/dist/{ConfigStore-DfuE49PH.mjs → ConfigStore-BnhyywYB.mjs} +1 -1
  6. package/dist/{Logger-D6QD3c7G.mjs → Logger-DqWiTWp3.mjs} +222 -90
  7. package/dist/{SandboxOrchestrator-Cm9L1TRR.mjs → SandboxOrchestrator-B-6_ssTd.mjs} +1 -1
  8. package/dist/{SandboxRuntimeAdapter-HEkl0-qG.mjs → SandboxRuntimeAdapter-CJhDJVwo.mjs} +2 -2
  9. package/dist/{SandboxRuntimeAdapter-DF9hg5Xl.mjs → SandboxRuntimeAdapter-DdF8pI-i.mjs} +1 -1
  10. package/dist/{SeatbeltRuntime-CYsIp616.mjs → SeatbeltRuntime-oPrQ1VGL.mjs} +2 -2
  11. package/dist/{WorkItemsClient-sUftLgOz.mjs → WorkItemsClient-BRvm9GFY.mjs} +1 -1
  12. package/dist/{buildToolSearch-Bb-DPCb0.mjs → buildToolSearch-BLpr9m1F.mjs} +2 -2
  13. package/dist/commands/acpCommand.mjs +5 -5
  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 +6 -6
  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-De8Q0ivE.mjs → dist-DQHccCo7.mjs} +23 -295
  25. package/dist/{fit-BsHUrxwe.mjs → fit-hHSF95FV.mjs} +3 -3
  26. package/dist/index.mjs +9 -9
  27. package/dist/{modelServers-Ca1l2hMC.mjs → modelServers-BmmJuF8X.mjs} +1 -1
  28. package/dist/{package-hEkaJgsy.mjs → package-CZ2nssWx.mjs} +1 -1
  29. package/dist/{serve-CiSddein.mjs → serve-BDv7yCLB.mjs} +163 -7
  30. package/dist/{updateChecker-dZqiMftm.mjs → updateChecker-DoKgSiYX.mjs} +1 -1
  31. package/package.json +11 -11
  32. package/dist/ConfigStore-1lUx9qD8.mjs +0 -2
@@ -1,12 +1,12 @@
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-DfuE49PH.mjs";
3
- import { a as extractErrorMessage, d as BaseStorage, f as isPrivateIP, h as redactLogValue, l as OllamaBackend, m as redactLogText, n as B4mStreamEndedError, o as getSettingsMap, p as Logger, r as createClient, s as getSettingsValue, t as B4mApiError, u as OpenAICompatibleBackend } from "./dist-De8Q0ivE.mjs";
4
- import { At as isPlaceholderImageSigningSecret, B as LOW_CONFIDENCE_COMPLETION_MODES, G as NotFoundError, Gt as secureParameters, Ht as reasoningChannelOf, I as ExpectedToolError, Jt as splitEquals, M as DecisionTextPartSchema, Mt as isRetryableError, N as DecisionsRequestSchema, Ot as isExpectedToolError, Rt as obfuscateApiKey, St as getMcpProviderMetadata, T as ChatModels, U as McpServerName, V as MODEL_DECLINED_MESSAGE, Y as PermissionDeniedError, a as htmlFirstH1, dt as assertAuthOriginMatchesApiKey, fn as frontmatterHasSourceStamp, h as ApiKeyType, ht as createReasoningWithholder, i as htmlErrorTitle, in as withholdsReasoning, it as SEARCH_RESULT_CARDS_LANGUAGE, jt as isProviderRefusalStopReason, kt as isPlaceholderApiKey, n as SESSION_ID_PATTERN, o as escapeArtifactBodyJson, qt as signImageUrl, r as isValidSessionId, rn as withRetry, st as UnprocessableEntityError, t as logger, ut as WORK_ITEM_STATUSES, w as CUSTOM_MCP_DATA_NOTICE, wt as googleMapsSearchUrl, x as CONFIDENCE_GATE_MODES, yt as fromCliTodos, z as LOCATION_MAP_LANGUAGE } from "./Logger-D6QD3c7G.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-BnhyywYB.mjs";
3
+ import { a as extractErrorMessage, c as OpenAICompatibleBackend, d as redactLogText, f as redactLogValue, l as isPrivateIP, n as B4mStreamEndedError, r as createClient, s as OllamaBackend, t as B4mApiError, u as Logger } from "./dist-DQHccCo7.mjs";
4
+ import { At as isPlaceholderApiKey, B as LOCATION_MAP_LANGUAGE, Ct as getMcpProviderMetadata, E as ChatModels, Gt as resolveSettingDefinition, H as MODEL_DECLINED_MESSAGE, Jt as signImageUrl, K as NotFoundError, Kt as secureParameters, L as ExpectedToolError, Mt as isProviderRefusalStopReason, N as DecisionTextPartSchema, Nt as isRetryableError, Ot as isEnforceCreditsLocked, P as DecisionsRequestSchema, S as CONFIDENCE_GATE_MODES, T as CUSTOM_MCP_DATA_NOTICE, Tt as googleMapsSearchUrl, Ut as reasoningChannelOf, V as LOW_CONFIDENCE_COMPLETION_MODES, W as McpServerName, X as PermissionDeniedError, Yt as splitEquals, a as htmlFirstH1, an as withholdsReasoning, at as SEARCH_RESULT_CARDS_LANGUAGE, bt as fromCliTodos, ct as UnprocessableEntityError, dt as WORK_ITEM_STATUSES, f as AdminAiStoredConfigSchema, ft as assertAuthOriginMatchesApiKey, gt as createReasoningWithholder, h as ApiKeyType, i as htmlErrorTitle, in as withRetry, jt as isPlaceholderImageSigningSecret, kt as isExpectedToolError, n as SESSION_ID_PATTERN, o as escapeArtifactBodyJson, pn as frontmatterHasSourceStamp, r as isValidSessionId, t as logger, y as BadGatewayError, zt as obfuscateApiKey } from "./Logger-DqWiTWp3.mjs";
5
5
  import { r as isReservedCommandName } from "./RemoteSkillSource-HqoLRV56.mjs";
6
6
  import { a as isPathAllowed, n as assertWritablePath, t as assertPathAllowed } from "./pathValidation-C4ADzpUR-BPIpINwZ.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-Ca1l2hMC.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-BmmJuF8X.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";
@@ -1632,7 +1632,19 @@ function createStructuredResultValidator(schema) {
1632
1632
  };
1633
1633
  }
1634
1634
  //#endregion
1635
- //#region ../../b4m-core/services/dist/webfetch-DXZS-v_A.mjs
1635
+ //#region ../../b4m-core/fab-pipeline/dist/storage-C-NmvuMy.mjs
1636
+ var BaseStorage = class {
1637
+ /**
1638
+ * Origin a browser fetches this storage's signed GET links from, or '' when signed links
1639
+ * are not usable by a browser here. Storages that cannot presign for browsers keep the
1640
+ * default.
1641
+ */
1642
+ async browserSigningOrigin() {
1643
+ return "";
1644
+ }
1645
+ };
1646
+ //#endregion
1647
+ //#region ../../b4m-core/services/dist/webfetch-DzpNrmBv.mjs
1636
1648
  const htmlToMarkdown = (html, _isArxiv = false) => {
1637
1649
  const turndownService = new turndown({
1638
1650
  headingStyle: "atx",
@@ -2042,6 +2054,22 @@ var UnreachableScrapeTargetError = class extends UnprocessableEntityError {
2042
2054
  this.cause = cause;
2043
2055
  }
2044
2056
  };
2057
+ function isNoResponseError(error) {
2058
+ return error instanceof FirecrawlError && error.statusCode === 0;
2059
+ }
2060
+ /**
2061
+ * The scraping provider could not be reached. A transient upstream outage, not a fault of ours or of
2062
+ * the URL: a 502 that /api/tools/web-fetch logs at warn (`expected`) instead of paging, with a message
2063
+ * that names no provider.
2064
+ */
2065
+ var ScrapeProviderUnreachableError = class extends BadGatewayError {
2066
+ constructor(cause) {
2067
+ super("The page could not be fetched right now: the web scraping service is unreachable. Try again later.");
2068
+ this.name = "ScrapeProviderUnreachableError";
2069
+ this.expected = true;
2070
+ this.cause = cause;
2071
+ }
2072
+ };
2045
2073
  /** Scrape after a 1s wait for client-side rendering, retrying without the action where Firecrawl rejects actions. */
2046
2074
  async function scrapeAfterRenderWait(app, url, params) {
2047
2075
  try {
@@ -2101,6 +2129,7 @@ async function firecrawlFetch(adapters, url, options) {
2101
2129
  if (scrapeError instanceof FirecrawlError && scrapeError.statusCode === 403) throw new UnsupportedScrapeTargetError(url, scrapeError);
2102
2130
  if (isUnsupportedFileTypeError(scrapeError)) throw new UnsupportedContentTypeError(scrapeError);
2103
2131
  if (isAllEnginesFailedError(scrapeError)) throw new UnreachableScrapeTargetError(scrapeError);
2132
+ if (isNoResponseError(scrapeError)) throw new ScrapeProviderUnreachableError(scrapeError);
2104
2133
  throw scrapeError;
2105
2134
  }
2106
2135
  const durationMs = Date.now() - startedAt;
@@ -2257,6 +2286,14 @@ const webFetchTool = {
2257
2286
  await context.statusUpdate({}, "WebFetch: unsupported file type");
2258
2287
  return WEB_FETCH_UNSUPPORTED_FILE_TYPE_MSG;
2259
2288
  }
2289
+ if (error instanceof ScrapeProviderUnreachableError) {
2290
+ context.logger.warn("WebFetch scraping provider unreachable", {
2291
+ url: params.url,
2292
+ cause: error.cause instanceof Error ? error.cause.message : void 0
2293
+ });
2294
+ await context.statusUpdate({}, "WebFetch: network error");
2295
+ return WEB_FETCH_UNREACHABLE_MSG;
2296
+ }
2260
2297
  if (error instanceof UnreachableScrapeTargetError) {
2261
2298
  context.logger.warn("WebFetch page unreachable", {
2262
2299
  url: params.url,
@@ -3490,6 +3527,288 @@ const weatherTool = {
3490
3527
  })
3491
3528
  };
3492
3529
  //#endregion
3530
+ //#region ../../b4m-core/utils/dist/settings-Emj-jnxm.mjs
3531
+ /**
3532
+ * In-memory cache for admin settings with TTL support and active cleanup
3533
+ * Can be easily extended to use Redis for production
3534
+ */
3535
+ var AdminSettingsCache = class AdminSettingsCache {
3536
+ cache = /* @__PURE__ */ new Map();
3537
+ individualCache = /* @__PURE__ */ new Map();
3538
+ /**
3539
+ * Every call through this field is optional-chained (`this.logger.debug?.()`).
3540
+ *
3541
+ * A cache must not throw because it could not log, and this one is exposed to that: it is a
3542
+ * process-wide singleton created with whichever logger happens to reach `getSettingsCache` first.
3543
+ * What each caller then does with a throw varies, and it is mostly NOT a degrade-to-defaults
3544
+ * guard: `getSettingsByNames` has none at all, the scoped resolver guards one layer out in
3545
+ * `resolveAll`, and `resolveSpendLevers` deliberately rethrows to halt spend. So a logger missing
3546
+ * a quieter level could surface as a silent wrong VALUE, as an unhandled rejection, or as a hard
3547
+ * fail-closed, depending on who asked. `ScopedSettingsCache` is built by the same factory pair
3548
+ * and still has one unguarded call - the same hazard, not a solved one.
3549
+ */
3550
+ logger;
3551
+ cleanupInterval = null;
3552
+ maxCacheSize = 1e3;
3553
+ static DEFAULT_TTL = 3e5;
3554
+ static DEVELOPMENT_TTL = 3e4;
3555
+ static CLEANUP_INTERVAL = 6e4;
3556
+ constructor(logger) {
3557
+ this.logger = logger;
3558
+ this.startCleanupTimer();
3559
+ }
3560
+ /**
3561
+ * Start periodic cleanup timer (only in persistent environments)
3562
+ */
3563
+ startCleanupTimer() {
3564
+ if (process.env.NODE_ENV !== "production" || process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME) {
3565
+ this.logger.debug?.("Skipping cleanup timer in serverless environment");
3566
+ return;
3567
+ }
3568
+ this.cleanupInterval = setInterval(() => {
3569
+ this.performCleanup();
3570
+ }, AdminSettingsCache.CLEANUP_INTERVAL);
3571
+ this.logger.debug?.("Started cache cleanup timer");
3572
+ }
3573
+ /**
3574
+ * Stop cleanup timer (for graceful shutdown)
3575
+ */
3576
+ stopCleanupTimer() {
3577
+ if (this.cleanupInterval) {
3578
+ clearInterval(this.cleanupInterval);
3579
+ this.cleanupInterval = null;
3580
+ this.logger.debug?.("Stopped cache cleanup timer");
3581
+ }
3582
+ }
3583
+ /**
3584
+ * Active cleanup of expired entries
3585
+ */
3586
+ performCleanup() {
3587
+ const beforeSize = this.cache.size + this.individualCache.size;
3588
+ let removedCount = 0;
3589
+ for (const [key, entry] of Array.from(this.cache.entries())) if (!this.isValid(entry.timestamp, entry.ttl)) {
3590
+ this.cache.delete(key);
3591
+ removedCount++;
3592
+ }
3593
+ for (const [key, entry] of Array.from(this.individualCache.entries())) if (!this.isValid(entry.timestamp, entry.ttl)) {
3594
+ this.individualCache.delete(key);
3595
+ removedCount++;
3596
+ }
3597
+ if (this.individualCache.size > this.maxCacheSize) {
3598
+ const entries = Array.from(this.individualCache.entries());
3599
+ entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
3600
+ const toRemove = this.individualCache.size - this.maxCacheSize;
3601
+ for (let i = 0; i < toRemove; i++) {
3602
+ this.individualCache.delete(entries[i][0]);
3603
+ removedCount++;
3604
+ }
3605
+ this.logger.warn?.(`Emergency cache cleanup: removed ${toRemove} entries due to size limit`);
3606
+ }
3607
+ if (removedCount > 0) this.logger.debug?.(`Cache cleanup removed ${removedCount} expired entries (${beforeSize} → ${this.cache.size + this.individualCache.size})`);
3608
+ }
3609
+ /**
3610
+ * Get TTL based on environment
3611
+ */
3612
+ getTTL() {
3613
+ return process.env.NODE_ENV === "development" ? AdminSettingsCache.DEVELOPMENT_TTL : AdminSettingsCache.DEFAULT_TTL;
3614
+ }
3615
+ /**
3616
+ * Check if cache entry is valid (not expired)
3617
+ */
3618
+ isValid(timestamp, ttl) {
3619
+ return Date.now() - timestamp < ttl;
3620
+ }
3621
+ /**
3622
+ * Get all admin settings with caching
3623
+ */
3624
+ async getSettingsMap(db) {
3625
+ const cacheKey = "all_settings";
3626
+ const cached = this.cache.get(cacheKey);
3627
+ if (cached && this.isValid(cached.timestamp, cached.ttl)) {
3628
+ this.logger.debug?.("📦 Admin settings cache HIT");
3629
+ return cached.data;
3630
+ }
3631
+ if (cached) this.cache.delete(cacheKey);
3632
+ this.logger.debug?.("🔍 Admin settings cache MISS - fetching from database");
3633
+ const fetchStart = Date.now();
3634
+ const settingsMap = (await db.adminSettings.findAll()).reduce((out, s) => {
3635
+ out[s.settingName] = s.settingValue;
3636
+ return out;
3637
+ }, {});
3638
+ const fetchTime = Date.now() - fetchStart;
3639
+ this.logger.info?.(`📦 Cached ${Object.keys(settingsMap).length} admin settings in ${fetchTime}ms`);
3640
+ const ttl = this.getTTL();
3641
+ this.cache.set(cacheKey, {
3642
+ data: settingsMap,
3643
+ timestamp: Date.now(),
3644
+ ttl
3645
+ });
3646
+ Object.entries(settingsMap).forEach(([key, value]) => {
3647
+ this.individualCache.set(key, {
3648
+ value,
3649
+ timestamp: Date.now(),
3650
+ ttl
3651
+ });
3652
+ });
3653
+ return settingsMap;
3654
+ }
3655
+ /**
3656
+ * Get individual admin setting with caching
3657
+ */
3658
+ async getSettingByName(settingName, db) {
3659
+ const cached = this.individualCache.get(settingName);
3660
+ if (cached && this.isValid(cached.timestamp, cached.ttl)) {
3661
+ this.logger.debug?.(`📦 Individual setting '${settingName}' cache HIT`);
3662
+ return cached.value;
3663
+ }
3664
+ if (cached) this.individualCache.delete(settingName);
3665
+ this.logger.debug?.(`🔍 Individual setting '${settingName}' cache MISS - fetching from database`);
3666
+ const fetchStart = Date.now();
3667
+ const value = (await db.adminSettings.findBySettingName(settingName))?.settingValue ?? null;
3668
+ const fetchTime = Date.now() - fetchStart;
3669
+ this.logger.debug?.(`📦 Cached individual setting '${settingName}' in ${fetchTime}ms`);
3670
+ this.individualCache.set(settingName, {
3671
+ value,
3672
+ timestamp: Date.now(),
3673
+ ttl: this.getTTL()
3674
+ });
3675
+ return value;
3676
+ }
3677
+ /**
3678
+ * Get multiple admin settings with caching
3679
+ */
3680
+ async getSettingsByNames(settingNames, db) {
3681
+ const result = {};
3682
+ const uncachedSettings = [];
3683
+ for (const settingName of settingNames) {
3684
+ const cached = this.individualCache.get(settingName);
3685
+ if (cached && this.isValid(cached.timestamp, cached.ttl)) {
3686
+ if (cached.value !== null) result[settingName] = cached.value;
3687
+ } else {
3688
+ if (cached) this.individualCache.delete(settingName);
3689
+ uncachedSettings.push(settingName);
3690
+ }
3691
+ }
3692
+ if (uncachedSettings.length > 0) {
3693
+ this.logger.debug?.(`🔍 Batch fetching ${uncachedSettings.length} uncached settings: ${uncachedSettings.join(", ")}`);
3694
+ const fetchStart = Date.now();
3695
+ const settings = await db.adminSettings.findBySettingNames(uncachedSettings);
3696
+ const fetchTime = Date.now() - fetchStart;
3697
+ this.logger.debug?.(`📦 Batch fetched ${settings.length} settings in ${fetchTime}ms`);
3698
+ const ttl = this.getTTL();
3699
+ settings.forEach((setting) => {
3700
+ result[setting.settingName] = setting.settingValue;
3701
+ this.individualCache.set(setting.settingName, {
3702
+ value: setting.settingValue,
3703
+ timestamp: Date.now(),
3704
+ ttl
3705
+ });
3706
+ });
3707
+ uncachedSettings.forEach((settingName) => {
3708
+ if (!settings.some((s) => s.settingName === settingName)) this.individualCache.set(settingName, {
3709
+ value: null,
3710
+ timestamp: Date.now(),
3711
+ ttl
3712
+ });
3713
+ });
3714
+ }
3715
+ this.logger.debug?.(`📦 Returned ${Object.keys(result).length} settings (${settingNames.length - uncachedSettings.length} from cache, ${uncachedSettings.length} from DB)`);
3716
+ return result;
3717
+ }
3718
+ /**
3719
+ * Invalidate specific setting(s) from cache
3720
+ */
3721
+ invalidateSetting(settingName) {
3722
+ this.individualCache.delete(settingName);
3723
+ this.cache.delete("all_settings");
3724
+ this.logger.info?.(`🗑️ Invalidated cache for setting: ${settingName}`);
3725
+ }
3726
+ /**
3727
+ * Invalidate all cached admin settings
3728
+ */
3729
+ invalidateAll() {
3730
+ this.cache.clear();
3731
+ this.individualCache.clear();
3732
+ this.logger.info?.("🗑️ Invalidated all admin settings cache");
3733
+ }
3734
+ /**
3735
+ * Get cache statistics for monitoring
3736
+ */
3737
+ getStats() {
3738
+ const estimateMemoryUsage = () => {
3739
+ let totalSize = 0;
3740
+ for (const [key, value] of Array.from(this.individualCache.entries())) {
3741
+ totalSize += key.length * 2;
3742
+ totalSize += (value.value?.length || 0) * 2;
3743
+ totalSize += 32;
3744
+ }
3745
+ return totalSize;
3746
+ };
3747
+ return {
3748
+ totalEntries: this.cache.size,
3749
+ individualEntries: this.individualCache.size,
3750
+ memoryUsage: {
3751
+ approximate: `~${Math.round(estimateMemoryUsage() / 1024)}KB`,
3752
+ cacheSize: this.cache.size,
3753
+ individualCacheSize: this.individualCache.size
3754
+ },
3755
+ environment: {
3756
+ isServerless: !!(process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME),
3757
+ hasCleanupTimer: this.cleanupInterval !== null
3758
+ }
3759
+ };
3760
+ }
3761
+ /**
3762
+ * Warm up the cache by fetching all settings
3763
+ */
3764
+ async warmUp(db) {
3765
+ this.logger.info?.("🔥 Warming up admin settings cache...");
3766
+ await this.getSettingsMap(db);
3767
+ this.logger.info?.("✅ Admin settings cache warmed up");
3768
+ }
3769
+ /**
3770
+ * Graceful shutdown - cleanup timers
3771
+ */
3772
+ shutdown() {
3773
+ this.stopCleanupTimer();
3774
+ this.logger.info?.("🛑 Admin settings cache shutdown complete");
3775
+ }
3776
+ };
3777
+ let globalSettingsCache = null;
3778
+ /**
3779
+ * Get or create the global settings cache instance
3780
+ */
3781
+ function getSettingsCache(logger) {
3782
+ if (!globalSettingsCache) globalSettingsCache = new AdminSettingsCache(logger || new Logger());
3783
+ return globalSettingsCache;
3784
+ }
3785
+ function getSettingsValue(key, settings, defaultValue) {
3786
+ if (key === "enforceCredits" && isEnforceCreditsLocked()) return true;
3787
+ const settingConfig = resolveSettingDefinition(key);
3788
+ if (!settingConfig) {
3789
+ Logger.globalInstance.warn(`Unknown setting key: ${key}`);
3790
+ return defaultValue;
3791
+ }
3792
+ const rawValue = settings[key];
3793
+ const parsed = (key === "adminAiConfig" ? AdminAiStoredConfigSchema : settingConfig.schema).safeParse(rawValue);
3794
+ if (parsed.success) {
3795
+ if (parsed.data === "" && defaultValue !== void 0) return defaultValue;
3796
+ return parsed.data;
3797
+ } else return defaultValue !== void 0 ? defaultValue : settingConfig.defaultValue;
3798
+ }
3799
+ /**
3800
+ * Retrieves all admin settings from the database and converts them into a key-value map.
3801
+ * Uses caching for improved performance.
3802
+ */
3803
+ async function getSettingsMap(db, options) {
3804
+ const logger = options?.logger;
3805
+ if (options?.skipCache) return (options?.names ? await db.adminSettings.findBySettingNames(options.names) : await db.adminSettings.findAll()).reduce((out, s) => {
3806
+ out[s.settingName] = s.settingValue;
3807
+ return out;
3808
+ }, {});
3809
+ return getSettingsCache(logger).getSettingsMap(db);
3810
+ }
3811
+ //#endregion
3493
3812
  //#region ../../b4m-core/utils/dist/globMatches.mjs
3494
3813
  /**
3495
3814
  * Backtrack-free glob match where `*` is the only wildcard and every other character is a
@@ -3715,7 +4034,7 @@ async function isOperationalBillingEnabled(db, logger, holder) {
3715
4034
  return holder ? isFreeTierHolder(holder) : false;
3716
4035
  }
3717
4036
  //#endregion
3718
- //#region ../../b4m-core/services/dist/toolGenerators-CflzUkRh.mjs
4037
+ //#region ../../b4m-core/services/dist/toolGenerators-ZXY0wEjP.mjs
3719
4038
  const diceRoll = async (parameters) => {
3720
4039
  if (!parameters?.sides || !parameters?.times) throw new Error("Tool dice roll: Missing required parameters");
3721
4040
  return sum(times(parameters.times, () => random(1, parameters.sides))).toString();
@@ -3744,16 +4063,29 @@ const diceRollTool = {
3744
4063
  }
3745
4064
  })
3746
4065
  };
3747
- let mathInstance = null;
3748
- function loadMath() {
3749
- mathInstance ??= import("mathjs").then(({ create, all }) => create(all, {
4066
+ let mathModule = null;
4067
+ function loadMathModule() {
4068
+ mathModule ??= import("mathjs").catch((error) => {
4069
+ mathModule = null;
4070
+ throw error;
4071
+ });
4072
+ return mathModule;
4073
+ }
4074
+ const DISABLED_FUNCTIONS = ["import", "createUnit"];
4075
+ function disabledFunction(name) {
4076
+ return () => {
4077
+ throw new Error(`Function ${name} is disabled`);
4078
+ };
4079
+ }
4080
+ /** A fresh instance per evaluation, so nothing an expression does to it reaches another (~10-25 ms each). */
4081
+ async function createIsolatedMath() {
4082
+ const { create, all } = await loadMathModule();
4083
+ const math = create(all, {
3750
4084
  number: "BigNumber",
3751
4085
  precision: 14
3752
- })).catch((error) => {
3753
- mathInstance = null;
3754
- throw error;
3755
4086
  });
3756
- return mathInstance;
4087
+ math.import(Object.fromEntries(DISABLED_FUNCTIONS.map((name) => [name, disabledFunction(name)])), { override: true });
4088
+ return math;
3757
4089
  }
3758
4090
  /**
3759
4091
  * Format a scalar result. Integers render in full via fixed notation so large
@@ -3788,7 +4120,7 @@ function evaluateInput(evaluate) {
3788
4120
  }
3789
4121
  async function evaluateMath(params) {
3790
4122
  Logger.globalInstance.log("🔢 Math Tool: Starting evaluation of expression:", params.expression);
3791
- const math = await loadMath();
4123
+ const math = await createIsolatedMath();
3792
4124
  try {
3793
4125
  let expression = params.expression.trim();
3794
4126
  expression = expression.replace(/\/\*[\s\S]*?\*\//g, "");
@@ -3873,6 +4205,11 @@ async function evaluateMath(params) {
3873
4205
  if (error instanceof MathEvaluationError) throw error;
3874
4206
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
3875
4207
  const FailureError = error instanceof MathInputError ? MathEvaluationError : Error;
4208
+ const disabledFunctionName = errorMessage.match(/Function (\w+) is disabled/);
4209
+ if (disabledFunctionName) {
4210
+ const name = disabledFunctionName[1];
4211
+ throw new FailureError(`Failed to evaluate math expression "${params.expression}". Reason: "${name}" is not available in this tool. Rewrite the expression without it; for a custom unit, write it as a multiple of a built-in unit (e.g. "5 * 0.3 m").`);
4212
+ }
3876
4213
  const undefinedSymbol = errorMessage.match(/Undefined symbol (\w+)/);
3877
4214
  if (undefinedSymbol) {
3878
4215
  const symbol = undefinedSymbol[1];
@@ -4581,7 +4918,7 @@ const askUserQuestionTool = {
4581
4918
  * re-export them without pulling the full tool graph. `index.ts` re-exports them
4582
4919
  * so the server barrel's public API is unchanged.
4583
4920
  */
4584
- const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFilter, kbScope, inlinedAttachmentIds, attachedFileIds, fullyInlinedAttachmentIds, suppressLakeArms, sessionRetrievalTags, sessionReaderConsentDatalakeTags, sessionLakeScopeExplicit, sessionIncludeLibraryFiles, sessionPreauthorizedLakeIds, organizationId, governingOrgModelPolicy, authOrigin, apiKeyId, questId, requestConfirmation, urlProvenance, slackDestination, numberCitables, decide, toLedgerModel, getAbortSignal }, storage, imageGenerateStorage, statusUpdate, onStart, onFinish, llm, config, model, imageProcessorLambdaName, tools, allowedDirectories, entitlementKeys = [], sessionId, codeMinifier, availableModels, onToolLlmUsage, servingModel) => {
4921
+ const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFilter, kbScope, inlinedAttachmentIds, attachedFileIds, fullyInlinedAttachmentIds, suppressLakeArms, sessionRetrievalTags, sessionReaderConsentDatalakeTags, sessionLakeScopeExplicit, sessionIncludeLibraryFiles, sessionPreauthorizedLakeIds, followedLakeIds, organizationId, governingOrgModelPolicy, authOrigin, apiKeyId, questId, requestConfirmation, urlProvenance, slackDestination, numberCitables, decide, toLedgerModel, getAbortSignal }, storage, imageGenerateStorage, statusUpdate, onStart, onFinish, llm, config, model, imageProcessorLambdaName, tools, allowedDirectories, entitlementKeys = [], sessionId, codeMinifier, availableModels, onToolLlmUsage, servingModel) => {
4585
4922
  assertAuthOriginMatchesApiKey(authOrigin, apiKeyId);
4586
4923
  const context = {
4587
4924
  userId,
@@ -4615,6 +4952,7 @@ const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFil
4615
4952
  sessionLakeScopeExplicit,
4616
4953
  sessionIncludeLibraryFiles,
4617
4954
  sessionPreauthorizedLakeIds,
4955
+ followedLakeIds,
4618
4956
  organizationId,
4619
4957
  governingOrgModelPolicy,
4620
4958
  authOrigin,
@@ -20157,8 +20495,8 @@ async function buildSandbox(input) {
20157
20495
  const { config, sessionId, permissionManager, checkpointStore } = input;
20158
20496
  const log = input.log ?? consoleLog;
20159
20497
  const [{ createSandboxRuntime }, { SandboxOrchestrator }, { DEFAULT_SANDBOX_CONFIG }, { ProxyManager }, { ViolationLogStore }] = await Promise.all([
20160
- import("./SandboxRuntimeAdapter-DF9hg5Xl.mjs"),
20161
- import("./SandboxOrchestrator-Cm9L1TRR.mjs"),
20498
+ import("./SandboxRuntimeAdapter-DdF8pI-i.mjs"),
20499
+ import("./SandboxOrchestrator-B-6_ssTd.mjs"),
20162
20500
  import("./types-BFIvwByC.mjs"),
20163
20501
  import("./ProxyManager-TxEKlgdO.mjs"),
20164
20502
  import("./ViolationLogStore-byEhxa2A.mjs")
@@ -20496,6 +20834,8 @@ var MCPClient = class {
20496
20834
  disconnected = false;
20497
20835
  connectionVersion = 0;
20498
20836
  tools = [];
20837
+ /** What each tool's server says about it (MCP tool annotations), by tool name; see McpToolHints. */
20838
+ toolHints = /* @__PURE__ */ new Map();
20499
20839
  serverName;
20500
20840
  constructor({ envVariables, name, command, args, suppressStderr = false, onStderrLine, url, headers }) {
20501
20841
  this.mcp = createSdkClient();
@@ -20573,6 +20913,7 @@ var MCPClient = class {
20573
20913
  input_schema: tool.inputSchema
20574
20914
  };
20575
20915
  });
20916
+ this.toolHints = hintsByTool(toolsResult.tools);
20576
20917
  } catch (e) {
20577
20918
  if (this.transport) {
20578
20919
  try {
@@ -20609,6 +20950,7 @@ var MCPClient = class {
20609
20950
  description: tool.description,
20610
20951
  input_schema: tool.inputSchema
20611
20952
  }));
20953
+ this.toolHints = hintsByTool(toolsResult.tools);
20612
20954
  }
20613
20955
  /**
20614
20956
  * Replace an expired HTTP session with a new one: a fresh SDK client and transport, re-initialized,
@@ -20761,6 +21103,25 @@ var MCPClient = class {
20761
21103
  }
20762
21104
  }
20763
21105
  };
21106
+ function hintsByTool(tools) {
21107
+ const hints = /* @__PURE__ */ new Map();
21108
+ for (const tool of tools) {
21109
+ const annotations = tool.annotations;
21110
+ if (typeof annotations !== "object" || annotations === null) continue;
21111
+ const read = (key) => {
21112
+ const value = annotations[key];
21113
+ return typeof value === "boolean" ? value : void 0;
21114
+ };
21115
+ const entry = {
21116
+ ...read("readOnlyHint") !== void 0 ? { readOnly: read("readOnlyHint") } : {},
21117
+ ...read("destructiveHint") !== void 0 ? { destructive: read("destructiveHint") } : {},
21118
+ ...read("idempotentHint") !== void 0 ? { idempotent: read("idempotentHint") } : {},
21119
+ ...read("openWorldHint") !== void 0 ? { openWorld: read("openWorldHint") } : {}
21120
+ };
21121
+ if (Object.keys(entry).length > 0) hints.set(tool.name, entry);
21122
+ }
21123
+ return hints;
21124
+ }
20764
21125
  //#endregion
20765
21126
  //#region src/utils/mcpAdapter.ts
20766
21127
  const CACHE_VERSION = 1;
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { b as AuthenticatedApiClient, t as ConfigStore, x as DeviceFlowClient } from "./ConfigStore-DfuE49PH.mjs";
3
- import { t as logger } from "./Logger-D6QD3c7G.mjs";
4
- import { t as version } from "./package-hEkaJgsy.mjs";
2
+ import { b as AuthenticatedApiClient, t as ConfigStore, x as DeviceFlowClient } from "./ConfigStore-BnhyywYB.mjs";
3
+ import { t as logger } from "./Logger-DqWiTWp3.mjs";
4
+ import { t as version } from "./package-CZ2nssWx.mjs";
5
5
  import { isAxiosError } from "axios";
6
6
  import { Readable } from "node:stream";
7
7
  //#region src/auth/OAuthClient.ts
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as logger } from "./Logger-D6QD3c7G.mjs";
3
- import { a as getContainerSocketPaths, c as resolveSandboxPath, o as getProtectedWorkspacePaths, s as isBinaryAvailable, t as assertProxyPort } from "./SandboxRuntimeAdapter-HEkl0-qG.mjs";
2
+ import { t as logger } from "./Logger-DqWiTWp3.mjs";
3
+ import { a as getContainerSocketPaths, c as resolveSandboxPath, o as getProtectedWorkspacePaths, s as isBinaryAvailable, t as assertProxyPort } from "./SandboxRuntimeAdapter-CJhDJVwo.mjs";
4
4
  import { lstatSync, mkdirSync, statSync } from "fs";
5
5
  import os from "os";
6
6
  import path from "path";
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export { t as ConfigStore } from "./ConfigStore-BnhyywYB.mjs";
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { T as ChatModels, t as logger } from "./Logger-D6QD3c7G.mjs";
2
+ import { E as ChatModels, t as logger } from "./Logger-DqWiTWp3.mjs";
3
3
  import { t as DEFAULT_SANDBOX_CONFIG } from "./types-CxrzVXel.mjs";
4
4
  import { isDeepStrictEqual } from "node:util";
5
5
  import { existsSync, promises } from "fs";