@bike4mind/cli 4.9.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AgentHistoryStore-jktM0SmD.mjs → AgentHistoryStore-C3hJOgpM.mjs} +374 -676
- package/dist/{ApiClient-CczpydlW.mjs → ApiClient-CeuIcSY8.mjs} +3 -3
- package/dist/{BubblewrapRuntime-aGfDSJPY.mjs → BubblewrapRuntime-BF5wXaNS.mjs} +2 -2
- package/dist/ConfigStore--dPqdX3O.mjs +2 -0
- package/dist/{ConfigStore-CO6kREaL.mjs → ConfigStore-nr0ebq4v.mjs} +6 -7
- package/dist/{Logger-CHKCF5hd.mjs → Logger-CovZt7LL.mjs} +2159 -1032
- package/dist/{RemoteSkillSource-D_F99yBR.mjs → RemoteSkillSource-HqoLRV56.mjs} +2 -6
- package/dist/{SandboxOrchestrator-ULWvuUct.mjs → SandboxOrchestrator-DTz_5Zub.mjs} +1 -1
- package/dist/{SandboxRuntimeAdapter-DpDSET-A.mjs → SandboxRuntimeAdapter-CC5KlbZ8.mjs} +2 -2
- package/dist/{SandboxRuntimeAdapter-FpZRkE6D.mjs → SandboxRuntimeAdapter-X0HAkbpW.mjs} +1 -1
- package/dist/{SeatbeltRuntime-C0GJ3nnY.mjs → SeatbeltRuntime-zdxVqGZ3.mjs} +2 -2
- package/dist/{WorkItemsClient-aCxMV_Wm.mjs → WorkItemsClient-lKJCPP0j.mjs} +3 -4
- package/dist/{buildToolSearch-CbLeZ5wP.mjs → buildToolSearch-BlOSK4m3.mjs} +2 -2
- package/dist/commands/acpCommand.mjs +7 -8
- package/dist/commands/apiCommand.mjs +1 -1
- package/dist/commands/doctorCommand.mjs +2 -2
- package/dist/commands/envCommand.mjs +1 -1
- package/dist/commands/headlessCommand.mjs +11 -12
- package/dist/commands/mcpCommand.mjs +3 -3
- package/dist/commands/mirrorCommand.mjs +2 -2
- package/dist/commands/modelsCommand.mjs +4 -4
- package/dist/commands/pluginCommand.mjs +1 -1
- package/dist/commands/skillsCommand.mjs +4 -4
- package/dist/commands/updateCommand.mjs +2 -2
- package/dist/{dist-BOxr8LQA.mjs → dist-BrBjZ6Cv.mjs} +5442 -186
- package/dist/{fit-BHDTSpfd.mjs → fit-vnmP4Dfc.mjs} +3 -3
- package/dist/index.mjs +455 -455
- package/dist/{modelServers-CVufZd1f.mjs → modelServers-CjSlPFsg.mjs} +1 -1
- package/dist/{package-TACInPbw.mjs → package-BTvxFRbB.mjs} +1 -1
- package/dist/{serve-OywSzShu.mjs → serve-BLBhPkyw.mjs} +301 -155
- package/dist/{updateChecker-5v_8LhXy.mjs → updateChecker-uDIZuEZg.mjs} +1 -1
- package/package.json +10 -43
- package/dist/ConfigStore-BAJ4hIHa.mjs +0 -2
|
@@ -1,25 +1,24 @@
|
|
|
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-
|
|
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-
|
|
4
|
-
import { At as
|
|
5
|
-
import {
|
|
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-nr0ebq4v.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-BrBjZ6Cv.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-CovZt7LL.mjs";
|
|
5
|
+
import { r as isReservedCommandName } from "./RemoteSkillSource-HqoLRV56.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-
|
|
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-CjSlPFsg.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";
|
|
18
17
|
import ignore from "ignore";
|
|
19
18
|
import fs, { mkdir, readFile, stat, writeFile } from "fs/promises";
|
|
20
19
|
import { z as z$1 } from "zod";
|
|
20
|
+
import YAML from "yaml";
|
|
21
21
|
import { isAxiosError } from "axios";
|
|
22
|
-
import Fuse from "fuse.js";
|
|
23
22
|
import { execFile, spawn } from "child_process";
|
|
24
23
|
import { promisify } from "util";
|
|
25
24
|
import * as fsp from "node:fs/promises";
|
|
@@ -29,13 +28,11 @@ import * as turndownPluginGfm from "@joplin/turndown-plugin-gfm";
|
|
|
29
28
|
import * as cheerio from "cheerio";
|
|
30
29
|
import FirecrawlDefault, { FirecrawlError } from "@mendable/firecrawl-js";
|
|
31
30
|
import { lookup } from "node:dns/promises";
|
|
32
|
-
import "@aws-sdk/client-cloudwatch";
|
|
33
31
|
import random from "lodash/random.js";
|
|
34
32
|
import sum from "lodash/sum.js";
|
|
35
33
|
import times from "lodash/times.js";
|
|
36
34
|
import * as Diff from "diff";
|
|
37
35
|
import { diffLines } from "diff";
|
|
38
|
-
import matter from "gray-matter";
|
|
39
36
|
import { parse as parse$1 } from "shell-quote";
|
|
40
37
|
import { EventEmitter } from "events";
|
|
41
38
|
import { fileURLToPath } from "url";
|
|
@@ -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}.${
|
|
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:
|
|
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:
|
|
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.
|
|
@@ -3712,18 +3623,79 @@ async function getModel(user, modelId, deps) {
|
|
|
3712
3623
|
* `searchModels`, `hydrateModel` (computes derived values and stamps `lastComputedAt`), and
|
|
3713
3624
|
* `duplicateModel` (reads one model and creates a NEW one owned by the caller).
|
|
3714
3625
|
*
|
|
3715
|
-
* Lattice models carry no share/grant field, so the creator is the only principal that can hold
|
|
3716
|
-
* write authority today. If an explicit write grant is ever added, this is the one place to admit
|
|
3717
|
-
* it - keeping the check here rather than inlined in six mutators is what makes that a one-line
|
|
3718
|
-
* change instead of a six-site audit.
|
|
3626
|
+
* Lattice models carry no share/grant field, so the creator is the only principal that can hold
|
|
3627
|
+
* write authority today. If an explicit write grant is ever added, this is the one place to admit
|
|
3628
|
+
* it - keeping the check here rather than inlined in six mutators is what makes that a one-line
|
|
3629
|
+
* change instead of a six-site audit.
|
|
3630
|
+
*/
|
|
3631
|
+
async function getModelForWrite(user, modelId, deps) {
|
|
3632
|
+
const model = await getModel(user, modelId, deps);
|
|
3633
|
+
if (!model) return null;
|
|
3634
|
+
return isModelOwner(model, user) ? model : null;
|
|
3635
|
+
}
|
|
3636
|
+
//#endregion
|
|
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.
|
|
3719
3686
|
*/
|
|
3720
|
-
async function
|
|
3721
|
-
const
|
|
3722
|
-
|
|
3723
|
-
|
|
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;
|
|
3724
3696
|
}
|
|
3725
3697
|
//#endregion
|
|
3726
|
-
//#region ../../b4m-core/services/dist/toolGenerators-
|
|
3698
|
+
//#region ../../b4m-core/services/dist/toolGenerators-CkAakXQw.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();
|
|
@@ -4330,6 +4302,33 @@ const promptEnhancementTool = {
|
|
|
4330
4302
|
}
|
|
4331
4303
|
})
|
|
4332
4304
|
};
|
|
4305
|
+
const OBJECT_ID_HEX = /^[0-9a-fA-F]{24}$/;
|
|
4306
|
+
/**
|
|
4307
|
+
* Is this value shaped like something Mongoose can cast to an `_id`?
|
|
4308
|
+
*
|
|
4309
|
+
* Tool arguments are composed by the model out of conversation text and reach us as unvalidated
|
|
4310
|
+
* JSON, so an id parameter routinely holds something that is not an id at all - a filename token,
|
|
4311
|
+
* an arXiv number, a bare integer. Mongoose casts `_id` and throws a CastError on those, which a
|
|
4312
|
+
* generic catch upstream then reports as an outage rather than the bad argument it is (#2530).
|
|
4313
|
+
* Call this before handing a model-supplied id to `findById` and answer a false the same way the
|
|
4314
|
+
* surface answers a genuinely missing row.
|
|
4315
|
+
*
|
|
4316
|
+
* `isObjectIdOrHexString`, not `isValidObjectId`: the latter also accepts a number and casts it to
|
|
4317
|
+
* a fabricated id, and a model emitting `{"file_id": 12}` gives us exactly that despite the
|
|
4318
|
+
* `string` type. Same choice, same reason, as `usableObjectIds` in @bike4mind/db-core, which is
|
|
4319
|
+
* the array-shaped version of this check.
|
|
4320
|
+
*
|
|
4321
|
+
* NOT usable for artifact ids (`artifact_<...>`), which are matched on a string `id` field rather
|
|
4322
|
+
* than `_id` - see `createArtifactId` in @bike4mind/common.
|
|
4323
|
+
*
|
|
4324
|
+
* A copy of Mongoose's `isObjectIdOrHexString` (an ObjectId instance, recognised by its
|
|
4325
|
+
* `_bsontype` tag, or a 24-hex string) rather than an import of it: this module is reached from
|
|
4326
|
+
* the CLI's tool registry, and importing mongoose there costs every CLI launch ~100-200 ms.
|
|
4327
|
+
*/
|
|
4328
|
+
function isObjectIdShaped$1(id) {
|
|
4329
|
+
if (typeof id === "string") return OBJECT_ID_HEX.test(id);
|
|
4330
|
+
return typeof id === "object" && id !== null && id._bsontype === "ObjectId";
|
|
4331
|
+
}
|
|
4333
4332
|
const DecisionToolRequestSchema = DecisionsRequestSchema.pick({
|
|
4334
4333
|
input: true,
|
|
4335
4334
|
questions: true,
|
|
@@ -4775,35 +4774,6 @@ const generateMcpToolsFromCache = (serverName, cachedTools, callTool) => {
|
|
|
4775
4774
|
return result;
|
|
4776
4775
|
};
|
|
4777
4776
|
//#endregion
|
|
4778
|
-
//#region ../../b4m-core/services/dist/objectId-Bhav0W6F.mjs
|
|
4779
|
-
const OBJECT_ID_HEX = /^[0-9a-fA-F]{24}$/;
|
|
4780
|
-
/**
|
|
4781
|
-
* Is this value shaped like something Mongoose can cast to an `_id`?
|
|
4782
|
-
*
|
|
4783
|
-
* Tool arguments are composed by the model out of conversation text and reach us as unvalidated
|
|
4784
|
-
* JSON, so an id parameter routinely holds something that is not an id at all - a filename token,
|
|
4785
|
-
* an arXiv number, a bare integer. Mongoose casts `_id` and throws a CastError on those, which a
|
|
4786
|
-
* generic catch upstream then reports as an outage rather than the bad argument it is (#2530).
|
|
4787
|
-
* Call this before handing a model-supplied id to `findById` and answer a false the same way the
|
|
4788
|
-
* surface answers a genuinely missing row.
|
|
4789
|
-
*
|
|
4790
|
-
* `isObjectIdOrHexString`, not `isValidObjectId`: the latter also accepts a number and casts it to
|
|
4791
|
-
* a fabricated id, and a model emitting `{"file_id": 12}` gives us exactly that despite the
|
|
4792
|
-
* `string` type. Same choice, same reason, as `usableObjectIds` in @bike4mind/db-core, which is
|
|
4793
|
-
* the array-shaped version of this check.
|
|
4794
|
-
*
|
|
4795
|
-
* NOT usable for artifact ids (`artifact_<...>`), which are matched on a string `id` field rather
|
|
4796
|
-
* than `_id` - see `createArtifactId` in @bike4mind/common.
|
|
4797
|
-
*
|
|
4798
|
-
* A copy of Mongoose's `isObjectIdOrHexString` (an ObjectId instance, recognised by its
|
|
4799
|
-
* `_bsontype` tag, or a 24-hex string) rather than an import of it: this module is reached from
|
|
4800
|
-
* the CLI's tool registry, and importing mongoose there costs every CLI launch ~100-200 ms.
|
|
4801
|
-
*/
|
|
4802
|
-
function isObjectIdShaped(id) {
|
|
4803
|
-
if (typeof id === "string") return OBJECT_ID_HEX.test(id);
|
|
4804
|
-
return typeof id === "object" && id !== null && id._bsontype === "ObjectId";
|
|
4805
|
-
}
|
|
4806
|
-
//#endregion
|
|
4807
4777
|
//#region ../../b4m-core/services/dist/llm/tools/cliTools.mjs
|
|
4808
4778
|
/**
|
|
4809
4779
|
* Validated fuzzy fallback for `edit_local_file` string matching.
|
|
@@ -6221,7 +6191,7 @@ const latticeAddEntityTool = {
|
|
|
6221
6191
|
createdAt: /* @__PURE__ */ new Date(),
|
|
6222
6192
|
updatedAt: /* @__PURE__ */ new Date()
|
|
6223
6193
|
};
|
|
6224
|
-
if (context.db.latticeModels && modelId && isObjectIdShaped(modelId)) try {
|
|
6194
|
+
if (context.db.latticeModels && modelId && isObjectIdShaped$1(modelId)) try {
|
|
6225
6195
|
const model = await getModelForWrite({
|
|
6226
6196
|
id: context.userId,
|
|
6227
6197
|
organizationId: context.user?.organizationId
|
|
@@ -6366,7 +6336,7 @@ const latticeSetValueTool = {
|
|
|
6366
6336
|
else if (rawValue.toLowerCase() === "true") value = true;
|
|
6367
6337
|
else if (rawValue.toLowerCase() === "false") value = false;
|
|
6368
6338
|
const entityId = toEntityId(entityName);
|
|
6369
|
-
if (context.db.latticeModels && modelId && isObjectIdShaped(modelId)) try {
|
|
6339
|
+
if (context.db.latticeModels && modelId && isObjectIdShaped$1(modelId)) try {
|
|
6370
6340
|
const model = await getModelForWrite({
|
|
6371
6341
|
id: context.userId,
|
|
6372
6342
|
organizationId: context.user?.organizationId
|
|
@@ -6512,7 +6482,7 @@ const latticeCreateRuleTool = {
|
|
|
6512
6482
|
};
|
|
6513
6483
|
const outputEntityId = parsedRule.outputEntity.toLowerCase().replace(/\s+/g, "_");
|
|
6514
6484
|
let entityCreatedMessage = "";
|
|
6515
|
-
if (context.db.latticeModels && modelId && isObjectIdShaped(modelId)) try {
|
|
6485
|
+
if (context.db.latticeModels && modelId && isObjectIdShaped$1(modelId)) try {
|
|
6516
6486
|
const model = await getModelForWrite({
|
|
6517
6487
|
id: context.userId,
|
|
6518
6488
|
organizationId: context.user?.organizationId
|
|
@@ -7054,54 +7024,119 @@ async function processFileReferences(message, confineTo) {
|
|
|
7054
7024
|
};
|
|
7055
7025
|
}
|
|
7056
7026
|
//#endregion
|
|
7057
|
-
//#region
|
|
7027
|
+
//#region ../../b4m-core/common/dist/utils/frontmatter.mjs
|
|
7058
7028
|
/**
|
|
7059
|
-
*
|
|
7060
|
-
*
|
|
7061
|
-
*
|
|
7062
|
-
*
|
|
7063
|
-
|
|
7064
|
-
|
|
7065
|
-
|
|
7066
|
-
|
|
7067
|
-
|
|
7068
|
-
|
|
7069
|
-
|
|
7070
|
-
|
|
7071
|
-
|
|
7029
|
+
* YAML front matter for markdown files: CLI skills, commands and agents, and the help articles.
|
|
7030
|
+
* Splits the file the way gray-matter did, which those files were written against, and parses
|
|
7031
|
+
* with the eemeli `yaml` package, which has no eval-capable engines. Sits behind
|
|
7032
|
+
* `@bike4mind/common/utils/frontmatter` so the barrel does not pull in a YAML parser.
|
|
7033
|
+
*/
|
|
7034
|
+
var FrontmatterLanguageError = class extends Error {
|
|
7035
|
+
lang;
|
|
7036
|
+
constructor(lang) {
|
|
7037
|
+
super(`Unsupported front matter language "${lang}"; only YAML is supported.`);
|
|
7038
|
+
this.name = "FrontmatterLanguageError";
|
|
7039
|
+
this.lang = lang;
|
|
7040
|
+
}
|
|
7041
|
+
};
|
|
7042
|
+
const OPEN$1 = "---";
|
|
7043
|
+
const CLOSE$1 = "\n---";
|
|
7044
|
+
const INTEGER_PATTERN = /^[-+]?(?:0|0b[01_]*[01]|0x[\da-fA-F_]*[\da-fA-F]|0[0-7_]*[0-7]|[1-9](?:[\d_]*\d)?|[1-9][\d_]*(?::[0-5]?\d)+)$/;
|
|
7045
|
+
const FLOAT_PATTERN = /^(?!.*_$)(?:[-+]?(?:0|[1-9][\d_]*)(?:\.[\d_]*)?(?:[eE][-+]?\d+)?|\.[\d_]+(?:[eE][-+]?\d+)?|[-+]?\d[\d_]*(?::[0-5]?\d)+\.[\d_]*|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$/;
|
|
7046
|
+
function parseSafeNumber(source, integer) {
|
|
7047
|
+
const normalized = source.replaceAll("_", "").toLowerCase();
|
|
7048
|
+
const sign = normalized.startsWith("-") ? -1 : 1;
|
|
7049
|
+
const value = normalized.replace(/^[-+]/, "");
|
|
7050
|
+
if (integer && value === "0") return 0;
|
|
7051
|
+
if (value === ".inf") return sign * Infinity;
|
|
7052
|
+
if (value === ".nan") return NaN;
|
|
7053
|
+
if (value.includes(":")) {
|
|
7054
|
+
const parts = value.split(":");
|
|
7055
|
+
return sign * parts.reduceRight((total, part, index) => total + Number(part) * 60 ** (parts.length - index - 1), 0);
|
|
7056
|
+
}
|
|
7057
|
+
if (!integer) return sign * Number.parseFloat(value);
|
|
7058
|
+
if (value.startsWith("0b")) return sign * Number.parseInt(value.slice(2), 2);
|
|
7059
|
+
if (value.startsWith("0x")) return sign * Number.parseInt(value.slice(2), 16);
|
|
7060
|
+
return sign * Number.parseInt(value, value.startsWith("0") ? 8 : 10);
|
|
7061
|
+
}
|
|
7062
|
+
const safeIntegerTag = {
|
|
7063
|
+
tag: "tag:yaml.org,2002:int",
|
|
7064
|
+
default: true,
|
|
7065
|
+
test: INTEGER_PATTERN,
|
|
7066
|
+
resolve: (source) => parseSafeNumber(source, true)
|
|
7067
|
+
};
|
|
7068
|
+
const safeFloatTag = {
|
|
7069
|
+
tag: "tag:yaml.org,2002:float",
|
|
7070
|
+
default: true,
|
|
7071
|
+
test: FLOAT_PATTERN,
|
|
7072
|
+
resolve: (source) => parseSafeNumber(source, false)
|
|
7073
|
+
};
|
|
7074
|
+
/**
|
|
7075
|
+
* Splits a leading `---` fence off `text` and parses it as YAML. A file that does not open with
|
|
7076
|
+
* `---` has no front matter; a fence that is never closed makes the rest of the file front matter.
|
|
7077
|
+
* Throws FrontmatterLanguageError for a language tag other than yaml/yml on the opening fence, and
|
|
7078
|
+
* an Error for invalid YAML or front matter that is not a set of key: value pairs.
|
|
7072
7079
|
*/
|
|
7073
|
-
|
|
7074
|
-
|
|
7075
|
-
|
|
7076
|
-
|
|
7080
|
+
function parseFrontmatter$1(text) {
|
|
7081
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
7082
|
+
if (!text.startsWith(OPEN$1) || text.charAt(3) === "-") return {
|
|
7083
|
+
data: {},
|
|
7084
|
+
content: text
|
|
7085
|
+
};
|
|
7086
|
+
let rest = text.slice(3);
|
|
7087
|
+
const eol = rest.search(/\r?\n/);
|
|
7088
|
+
const lang = (eol === -1 ? rest : rest.slice(0, eol)).trim().toLowerCase();
|
|
7089
|
+
if (lang && lang !== "yaml" && lang !== "yml") throw new FrontmatterLanguageError(lang);
|
|
7090
|
+
rest = eol === -1 ? "" : rest.slice(eol);
|
|
7091
|
+
const close = rest.indexOf(CLOSE$1);
|
|
7092
|
+
const block = close === -1 ? rest : rest.slice(0, close).replace(/\r$/, "");
|
|
7093
|
+
let content = close === -1 ? "" : rest.slice(close + 4);
|
|
7094
|
+
if (content.startsWith("\r")) content = content.slice(1);
|
|
7095
|
+
if (content.startsWith("\n")) content = content.slice(1);
|
|
7096
|
+
if (block.replace(/^\s*#[^\n]+/gm, "").trim() === "") return {
|
|
7097
|
+
data: {},
|
|
7098
|
+
content
|
|
7099
|
+
};
|
|
7100
|
+
const document = YAML.parseDocument(block, {
|
|
7101
|
+
schema: "core",
|
|
7102
|
+
customTags: (tags) => [
|
|
7103
|
+
...tags.filter((tag) => typeof tag === "string" || !["tag:yaml.org,2002:int", "tag:yaml.org,2002:float"].includes(tag.tag)),
|
|
7104
|
+
safeIntegerTag,
|
|
7105
|
+
safeFloatTag,
|
|
7106
|
+
"timestamp"
|
|
7107
|
+
],
|
|
7108
|
+
merge: true,
|
|
7109
|
+
logLevel: "error"
|
|
7110
|
+
});
|
|
7111
|
+
const parseError = document.errors[0] ?? document.warnings.find((warning) => warning.code === "TAG_RESOLVE_FAILED");
|
|
7112
|
+
if (parseError) throw parseError;
|
|
7113
|
+
const data = document.toJS();
|
|
7114
|
+
if (data === null) return {
|
|
7115
|
+
data: {},
|
|
7116
|
+
content
|
|
7117
|
+
};
|
|
7118
|
+
if (Object.prototype.toString.call(data) !== "[object Object]") throw new Error("The front matter must be a set of key: value pairs.");
|
|
7119
|
+
return {
|
|
7120
|
+
data,
|
|
7121
|
+
content
|
|
7122
|
+
};
|
|
7077
7123
|
}
|
|
7124
|
+
//#endregion
|
|
7125
|
+
//#region src/utils/parseFrontmatter.ts
|
|
7126
|
+
/**
|
|
7127
|
+
* Frontmatter for SKILL.md, command and agent files, which are untrusted input. Only YAML is read:
|
|
7128
|
+
* a `---js`-style fence is never evaluated, and it, like malformed YAML, degrades to empty
|
|
7129
|
+
* frontmatter with a warning rather than throwing.
|
|
7130
|
+
*/
|
|
7078
7131
|
function parseFrontmatter(content) {
|
|
7079
|
-
if (content.charCodeAt(0) === 65279) content = content.slice(1);
|
|
7080
|
-
const fence = content.match(OPENING_FENCE);
|
|
7081
|
-
if (fence) {
|
|
7082
|
-
const lang = fence[1].trim().toLowerCase();
|
|
7083
|
-
if (lang && lang !== "yaml" && lang !== "yml") {
|
|
7084
|
-
logger.warn(`Ignoring non-YAML frontmatter language "${lang}"; treating frontmatter as empty`);
|
|
7085
|
-
return {
|
|
7086
|
-
data: {},
|
|
7087
|
-
content
|
|
7088
|
-
};
|
|
7089
|
-
}
|
|
7090
|
-
}
|
|
7091
7132
|
try {
|
|
7092
|
-
|
|
7093
|
-
javascript: nonYamlEngineDisabled,
|
|
7094
|
-
coffee: nonYamlEngineDisabled
|
|
7095
|
-
} });
|
|
7096
|
-
return {
|
|
7097
|
-
data: parsed.data,
|
|
7098
|
-
content: parsed.content
|
|
7099
|
-
};
|
|
7133
|
+
return parseFrontmatter$1(content);
|
|
7100
7134
|
} catch (error) {
|
|
7101
|
-
logger.warn(`
|
|
7135
|
+
if (error instanceof FrontmatterLanguageError) logger.warn(`Ignoring non-YAML frontmatter language "${error.lang}"; treating frontmatter as empty`);
|
|
7136
|
+
else logger.warn(`Failed to parse frontmatter: ${error instanceof Error ? error.message : String(error)}`);
|
|
7102
7137
|
return {
|
|
7103
7138
|
data: {},
|
|
7104
|
-
content
|
|
7139
|
+
content: content.charCodeAt(0) === 65279 ? content.slice(1) : content
|
|
7105
7140
|
};
|
|
7106
7141
|
}
|
|
7107
7142
|
}
|
|
@@ -17374,378 +17409,6 @@ function createGetFileStructureTool(allowedDirectories) {
|
|
|
17374
17409
|
};
|
|
17375
17410
|
}
|
|
17376
17411
|
//#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
17412
|
//#region src/utils/StreamLogger.ts
|
|
17750
17413
|
/**
|
|
17751
17414
|
* StreamLogger manages intelligent batching of SSE stream debug logs.
|
|
@@ -20061,8 +19724,8 @@ async function buildSandbox(input) {
|
|
|
20061
19724
|
const { config, sessionId, permissionManager, checkpointStore } = input;
|
|
20062
19725
|
const log = input.log ?? consoleLog;
|
|
20063
19726
|
const [{ createSandboxRuntime }, { SandboxOrchestrator }, { DEFAULT_SANDBOX_CONFIG }, { ProxyManager }, { ViolationLogStore }] = await Promise.all([
|
|
20064
|
-
import("./SandboxRuntimeAdapter-
|
|
20065
|
-
import("./SandboxOrchestrator-
|
|
19727
|
+
import("./SandboxRuntimeAdapter-X0HAkbpW.mjs"),
|
|
19728
|
+
import("./SandboxOrchestrator-DTz_5Zub.mjs"),
|
|
20066
19729
|
import("./types-BFIvwByC.mjs"),
|
|
20067
19730
|
import("./ProxyManager-TxEKlgdO.mjs"),
|
|
20068
19731
|
import("./ViolationLogStore-byEhxa2A.mjs")
|
|
@@ -20351,6 +20014,24 @@ function buildMcpChildEnv({ serverName, envVariables, hasCustomCommand = false }
|
|
|
20351
20014
|
droppedKeys
|
|
20352
20015
|
};
|
|
20353
20016
|
}
|
|
20017
|
+
function emit(level, scope, message, fields) {
|
|
20018
|
+
const redacted = fields ? redactLogValue(fields) : void 0;
|
|
20019
|
+
console[level](`[${scope}] ${redactLogText(message)}`, ...redacted ? [redacted] : []);
|
|
20020
|
+
}
|
|
20021
|
+
/**
|
|
20022
|
+
* Redacting logger for code that runs inside a host process (the CLI's Ink TUI, desktop main, servers),
|
|
20023
|
+
* as opposed to a stdio server. Redaction happens here in `emit`; writing through `console` lets the
|
|
20024
|
+
* host's console patching apply. debug/info are no-ops: host-side callers do not use them.
|
|
20025
|
+
*/
|
|
20026
|
+
function createConsoleLogger(scope) {
|
|
20027
|
+
return {
|
|
20028
|
+
debug: () => {},
|
|
20029
|
+
info: () => {},
|
|
20030
|
+
warn: (message, fields) => emit("warn", scope, message, fields),
|
|
20031
|
+
error: (message, fields) => emit("error", scope, message, fields)
|
|
20032
|
+
};
|
|
20033
|
+
}
|
|
20034
|
+
const log = createConsoleLogger("mcp-client");
|
|
20354
20035
|
const createSdkClient = () => new Client({
|
|
20355
20036
|
name: "mcp-client-cli",
|
|
20356
20037
|
version: "1.0.0"
|
|
@@ -20413,14 +20094,16 @@ var MCPClient = class {
|
|
|
20413
20094
|
const serverScriptPath = path.join(moduleDir, this.serverName, "index.mjs");
|
|
20414
20095
|
if (!existsSync(serverScriptPath)) {
|
|
20415
20096
|
const availableFiles = readdirSync(moduleDir, { withFileTypes: true }).map((d) => d.isDirectory() ? `${d.name}/` : d.name);
|
|
20416
|
-
|
|
20417
|
-
|
|
20418
|
-
|
|
20097
|
+
log.error("server script not found", {
|
|
20098
|
+
server: this.serverName,
|
|
20099
|
+
serverScriptPath,
|
|
20100
|
+
moduleDir,
|
|
20101
|
+
availableFiles
|
|
20102
|
+
});
|
|
20419
20103
|
throw new Error(`MCP Server script not found for ${this.serverName} at ${serverScriptPath}. Module dir: ${moduleDir}`);
|
|
20420
20104
|
}
|
|
20421
20105
|
command = process.execPath;
|
|
20422
20106
|
args = [serverScriptPath];
|
|
20423
|
-
console.log(`[MCP] Using server: ${this.serverName} at ${serverScriptPath}`);
|
|
20424
20107
|
}
|
|
20425
20108
|
const stderrMode = this.suppressStderr ? "ignore" : this.onStderrLine ? "pipe" : void 0;
|
|
20426
20109
|
const { env, droppedKeys } = buildMcpChildEnv({
|
|
@@ -20428,7 +20111,10 @@ var MCPClient = class {
|
|
|
20428
20111
|
envVariables: this.envVariables,
|
|
20429
20112
|
hasCustomCommand: Boolean(customCommand)
|
|
20430
20113
|
});
|
|
20431
|
-
if (droppedKeys.length > 0)
|
|
20114
|
+
if (droppedKeys.length > 0) log.warn("withheld undeclared env variables from server", {
|
|
20115
|
+
server: this.serverName,
|
|
20116
|
+
droppedKeys
|
|
20117
|
+
});
|
|
20432
20118
|
const transportConfig = {
|
|
20433
20119
|
command,
|
|
20434
20120
|
args,
|
|
@@ -20438,7 +20124,10 @@ var MCPClient = class {
|
|
|
20438
20124
|
const stdioTransport = new StdioClientTransport(transportConfig);
|
|
20439
20125
|
this.transport = stdioTransport;
|
|
20440
20126
|
stdioTransport.onerror = (error) => {
|
|
20441
|
-
|
|
20127
|
+
log.error("transport error", {
|
|
20128
|
+
server: this.serverName,
|
|
20129
|
+
error
|
|
20130
|
+
});
|
|
20442
20131
|
};
|
|
20443
20132
|
if (this.onStderrLine && stdioTransport.stderr) this.readStderr(stdioTransport.stderr);
|
|
20444
20133
|
await this.mcp.connect(stdioTransport);
|
|
@@ -20472,7 +20161,10 @@ var MCPClient = class {
|
|
|
20472
20161
|
sessionExpired = true;
|
|
20473
20162
|
return;
|
|
20474
20163
|
}
|
|
20475
|
-
|
|
20164
|
+
log.error("transport error", {
|
|
20165
|
+
server: this.serverName,
|
|
20166
|
+
detail: error.message
|
|
20167
|
+
});
|
|
20476
20168
|
};
|
|
20477
20169
|
this.transport = transport;
|
|
20478
20170
|
await client.connect(transport);
|
|
@@ -20606,7 +20298,10 @@ var MCPClient = class {
|
|
|
20606
20298
|
}
|
|
20607
20299
|
} catch (error) {
|
|
20608
20300
|
if (error instanceof Error && (error.message.includes("Connection closed") || error.message.includes("-32000") || error.message.includes("EPIPE"))) {
|
|
20609
|
-
|
|
20301
|
+
log.error("connection lost while calling tool", {
|
|
20302
|
+
server: this.serverName,
|
|
20303
|
+
toolName
|
|
20304
|
+
});
|
|
20610
20305
|
throw new Error(`MCP connection lost for ${this.serverName}. Please retry the operation.`);
|
|
20611
20306
|
}
|
|
20612
20307
|
throw error;
|
|
@@ -20622,7 +20317,10 @@ var MCPClient = class {
|
|
|
20622
20317
|
if (this.transport) await this.mcp.close();
|
|
20623
20318
|
} catch (error) {
|
|
20624
20319
|
if (!(error instanceof Error && (error.message.includes("Connection closed") || error.message.includes("-32000") || error.message.includes("EPIPE") || error.message.includes("ECONNRESET")))) {
|
|
20625
|
-
|
|
20320
|
+
log.error("error during disconnect", {
|
|
20321
|
+
server: this.serverName,
|
|
20322
|
+
error
|
|
20323
|
+
});
|
|
20626
20324
|
throw error;
|
|
20627
20325
|
}
|
|
20628
20326
|
} finally {
|
|
@@ -22177,4 +21875,4 @@ var AgentHistoryStore = class {
|
|
|
22177
21875
|
}
|
|
22178
21876
|
};
|
|
22179
21877
|
//#endregion
|
|
22180
|
-
export {
|
|
21878
|
+
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 };
|