@bike4mind/cli 5.0.1 → 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-DW6BBbVj.mjs → AgentHistoryStore-dVWBO__c.mjs} +436 -30
  2. package/dist/{ApiClient-D4bDuWXg.mjs → ApiClient-ByJM2OpM.mjs} +3 -3
  3. package/dist/{BubblewrapRuntime-D3EO5Y0C.mjs → BubblewrapRuntime-BQICHr_L.mjs} +2 -2
  4. package/dist/ConfigStore-9rudXRh5.mjs +2 -0
  5. package/dist/{ConfigStore-BuLA_-uZ.mjs → ConfigStore-BnhyywYB.mjs} +1 -1
  6. package/dist/{Logger-CjaYx85U.mjs → Logger-DqWiTWp3.mjs} +1842 -381
  7. package/dist/{SandboxOrchestrator-yORi2eFV.mjs → SandboxOrchestrator-B-6_ssTd.mjs} +1 -1
  8. package/dist/{SandboxRuntimeAdapter-BmkaFzqU.mjs → SandboxRuntimeAdapter-CJhDJVwo.mjs} +2 -2
  9. package/dist/{SandboxRuntimeAdapter-BjJwJNfg.mjs → SandboxRuntimeAdapter-DdF8pI-i.mjs} +1 -1
  10. package/dist/{SeatbeltRuntime-CyZNmFwD.mjs → SeatbeltRuntime-oPrQ1VGL.mjs} +2 -2
  11. package/dist/{WorkItemsClient-xmo0DrCm.mjs → WorkItemsClient-BRvm9GFY.mjs} +1 -1
  12. package/dist/{buildToolSearch-CXxEtVKc.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-DsMzCRLX.mjs → dist-DQHccCo7.mjs} +122 -303
  25. package/dist/{fit-C9eLTDcR.mjs → fit-hHSF95FV.mjs} +3 -3
  26. package/dist/index.mjs +9 -9
  27. package/dist/{modelServers-DeOGFwLi.mjs → modelServers-BmmJuF8X.mjs} +1 -1
  28. package/dist/{package-CvffLo0I.mjs → package-CZ2nssWx.mjs} +1 -1
  29. package/dist/{serve-tmC__JNj.mjs → serve-BDv7yCLB.mjs} +247 -18
  30. package/dist/{updateChecker-U4AfrPKj.mjs → updateChecker-DoKgSiYX.mjs} +1 -1
  31. package/package.json +13 -14
  32. package/dist/ConfigStore-DdqxfmDr.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-BuLA_-uZ.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-DsMzCRLX.mjs";
4
- import { At as isProviderRefusalStopReason, B as LOW_CONFIDENCE_COMPLETION_MODES, G as NotFoundError, I as ExpectedToolError, Kt as signImageUrl, Lt as obfuscateApiKey, M as DecisionTextPartSchema, N as DecisionsRequestSchema, Ot as isExpectedToolError, St as getMcpProviderMetadata, T as ChatModels, U as McpServerName, V as MODEL_DECLINED_MESSAGE, Vt as reasoningChannelOf, Wt as secureParameters, Y as PermissionDeniedError, a as htmlFirstH1, dn as frontmatterHasSourceStamp, dt as assertAuthOriginMatchesApiKey, h as ApiKeyType, ht as createReasoningWithholder, i as htmlErrorTitle, it as SEARCH_RESULT_CARDS_LANGUAGE, jt as isRetryableError, kt as isPlaceholderImageSigningSecret, n as SESSION_ID_PATTERN, nn as withRetry, o as escapeArtifactBodyJson, qt as splitEquals, r as isValidSessionId, rn as withholdsReasoning, 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-CjaYx85U.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-DeOGFwLi.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";
@@ -1270,6 +1270,7 @@ var apiKeyService_exports$1 = /* @__PURE__ */ __exportAll$2({
1270
1270
  setApiKey: () => setApiKey,
1271
1271
  sharedAdminKeyProviders: () => sharedAdminKeyProviders,
1272
1272
  t: () => apiKeyService_exports$2,
1273
+ usableApiKey: () => usableApiKey,
1273
1274
  userKeyProviders: () => userKeyProviders
1274
1275
  });
1275
1276
  const createApiKeySchema = z$1.object({
@@ -1348,6 +1349,15 @@ const ENV_KEY_MAP = {
1348
1349
  const envKey = (name) => process.env.B4M_SELF_HOST === "true" && process.env[name]?.trim() || null;
1349
1350
  /** What getEffectiveLLMApiKeys returns in place of a user's own key once it has expired. */
1350
1351
  const EXPIRED_API_KEY = "expired";
1352
+ /**
1353
+ * The trimmed key when `value` is a usable credential, else null: absent, blank, the expired marker
1354
+ * and any recognized placeholder are not credentials. The one predicate for "can this go upstream".
1355
+ */
1356
+ const usableApiKey = (value) => {
1357
+ const trimmed = value?.trim();
1358
+ if (!trimmed || trimmed === "expired" || isPlaceholderApiKey(trimmed)) return null;
1359
+ return trimmed;
1360
+ };
1351
1361
  const getSerperKey = async (adapters) => {
1352
1362
  const { db } = adapters;
1353
1363
  return (await db.adminSettings.findBySettingName("SerperKey"))?.settingValue;
@@ -1566,6 +1576,7 @@ var apiKeyService_exports$2 = /* @__PURE__ */ __exportAll({
1566
1576
  listOwnApiKeys: () => listOwnApiKeys,
1567
1577
  setApiKey: () => setApiKey,
1568
1578
  sharedAdminKeyProviders: () => sharedAdminKeyProviders,
1579
+ usableApiKey: () => usableApiKey,
1569
1580
  userKeyProviders: () => userKeyProviders
1570
1581
  });
1571
1582
  //#endregion
@@ -1621,7 +1632,19 @@ function createStructuredResultValidator(schema) {
1621
1632
  };
1622
1633
  }
1623
1634
  //#endregion
1624
- //#region ../../b4m-core/services/dist/webfetch-Bw4BUb5S.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
1625
1648
  const htmlToMarkdown = (html, _isArxiv = false) => {
1626
1649
  const turndownService = new turndown({
1627
1650
  headingStyle: "atx",
@@ -1907,6 +1930,7 @@ async function plainFetchScrape(url, options) {
1907
1930
  title
1908
1931
  };
1909
1932
  }
1933
+ const URL_NOT_IN_CONVERSATION_MESSAGE = "This URL does not appear in anything the user sent or in an earlier search, page, file or tool result in this conversation, so it was not fetched. Only fetch URLs exactly as they appear there; to find a page, use web_search, or ask the user to paste the link.";
1910
1934
  const DEFAULT_TIMEOUT_MS = 6e4;
1911
1935
  const PDF_TIMEOUT_MS = 9e4;
1912
1936
  const WEB_FETCH_CONTENT_CAP = 5e4;
@@ -2030,6 +2054,22 @@ var UnreachableScrapeTargetError = class extends UnprocessableEntityError {
2030
2054
  this.cause = cause;
2031
2055
  }
2032
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
+ };
2033
2073
  /** Scrape after a 1s wait for client-side rendering, retrying without the action where Firecrawl rejects actions. */
2034
2074
  async function scrapeAfterRenderWait(app, url, params) {
2035
2075
  try {
@@ -2089,6 +2129,7 @@ async function firecrawlFetch(adapters, url, options) {
2089
2129
  if (scrapeError instanceof FirecrawlError && scrapeError.statusCode === 403) throw new UnsupportedScrapeTargetError(url, scrapeError);
2090
2130
  if (isUnsupportedFileTypeError(scrapeError)) throw new UnsupportedContentTypeError(scrapeError);
2091
2131
  if (isAllEnginesFailedError(scrapeError)) throw new UnreachableScrapeTargetError(scrapeError);
2132
+ if (isNoResponseError(scrapeError)) throw new ScrapeProviderUnreachableError(scrapeError);
2092
2133
  throw scrapeError;
2093
2134
  }
2094
2135
  const durationMs = Date.now() - startedAt;
@@ -2185,6 +2226,10 @@ const webFetchTool = {
2185
2226
  toolFn: async (value) => {
2186
2227
  const params = value;
2187
2228
  Logger.globalInstance.log("🌐 WebFetch Tool: Starting fetch for URL:", params.url);
2229
+ if (context.urlProvenance && !context.urlProvenance.allows(params.url)) {
2230
+ context.logger.warn("WebFetch refused a URL not present in the conversation");
2231
+ throw new ExpectedToolError(URL_NOT_IN_CONVERSATION_MESSAGE);
2232
+ }
2188
2233
  try {
2189
2234
  await context.statusUpdate({}, `Fetching content from ${params.url}...`);
2190
2235
  const result = await firecrawlFetch({ db: context.db }, params.url, { offset: params.offset });
@@ -2241,6 +2286,14 @@ const webFetchTool = {
2241
2286
  await context.statusUpdate({}, "WebFetch: unsupported file type");
2242
2287
  return WEB_FETCH_UNSUPPORTED_FILE_TYPE_MSG;
2243
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
+ }
2244
2297
  if (error instanceof UnreachableScrapeTargetError) {
2245
2298
  context.logger.warn("WebFetch page unreachable", {
2246
2299
  url: params.url,
@@ -2368,7 +2421,7 @@ const WEB_SEARCH_MAP_PROMPT = [
2368
2421
  "explanation or citations. Omit it only if none of the places actually answer the question."
2369
2422
  ].join("\n");
2370
2423
  //#endregion
2371
- //#region ../../b4m-core/services/dist/websearch-Bm2eZQma.mjs
2424
+ //#region ../../b4m-core/services/dist/websearch-Cce90Bvo.mjs
2372
2425
  /**
2373
2426
  * Shown to the model under tool results that carry the turn's shared numbers, so it cites them the
2374
2427
  * way forced retrieval's header asks it to cite the documents numbered before them. Keep it a directive:
@@ -2718,6 +2771,7 @@ async function serpApiSearch(adapters, query, num_results, options) {
2718
2771
  setSerpApiGeoTargeting(searchParams, options);
2719
2772
  const bucket = recencyBucket(options?.recencyDays);
2720
2773
  if (bucket) searchParams.set("tbs", SERPAPI_QDR[bucket]);
2774
+ if (options?.pageOffset && options.pageOffset > 0) searchParams.set("start", String(options.pageOffset));
2721
2775
  url.search = searchParams.toString();
2722
2776
  const maxAttempts = Math.min(Math.max(1, options?.maxAttempts ?? SERPAPI_MAX_ATTEMPTS), SERPAPI_MAX_ATTEMPTS);
2723
2777
  const failures = [];
@@ -3010,10 +3064,13 @@ function createSearxngProvider(baseUrl) {
3010
3064
  });
3011
3065
  const bucket = recencyBucket(options?.recencyDays);
3012
3066
  if (bucket) params.set("time_range", bucket);
3067
+ const pageno = options?.pageIndex && options.pageIndex > 1 ? options.pageIndex : 1;
3068
+ if (pageno > 1) params.set("pageno", String(pageno));
3013
3069
  url.search = params.toString();
3014
3070
  const request = {
3015
3071
  q: query,
3016
3072
  ...bucket && { time_range: bucket },
3073
+ ...pageno > 1 && { pageno },
3017
3074
  limit
3018
3075
  };
3019
3076
  const controller = new AbortController();
@@ -3470,6 +3527,288 @@ const weatherTool = {
3470
3527
  })
3471
3528
  };
3472
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
3473
3812
  //#region ../../b4m-core/utils/dist/globMatches.mjs
3474
3813
  /**
3475
3814
  * Backtrack-free glob match where `*` is the only wildcard and every other character is a
@@ -3695,7 +4034,7 @@ async function isOperationalBillingEnabled(db, logger, holder) {
3695
4034
  return holder ? isFreeTierHolder(holder) : false;
3696
4035
  }
3697
4036
  //#endregion
3698
- //#region ../../b4m-core/services/dist/toolGenerators-CkAakXQw.mjs
4037
+ //#region ../../b4m-core/services/dist/toolGenerators-ZXY0wEjP.mjs
3699
4038
  const diceRoll = async (parameters) => {
3700
4039
  if (!parameters?.sides || !parameters?.times) throw new Error("Tool dice roll: Missing required parameters");
3701
4040
  return sum(times(parameters.times, () => random(1, parameters.sides))).toString();
@@ -3724,16 +4063,29 @@ const diceRollTool = {
3724
4063
  }
3725
4064
  })
3726
4065
  };
3727
- let mathInstance = null;
3728
- function loadMath() {
3729
- 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, {
3730
4084
  number: "BigNumber",
3731
4085
  precision: 14
3732
- })).catch((error) => {
3733
- mathInstance = null;
3734
- throw error;
3735
4086
  });
3736
- return mathInstance;
4087
+ math.import(Object.fromEntries(DISABLED_FUNCTIONS.map((name) => [name, disabledFunction(name)])), { override: true });
4088
+ return math;
3737
4089
  }
3738
4090
  /**
3739
4091
  * Format a scalar result. Integers render in full via fixed notation so large
@@ -3768,7 +4120,7 @@ function evaluateInput(evaluate) {
3768
4120
  }
3769
4121
  async function evaluateMath(params) {
3770
4122
  Logger.globalInstance.log("🔢 Math Tool: Starting evaluation of expression:", params.expression);
3771
- const math = await loadMath();
4123
+ const math = await createIsolatedMath();
3772
4124
  try {
3773
4125
  let expression = params.expression.trim();
3774
4126
  expression = expression.replace(/\/\*[\s\S]*?\*\//g, "");
@@ -3853,6 +4205,11 @@ async function evaluateMath(params) {
3853
4205
  if (error instanceof MathEvaluationError) throw error;
3854
4206
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
3855
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
+ }
3856
4213
  const undefinedSymbol = errorMessage.match(/Undefined symbol (\w+)/);
3857
4214
  if (undefinedSymbol) {
3858
4215
  const symbol = undefinedSymbol[1];
@@ -4561,7 +4918,7 @@ const askUserQuestionTool = {
4561
4918
  * re-export them without pulling the full tool graph. `index.ts` re-exports them
4562
4919
  * so the server barrel's public API is unchanged.
4563
4920
  */
4564
- const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFilter, kbScope, inlinedAttachmentIds, attachedFileIds, fullyInlinedAttachmentIds, suppressLakeArms, sessionRetrievalTags, sessionReaderConsentDatalakeTags, sessionLakeScopeExplicit, sessionIncludeLibraryFiles, sessionPreauthorizedLakeIds, organizationId, governingOrgModelPolicy, authOrigin, apiKeyId, questId, requestConfirmation, 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) => {
4565
4922
  assertAuthOriginMatchesApiKey(authOrigin, apiKeyId);
4566
4923
  const context = {
4567
4924
  userId,
@@ -4569,6 +4926,7 @@ const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFil
4569
4926
  sessionId,
4570
4927
  questId,
4571
4928
  requestConfirmation,
4929
+ urlProvenance,
4572
4930
  slackDestination,
4573
4931
  logger,
4574
4932
  db,
@@ -4594,6 +4952,7 @@ const generateTools = (userId, user, logger, { db, getEntitlements, retrievalFil
4594
4952
  sessionLakeScopeExplicit,
4595
4953
  sessionIncludeLibraryFiles,
4596
4954
  sessionPreauthorizedLakeIds,
4955
+ followedLakeIds,
4597
4956
  organizationId,
4598
4957
  governingOrgModelPolicy,
4599
4958
  authOrigin,
@@ -20136,8 +20495,8 @@ async function buildSandbox(input) {
20136
20495
  const { config, sessionId, permissionManager, checkpointStore } = input;
20137
20496
  const log = input.log ?? consoleLog;
20138
20497
  const [{ createSandboxRuntime }, { SandboxOrchestrator }, { DEFAULT_SANDBOX_CONFIG }, { ProxyManager }, { ViolationLogStore }] = await Promise.all([
20139
- import("./SandboxRuntimeAdapter-BjJwJNfg.mjs"),
20140
- import("./SandboxOrchestrator-yORi2eFV.mjs"),
20498
+ import("./SandboxRuntimeAdapter-DdF8pI-i.mjs"),
20499
+ import("./SandboxOrchestrator-B-6_ssTd.mjs"),
20141
20500
  import("./types-BFIvwByC.mjs"),
20142
20501
  import("./ProxyManager-TxEKlgdO.mjs"),
20143
20502
  import("./ViolationLogStore-byEhxa2A.mjs")
@@ -20475,6 +20834,8 @@ var MCPClient = class {
20475
20834
  disconnected = false;
20476
20835
  connectionVersion = 0;
20477
20836
  tools = [];
20837
+ /** What each tool's server says about it (MCP tool annotations), by tool name; see McpToolHints. */
20838
+ toolHints = /* @__PURE__ */ new Map();
20478
20839
  serverName;
20479
20840
  constructor({ envVariables, name, command, args, suppressStderr = false, onStderrLine, url, headers }) {
20480
20841
  this.mcp = createSdkClient();
@@ -20552,6 +20913,7 @@ var MCPClient = class {
20552
20913
  input_schema: tool.inputSchema
20553
20914
  };
20554
20915
  });
20916
+ this.toolHints = hintsByTool(toolsResult.tools);
20555
20917
  } catch (e) {
20556
20918
  if (this.transport) {
20557
20919
  try {
@@ -20588,6 +20950,7 @@ var MCPClient = class {
20588
20950
  description: tool.description,
20589
20951
  input_schema: tool.inputSchema
20590
20952
  }));
20953
+ this.toolHints = hintsByTool(toolsResult.tools);
20591
20954
  }
20592
20955
  /**
20593
20956
  * Replace an expired HTTP session with a new one: a fresh SDK client and transport, re-initialized,
@@ -20740,6 +21103,25 @@ var MCPClient = class {
20740
21103
  }
20741
21104
  }
20742
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
+ }
20743
21125
  //#endregion
20744
21126
  //#region src/utils/mcpAdapter.ts
20745
21127
  const CACHE_VERSION = 1;
@@ -21067,7 +21449,7 @@ const MODEL_ALIASES = {
21067
21449
  "claude-4.7-opus": ChatModels.CLAUDE_4_7_OPUS,
21068
21450
  "claude-4.6-opus": ChatModels.CLAUDE_4_6_OPUS,
21069
21451
  "claude-4.6-sonnet": ChatModels.CLAUDE_4_6_SONNET,
21070
- "claude-4.5-opus": ChatModels.CLAUDE_4_5_OPUS,
21452
+ "claude-4.5-opus": ChatModels.CLAUDE_4_8_OPUS,
21071
21453
  "claude-4.5-sonnet": ChatModels.CLAUDE_5_5_SONNET,
21072
21454
  "claude-4.5-haiku": ChatModels.CLAUDE_4_5_HAIKU,
21073
21455
  "claude-4-opus": ChatModels.CLAUDE_4_8_OPUS,
@@ -21077,13 +21459,8 @@ const MODEL_ALIASES = {
21077
21459
  "claude-3.5-sonnet": ChatModels.CLAUDE_5_5_SONNET,
21078
21460
  "claude-3.5-haiku": ChatModels.CLAUDE_4_5_HAIKU,
21079
21461
  "claude-3-opus": ChatModels.CLAUDE_4_8_OPUS,
21080
- "gpt-4o": ChatModels.GPT4o,
21081
- "gpt-4o-mini": ChatModels.GPT4o_MINI,
21082
21462
  "gpt-4.1": ChatModels.GPT4_1,
21083
21463
  "gpt-4.1-mini": ChatModels.GPT4_1_MINI,
21084
- "gpt-5": ChatModels.GPT5,
21085
- "gpt-5-mini": ChatModels.GPT5_MINI,
21086
- "gpt-5-nano": ChatModels.GPT5_NANO,
21087
21464
  "gpt-5.1": ChatModels.GPT5_1,
21088
21465
  "gpt-5.2": ChatModels.GPT5_2,
21089
21466
  "gpt-5.4": ChatModels.GPT5_4,
@@ -21093,6 +21470,10 @@ const MODEL_ALIASES = {
21093
21470
  "gpt-5.6-sol": ChatModels.GPT5_6_SOL,
21094
21471
  "gpt-5.6-luna": ChatModels.GPT5_6_LUNA,
21095
21472
  "gpt-5.6-terra": ChatModels.GPT5_6_TERRA,
21473
+ "gpt-6.2-astra": ChatModels.GPT6_2_ASTRA,
21474
+ "gpt-6.2-sol": ChatModels.GPT6_2_SOL,
21475
+ "gpt-6.1-terra": ChatModels.GPT6_1_TERRA,
21476
+ "gpt-6-luna": ChatModels.GPT6_LUNA,
21096
21477
  gemini: ChatModels.GEMINI_3_5_FLASH,
21097
21478
  "gemini-pro": ChatModels.GEMINI_3_1_PRO_PREVIEW,
21098
21479
  "gemini-flash": ChatModels.GEMINI_3_5_FLASH,
@@ -21106,8 +21487,8 @@ const MODEL_ALIASES = {
21106
21487
  grok: ChatModels.GROK_4_5,
21107
21488
  "grok-3": ChatModels.GROK_4_5,
21108
21489
  "grok-3-fast": ChatModels.GROK_4_5,
21109
- "grok-3-mini": ChatModels.GROK_3_MINI,
21110
- "grok-3-mini-fast": ChatModels.GROK_3_MINI,
21490
+ "grok-3-mini": ChatModels.GROK_4_5,
21491
+ "grok-3-mini-fast": ChatModels.GROK_4_5,
21111
21492
  "grok-2": ChatModels.GROK_4_5,
21112
21493
  "grok-2-vision": ChatModels.GROK_4_5,
21113
21494
  deepseek: ChatModels.DEEPSEEK_FLASH,
@@ -21138,17 +21519,42 @@ const SUNSETTING_MODEL_ALIASES = {
21138
21519
  "gpt-4.1-nano": {
21139
21520
  model: ChatModels.GPT4_1_NANO,
21140
21521
  retiresOn: "2026-10-23",
21141
- successor: "gpt-5-nano"
21522
+ successor: "gpt-6-luna"
21142
21523
  },
21143
21524
  "o4-mini": {
21144
21525
  model: ChatModels.O4_MINI,
21145
21526
  retiresOn: "2026-10-23",
21146
- successor: "gpt-5-mini"
21527
+ successor: "gpt-6-luna"
21147
21528
  },
21148
21529
  o3: {
21149
21530
  model: ChatModels.O3,
21150
21531
  retiresOn: "2026-12-11",
21151
21532
  successor: "gpt-5.5"
21533
+ },
21534
+ "gpt-5": {
21535
+ model: ChatModels.GPT5,
21536
+ retiresOn: "2026-12-11",
21537
+ successor: "gpt-6.2-sol"
21538
+ },
21539
+ "gpt-5-mini": {
21540
+ model: ChatModels.GPT5_MINI,
21541
+ retiresOn: "2026-12-11",
21542
+ successor: "gpt-6-luna"
21543
+ },
21544
+ "gpt-5-nano": {
21545
+ model: ChatModels.GPT5_NANO,
21546
+ retiresOn: "2026-12-11",
21547
+ successor: "gpt-6-luna"
21548
+ },
21549
+ "gpt-4o": {
21550
+ model: ChatModels.GPT4o,
21551
+ retiresOn: "2027-01-14",
21552
+ successor: "gpt-6-luna"
21553
+ },
21554
+ "gpt-4o-mini": {
21555
+ model: ChatModels.GPT4o_MINI,
21556
+ retiresOn: "2027-01-14",
21557
+ successor: "gpt-6-luna"
21152
21558
  }
21153
21559
  };
21154
21560
  /**
@@ -21160,8 +21566,8 @@ const RETIRED_MODEL_ALIASES = {
21160
21566
  "gpt-4.5": "gpt-5.5",
21161
21567
  o1: "gpt-5.5",
21162
21568
  "o1-preview": "gpt-5.5",
21163
- "o1-mini": "gpt-5-mini",
21164
- "o3-mini": "gpt-5-mini",
21569
+ "o1-mini": "gpt-6-luna",
21570
+ "o3-mini": "gpt-6-luna",
21165
21571
  "gemini-2.0-flash": "gemini-flash",
21166
21572
  "gemini-1.5-pro": "gemini-pro",
21167
21573
  "gemini-1.5-flash": "gemini-flash",