@bike4mind/cli 4.10.0 → 5.0.1

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 (38) hide show
  1. package/dist/{AgentHistoryStore-CjGVgxLR.mjs → AgentHistoryStore-DW6BBbVj.mjs} +624 -114
  2. package/dist/{ApiClient-SVXSI3HI.mjs → ApiClient-D4bDuWXg.mjs} +3 -3
  3. package/dist/{BubblewrapRuntime-CTc_KPnd.mjs → BubblewrapRuntime-D3EO5Y0C.mjs} +2 -2
  4. package/dist/{ConfigStore-B2Dy-PT9.mjs → ConfigStore-BuLA_-uZ.mjs} +17 -1
  5. package/dist/ConfigStore-DdqxfmDr.mjs +2 -0
  6. package/dist/{Logger-7MmrU5w6.mjs → Logger-CjaYx85U.mjs} +1560 -805
  7. package/dist/{RemoteSkillSource-D_F99yBR.mjs → RemoteSkillSource-HqoLRV56.mjs} +2 -6
  8. package/dist/{SandboxOrchestrator-CeDwd6Fj.mjs → SandboxOrchestrator-yORi2eFV.mjs} +1 -1
  9. package/dist/{SandboxRuntimeAdapter-CFEIywKt.mjs → SandboxRuntimeAdapter-BjJwJNfg.mjs} +1 -1
  10. package/dist/{SandboxRuntimeAdapter-CjNDzYSf.mjs → SandboxRuntimeAdapter-BmkaFzqU.mjs} +2 -2
  11. package/dist/{SeatbeltRuntime-CQItj-F1.mjs → SeatbeltRuntime-CyZNmFwD.mjs} +2 -2
  12. package/dist/{WorkItemsClient-C9_pjHCo.mjs → WorkItemsClient-xmo0DrCm.mjs} +1 -1
  13. package/dist/{buildToolSearch-8xyBwXRx.mjs → buildToolSearch-CXxEtVKc.mjs} +2 -2
  14. package/dist/commands/acpCommand.mjs +6 -6
  15. package/dist/commands/apiCommand.mjs +1 -1
  16. package/dist/commands/doctorCommand.mjs +2 -2
  17. package/dist/commands/envCommand.mjs +1 -1
  18. package/dist/commands/headlessCommand.mjs +7 -7
  19. package/dist/commands/mcpCommand.mjs +3 -3
  20. package/dist/commands/mirrorCommand.mjs +2 -2
  21. package/dist/commands/modelsCommand.mjs +4 -4
  22. package/dist/commands/pluginCommand.mjs +1 -1
  23. package/dist/commands/skillsCommand.mjs +4 -4
  24. package/dist/commands/updateCommand.mjs +2 -2
  25. package/dist/{createFile-B8bur5Rb-CVzCarEA.mjs → createFile-CPKmd6Uf-Bk-3V2T3.mjs} +3 -3
  26. package/dist/{deleteFile-9B3gW_Nb-DG2sovIl.mjs → deleteFile-CD_xQ7Y6-C1X4Ievb.mjs} +17 -4
  27. package/dist/{dist-DHgMhdzV.mjs → dist-DsMzCRLX.mjs} +96 -34
  28. package/dist/{fit-D8Quui6j.mjs → fit-C9eLTDcR.mjs} +3 -3
  29. package/dist/{globFiles-CwJ8qmYo-BR5b2KvO.mjs → globFiles-CoapsO8G-CpvQo-R2.mjs} +9 -5
  30. package/dist/{grepSearch-CLtEqT4j-BnKPtNWr.mjs → grepSearch-DeH7M2e7-BIvo-yNy.mjs} +2 -2
  31. package/dist/index.mjs +12 -417
  32. package/dist/{modelServers-JsKBm7Wn.mjs → modelServers-DeOGFwLi.mjs} +1 -1
  33. package/dist/{package-r_xumsGY.mjs → package-CvffLo0I.mjs} +1 -1
  34. package/dist/{pathValidation-BRqf4HFX-CHwtwp3O.mjs → pathValidation-C4ADzpUR-BPIpINwZ.mjs} +36 -12
  35. package/dist/{serve-BM9PKMLH.mjs → serve-tmC__JNj.mjs} +6 -6
  36. package/dist/{updateChecker-BOqaLeZU.mjs → updateChecker-U4AfrPKj.mjs} +1 -1
  37. package/package.json +10 -11
  38. package/dist/ConfigStore-zlY0PikB.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-B2Dy-PT9.mjs";
3
- import { a as extractErrorMessage, d as BaseStorage, f as isPrivateIP, l as OllamaBackend, n as B4mStreamEndedError, o as getSettingsMap, p as Logger, r as createClient, s as getSettingsValue, t as B4mApiError, u as OpenAICompatibleBackend } from "./dist-DHgMhdzV.mjs";
4
- import { At as isExpectedToolError, B as LOW_CONFIDENCE_COMPLETION_MODES, Et as googleMapsSearchUrl, G as NotFoundError, I as ExpectedToolError, Jt as signImageUrl, Kt as secureParameters, M as DecisionTextPartSchema, Mt as isProviderRefusalStopReason, N as DecisionsRequestSchema, Nt as isRetryableError, T as ChatModels, U as McpServerName, Ut as reasoningChannelOf, V as MODEL_DECLINED_MESSAGE, Y as PermissionDeniedError, Yt as splitEquals, _t as createReasoningWithholder, a as htmlFirstH1, an as withholdsReasoning, at as SEARCH_RESULT_CARDS_LANGUAGE, ft as WORK_ITEM_STATUSES, h as ApiKeyType, i as htmlErrorTitle, in as withRetry, jt as isPlaceholderImageSigningSecret, lt as UnprocessableEntityError, n as SESSION_ID_PATTERN, o as escapeArtifactBodyJson, pn as frontmatterHasSourceStamp, pt as assertAuthOriginMatchesApiKey, r as isValidSessionId, t as logger, w as CUSTOM_MCP_DATA_NOTICE, wt as getMcpProviderMetadata, x as CONFIDENCE_GATE_MODES, xt as fromCliTodos, z as LOCATION_MAP_LANGUAGE, zt as obfuscateApiKey } from "./Logger-7MmrU5w6.mjs";
5
- import { r as isReservedCommandName } from "./RemoteSkillSource-D_F99yBR.mjs";
6
- import { n as isPathAllowed, t as assertPathAllowed } from "./pathValidation-BRqf4HFX-CHwtwp3O.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-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";
5
+ import { r as isReservedCommandName } from "./RemoteSkillSource-HqoLRV56.mjs";
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-JsKBm7Wn.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";
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";
@@ -17,6 +17,7 @@ import { AsyncFzf } from "fzf";
17
17
  import ignore from "ignore";
18
18
  import fs, { mkdir, readFile, stat, writeFile } from "fs/promises";
19
19
  import { z as z$1 } from "zod";
20
+ import YAML from "yaml";
20
21
  import { isAxiosError } from "axios";
21
22
  import { execFile, spawn } from "child_process";
22
23
  import { promisify } from "util";
@@ -32,7 +33,6 @@ import sum from "lodash/sum.js";
32
33
  import times from "lodash/times.js";
33
34
  import * as Diff from "diff";
34
35
  import { diffLines } from "diff";
35
- import matter from "gray-matter";
36
36
  import { parse as parse$1 } from "shell-quote";
37
37
  import { EventEmitter } from "events";
38
38
  import { fileURLToPath } from "url";
@@ -3695,7 +3695,7 @@ async function isOperationalBillingEnabled(db, logger, holder) {
3695
3695
  return holder ? isFreeTierHolder(holder) : false;
3696
3696
  }
3697
3697
  //#endregion
3698
- //#region ../../b4m-core/services/dist/toolGenerators-Bh6zx8vU.mjs
3698
+ //#region ../../b4m-core/services/dist/toolGenerators-CkAakXQw.mjs
3699
3699
  const diceRoll = async (parameters) => {
3700
3700
  if (!parameters?.sides || !parameters?.times) throw new Error("Tool dice roll: Missing required parameters");
3701
3701
  return sum(times(parameters.times, () => random(1, parameters.sides))).toString();
@@ -4302,6 +4302,33 @@ const promptEnhancementTool = {
4302
4302
  }
4303
4303
  })
4304
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
+ }
4305
4332
  const DecisionToolRequestSchema = DecisionsRequestSchema.pick({
4306
4333
  input: true,
4307
4334
  questions: true,
@@ -4747,35 +4774,6 @@ const generateMcpToolsFromCache = (serverName, cachedTools, callTool) => {
4747
4774
  return result;
4748
4775
  };
4749
4776
  //#endregion
4750
- //#region ../../b4m-core/services/dist/objectId-Bhav0W6F.mjs
4751
- const OBJECT_ID_HEX = /^[0-9a-fA-F]{24}$/;
4752
- /**
4753
- * Is this value shaped like something Mongoose can cast to an `_id`?
4754
- *
4755
- * Tool arguments are composed by the model out of conversation text and reach us as unvalidated
4756
- * JSON, so an id parameter routinely holds something that is not an id at all - a filename token,
4757
- * an arXiv number, a bare integer. Mongoose casts `_id` and throws a CastError on those, which a
4758
- * generic catch upstream then reports as an outage rather than the bad argument it is (#2530).
4759
- * Call this before handing a model-supplied id to `findById` and answer a false the same way the
4760
- * surface answers a genuinely missing row.
4761
- *
4762
- * `isObjectIdOrHexString`, not `isValidObjectId`: the latter also accepts a number and casts it to
4763
- * a fabricated id, and a model emitting `{"file_id": 12}` gives us exactly that despite the
4764
- * `string` type. Same choice, same reason, as `usableObjectIds` in @bike4mind/db-core, which is
4765
- * the array-shaped version of this check.
4766
- *
4767
- * NOT usable for artifact ids (`artifact_<...>`), which are matched on a string `id` field rather
4768
- * than `_id` - see `createArtifactId` in @bike4mind/common.
4769
- *
4770
- * A copy of Mongoose's `isObjectIdOrHexString` (an ObjectId instance, recognised by its
4771
- * `_bsontype` tag, or a 24-hex string) rather than an import of it: this module is reached from
4772
- * the CLI's tool registry, and importing mongoose there costs every CLI launch ~100-200 ms.
4773
- */
4774
- function isObjectIdShaped(id) {
4775
- if (typeof id === "string") return OBJECT_ID_HEX.test(id);
4776
- return typeof id === "object" && id !== null && id._bsontype === "ObjectId";
4777
- }
4778
- //#endregion
4779
4777
  //#region ../../b4m-core/services/dist/llm/tools/cliTools.mjs
4780
4778
  /**
4781
4779
  * Validated fuzzy fallback for `edit_local_file` string matching.
@@ -5135,7 +5133,7 @@ function formatSpanPreview(filePath, matchedText, replacement) {
5135
5133
  /**
5136
5134
  * Authorized, read-only resolve for the permission layer: validate the path,
5137
5135
  * read the file, and resolve the span WITHOUT writing. Runs the SAME path
5138
- * authorization ({@link assertPathAllowed}) and matcher ({@link resolveEdit}) as
5136
+ * authorization ({@link assertWritablePath}) and matcher ({@link resolveEdit}) as
5139
5137
  * the write path, so a preflight can never read a path the tool itself would
5140
5138
  * refuse (no raw-model-path read - closes the auth-bypass / special-file-DoS
5141
5139
  * hole) and its fuzzy verdict matches what execution will do. Throws the same
@@ -5143,7 +5141,7 @@ function formatSpanPreview(filePath, matchedText, replacement) {
5143
5141
  */
5144
5142
  async function resolveEditLocalFile(params, allowedDirectories) {
5145
5143
  const { path: filePath, old_string, new_string } = params;
5146
- const resolvedPath = assertPathAllowed(filePath, allowedDirectories, "edit");
5144
+ const resolvedPath = assertWritablePath(filePath, allowedDirectories, "edit");
5147
5145
  if (!existsSync(resolvedPath)) throw new Error(`File not found: ${filePath}`);
5148
5146
  const currentContent = await promises.readFile(resolvedPath, "utf-8");
5149
5147
  const resolved = resolveEdit(currentContent, old_string, new_string);
@@ -5157,7 +5155,7 @@ async function resolveEditLocalFile(params, allowedDirectories) {
5157
5155
  }
5158
5156
  async function editLocalFile(params, allowedDirectories) {
5159
5157
  const { path: filePath, old_string, new_string, confirmedFuzzyHash, gateSnapshot } = params;
5160
- const resolvedPath = assertPathAllowed(filePath, allowedDirectories, "edit");
5158
+ const resolvedPath = assertWritablePath(filePath, allowedDirectories, "edit");
5161
5159
  if (!existsSync(resolvedPath)) throw new Error(`File not found: ${filePath}`);
5162
5160
  const currentContent = await promises.readFile(resolvedPath, "utf-8");
5163
5161
  const currentHash = sha256(currentContent);
@@ -6193,7 +6191,7 @@ const latticeAddEntityTool = {
6193
6191
  createdAt: /* @__PURE__ */ new Date(),
6194
6192
  updatedAt: /* @__PURE__ */ new Date()
6195
6193
  };
6196
- if (context.db.latticeModels && modelId && isObjectIdShaped(modelId)) try {
6194
+ if (context.db.latticeModels && modelId && isObjectIdShaped$1(modelId)) try {
6197
6195
  const model = await getModelForWrite({
6198
6196
  id: context.userId,
6199
6197
  organizationId: context.user?.organizationId
@@ -6338,7 +6336,7 @@ const latticeSetValueTool = {
6338
6336
  else if (rawValue.toLowerCase() === "true") value = true;
6339
6337
  else if (rawValue.toLowerCase() === "false") value = false;
6340
6338
  const entityId = toEntityId(entityName);
6341
- if (context.db.latticeModels && modelId && isObjectIdShaped(modelId)) try {
6339
+ if (context.db.latticeModels && modelId && isObjectIdShaped$1(modelId)) try {
6342
6340
  const model = await getModelForWrite({
6343
6341
  id: context.userId,
6344
6342
  organizationId: context.user?.organizationId
@@ -6484,7 +6482,7 @@ const latticeCreateRuleTool = {
6484
6482
  };
6485
6483
  const outputEntityId = parsedRule.outputEntity.toLowerCase().replace(/\s+/g, "_");
6486
6484
  let entityCreatedMessage = "";
6487
- if (context.db.latticeModels && modelId && isObjectIdShaped(modelId)) try {
6485
+ if (context.db.latticeModels && modelId && isObjectIdShaped$1(modelId)) try {
6488
6486
  const model = await getModelForWrite({
6489
6487
  id: context.userId,
6490
6488
  organizationId: context.user?.organizationId
@@ -6844,10 +6842,10 @@ const latticeToolDefinitions = {
6844
6842
  */
6845
6843
  const getCliOnlyTools = async () => {
6846
6844
  const [{ createFileTool }, { globFilesTool }, { grepSearchTool }, { deleteFileTool }, { bashExecuteTool }] = await Promise.all([
6847
- import("./createFile-B8bur5Rb-CVzCarEA.mjs"),
6848
- import("./globFiles-CwJ8qmYo-BR5b2KvO.mjs"),
6849
- import("./grepSearch-CLtEqT4j-BnKPtNWr.mjs"),
6850
- import("./deleteFile-9B3gW_Nb-DG2sovIl.mjs"),
6845
+ import("./createFile-CPKmd6Uf-Bk-3V2T3.mjs"),
6846
+ import("./globFiles-CoapsO8G-CpvQo-R2.mjs"),
6847
+ import("./grepSearch-DeH7M2e7-BIvo-yNy.mjs"),
6848
+ import("./deleteFile-CD_xQ7Y6-C1X4Ievb.mjs"),
6851
6849
  import("./bashExecute-CrdPpBqk-CgK1gZa2.mjs")
6852
6850
  ]);
6853
6851
  return {
@@ -7026,54 +7024,119 @@ async function processFileReferences(message, confineTo) {
7026
7024
  };
7027
7025
  }
7028
7026
  //#endregion
7029
- //#region src/utils/parseFrontmatter.ts
7027
+ //#region ../../b4m-core/common/dist/utils/frontmatter.mjs
7030
7028
  /**
7031
- * gray-matter selects its parse engine from the language tag on the opening
7032
- * fence (e.g. `---js`), and its built-in `javascript` engine `eval()`s the
7033
- * block - so a hostile SKILL.md/command/agent file can run code the moment it
7034
- * is loaded, before any Zod validation. This helper is the single guard both
7035
- * frontmatter call sites route through:
7036
- *
7037
- * 1. Reject any opening fence whose language tag is non-empty and not YAML.
7038
- * 2. Disable the eval-capable engines as defense in depth (gray-matter merges
7039
- * a custom `engines` map ON TOP of its built-ins, so the override, not the
7040
- * absence, is what neutralizes `javascript`).
7041
- *
7042
- * A rejected or malformed file degrades to empty frontmatter (with a warning),
7043
- * never an eval and never an uncaught throw.
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.
7044
7079
  */
7045
- /** Opening `---<lang>` fence: capture the language tag on the first line. */
7046
- const OPENING_FENCE = /^---([^\r\n]*)\r?\n/;
7047
- function nonYamlEngineDisabled() {
7048
- throw new Error("non-YAML frontmatter engine is disabled");
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
+ };
7049
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
+ */
7050
7131
  function parseFrontmatter(content) {
7051
- if (content.charCodeAt(0) === 65279) content = content.slice(1);
7052
- const fence = content.match(OPENING_FENCE);
7053
- if (fence) {
7054
- const lang = fence[1].trim().toLowerCase();
7055
- if (lang && lang !== "yaml" && lang !== "yml") {
7056
- logger.warn(`Ignoring non-YAML frontmatter language "${lang}"; treating frontmatter as empty`);
7057
- return {
7058
- data: {},
7059
- content
7060
- };
7061
- }
7062
- }
7063
7132
  try {
7064
- const parsed = matter(content, { engines: {
7065
- javascript: nonYamlEngineDisabled,
7066
- coffee: nonYamlEngineDisabled
7067
- } });
7068
- return {
7069
- data: parsed.data,
7070
- content: parsed.content
7071
- };
7133
+ return parseFrontmatter$1(content);
7072
7134
  } catch (error) {
7073
- logger.warn(`Failed to parse frontmatter: ${error instanceof Error ? error.message : String(error)}`);
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)}`);
7074
7137
  return {
7075
7138
  data: {},
7076
- content
7139
+ content: content.charCodeAt(0) === 65279 ? content.slice(1) : content
7077
7140
  };
7078
7141
  }
7079
7142
  }
@@ -8226,6 +8289,186 @@ function maxLevel(a, b) {
8226
8289
  function isOperator$1(token) {
8227
8290
  return typeof token === "object" && token !== null && "op" in token;
8228
8291
  }
8292
+ function isComment(token) {
8293
+ return typeof token === "object" && token !== null && "comment" in token;
8294
+ }
8295
+ const SHELL_METACHARACTERS = /* @__PURE__ */ new Set([
8296
+ ";",
8297
+ "&",
8298
+ "|",
8299
+ "(",
8300
+ ")",
8301
+ "<",
8302
+ ">"
8303
+ ]);
8304
+ const BASH_BLANKS = /* @__PURE__ */ new Set([
8305
+ " ",
8306
+ " ",
8307
+ "\n"
8308
+ ]);
8309
+ const OPAQUE_SHELL_KEYWORDS = /* @__PURE__ */ new Set([
8310
+ "if",
8311
+ "then",
8312
+ "elif",
8313
+ "else",
8314
+ "fi",
8315
+ "for",
8316
+ "while",
8317
+ "until",
8318
+ "do",
8319
+ "done",
8320
+ "case",
8321
+ "esac",
8322
+ "function",
8323
+ "select",
8324
+ "coproc",
8325
+ "time",
8326
+ "!",
8327
+ "{",
8328
+ "}",
8329
+ "[[",
8330
+ "]]"
8331
+ ]);
8332
+ /** Stands in for a command substitution; its code is classified on its own. */
8333
+ const SUBSTITUTION_PLACEHOLDER = "__cmdsub__";
8334
+ /**
8335
+ * Rewrite a bash command so shell-quote tokenizes it the way bash does. Unquoted newlines become
8336
+ * `;`, bash comments are dropped, a mid-word `#` and whitespace bash does not split on are
8337
+ * escaped, heredocs require approval, and each `$(...)` or backquote substitution (quoted or
8338
+ * not) is replaced by a placeholder word and returned
8339
+ * separately for classification.
8340
+ */
8341
+ function scanShellCommand(command) {
8342
+ const substitutions = [];
8343
+ const { text } = scanCode(command, 0, null, substitutions);
8344
+ return {
8345
+ text,
8346
+ substitutions
8347
+ };
8348
+ }
8349
+ /** Scan unquoted shell code from `start` until `stop` closes it, or to the end of input. */
8350
+ function scanCode(src, start, stop, substitutions) {
8351
+ let out = "";
8352
+ let wordStart = true;
8353
+ let parenDepth = 0;
8354
+ let caseDepth = 0;
8355
+ let index = start;
8356
+ for (; index < src.length; index += 1) {
8357
+ const character = src[index];
8358
+ if (character === stop && (stop === "`" || parenDepth === 0 && caseDepth === 0)) return {
8359
+ text: out,
8360
+ end: index
8361
+ };
8362
+ if (wordStart && /^case[\s;]/.test(src.slice(index, index + 5))) caseDepth += 1;
8363
+ if (wordStart && caseDepth > 0 && /^esac(?:[\s;)&|]|$)/.test(src.slice(index, index + 5))) caseDepth -= 1;
8364
+ if (character === "'") {
8365
+ const close = src.indexOf("'", index + 1);
8366
+ const end = close < 0 ? src.length - 1 : close;
8367
+ out += src.slice(index, end + 1);
8368
+ index = end;
8369
+ wordStart = false;
8370
+ continue;
8371
+ }
8372
+ if (character === "$" && src[index + 1] === "'") {
8373
+ let end = index + 2;
8374
+ while (end < src.length && src[end] !== "'") end += src[end] === "\\" ? 2 : 1;
8375
+ out += src.slice(index, end + 1);
8376
+ index = end;
8377
+ wordStart = false;
8378
+ continue;
8379
+ }
8380
+ if (character === "$" && src[index + 1] === "(" || character === "`") {
8381
+ index = scanSubstitution(src, index, substitutions);
8382
+ out += SUBSTITUTION_PLACEHOLDER;
8383
+ wordStart = false;
8384
+ continue;
8385
+ }
8386
+ if (character === "\"") {
8387
+ const quoted = scanDoubleQuoted(src, index + 1, substitutions);
8388
+ out += `"${quoted.text}"`;
8389
+ index = quoted.end;
8390
+ wordStart = false;
8391
+ continue;
8392
+ }
8393
+ if (character === "\\") {
8394
+ if (src[index + 1] === "\n") {
8395
+ index += 1;
8396
+ continue;
8397
+ }
8398
+ out += character + (src[index + 1] ?? "");
8399
+ index += 1;
8400
+ wordStart = false;
8401
+ continue;
8402
+ }
8403
+ if (character === "#") {
8404
+ if (wordStart) {
8405
+ while (index + 1 < src.length && src[index + 1] !== "\n") index += 1;
8406
+ continue;
8407
+ }
8408
+ out += "\\#";
8409
+ continue;
8410
+ }
8411
+ if (character === "\n") {
8412
+ out += ";";
8413
+ wordStart = true;
8414
+ continue;
8415
+ }
8416
+ if (character === "<" && src[index + 1] === "<" && src[index + 2] !== "<") throw new Error("Heredoc syntax requires approval");
8417
+ if (character === "<" && src.startsWith("<<<", index)) {
8418
+ out += "<<<";
8419
+ index += 2;
8420
+ wordStart = true;
8421
+ continue;
8422
+ }
8423
+ if (BASH_BLANKS.has(character) || SHELL_METACHARACTERS.has(character)) {
8424
+ if (character === "(") parenDepth += 1;
8425
+ if (character === ")" && parenDepth > 0) parenDepth -= 1;
8426
+ out += character;
8427
+ wordStart = true;
8428
+ continue;
8429
+ }
8430
+ if (/\s/.test(character)) {
8431
+ out += `\\${character}`;
8432
+ wordStart = false;
8433
+ continue;
8434
+ }
8435
+ out += character;
8436
+ wordStart = false;
8437
+ }
8438
+ return {
8439
+ text: out,
8440
+ end: index
8441
+ };
8442
+ }
8443
+ /** Record the code of the substitution opening at `index`; returns the index of its closer. */
8444
+ function scanSubstitution(src, index, substitutions) {
8445
+ const backquote = src[index] === "`";
8446
+ const codeStart = index + (backquote ? 1 : 2);
8447
+ const { end } = scanCode(src, codeStart, backquote ? "`" : ")", []);
8448
+ const code = src.slice(codeStart, end);
8449
+ if (backquote && /\\[`$\\]/.test(code)) throw new Error("Unsupported escaped backquote substitution");
8450
+ substitutions.push(code);
8451
+ return end;
8452
+ }
8453
+ /** Scan a double-quoted string body from `start`; returns its text and the closing quote index. */
8454
+ function scanDoubleQuoted(src, start, substitutions) {
8455
+ let text = "";
8456
+ let index = start;
8457
+ for (; index < src.length && src[index] !== "\""; index += 1) {
8458
+ const character = src[index];
8459
+ if (character === "\\") {
8460
+ text += character + (src[index + 1] ?? "");
8461
+ index += 1;
8462
+ } else if (character === "$" && src[index + 1] === "(" || character === "`") {
8463
+ index = scanSubstitution(src, index, substitutions);
8464
+ text += SUBSTITUTION_PLACEHOLDER;
8465
+ } else text += character;
8466
+ }
8467
+ return {
8468
+ text,
8469
+ end: index
8470
+ };
8471
+ }
8229
8472
  function asString(token) {
8230
8473
  if (typeof token === "string") return token;
8231
8474
  if (typeof token === "object" && token !== null && "pattern" in token) return token.pattern;
@@ -8329,11 +8572,27 @@ function classifySimpleCommand(args, reasons, depth) {
8329
8572
  const inner = args.slice(index);
8330
8573
  if (inner.length === 0) return level;
8331
8574
  const prog = programName$1(inner[0]);
8575
+ if (ENV_ASSIGNMENT.test(inner[0]) || OPAQUE_SHELL_KEYWORDS.has(prog)) {
8576
+ reasons.push("shell context requires approval");
8577
+ return "high";
8578
+ }
8579
+ if (prog.includes(SUBSTITUTION_PLACEHOLDER)) {
8580
+ reasons.push("computed program requires approval");
8581
+ return "high";
8582
+ }
8583
+ if ((DESTINATION_WRITERS.has(prog) || OPERAND_WRITERS.has(prog) || prog === "dd") && inner.slice(1).some((arg) => arg.includes(SUBSTITUTION_PLACEHOLDER))) {
8584
+ reasons.push("computed writer arguments require approval");
8585
+ return "high";
8586
+ }
8332
8587
  if (INTERPRETERS.has(prog)) {
8333
8588
  const codeCandidates = interpreterCodeCandidates(inner, EVAL_E_INTERPRETERS.has(prog) ? /[ce]/ : /c/);
8334
8589
  if (codeCandidates.length > 0) {
8335
8590
  reasons.push(`inline code executed via '${prog}'`);
8336
8591
  for (const code of codeCandidates) {
8592
+ if (code.includes(SUBSTITUTION_PLACEHOLDER)) {
8593
+ reasons.push("computed interpreter code requires approval");
8594
+ return "high";
8595
+ }
8337
8596
  const nested = classifyAtDepth(code, depth + 1);
8338
8597
  reasons.push(...nested.reasons);
8339
8598
  level = maxLevel(level, nested.level);
@@ -8343,6 +8602,10 @@ function classifySimpleCommand(args, reasons, depth) {
8343
8602
  }
8344
8603
  if (prog === "eval" && inner.length > 1) {
8345
8604
  reasons.push("dynamic evaluation via 'eval'");
8605
+ if (inner.slice(1).some((arg) => arg.includes(SUBSTITUTION_PLACEHOLDER))) {
8606
+ reasons.push("computed eval code requires approval");
8607
+ return "high";
8608
+ }
8346
8609
  const nested = classifyAtDepth(inner.slice(1).join(" "), depth + 1);
8347
8610
  reasons.push(...nested.reasons);
8348
8611
  return maxLevel(level, nested.level);
@@ -8355,6 +8618,10 @@ function classifySimpleCommand(args, reasons, depth) {
8355
8618
  reasons.push("write to a raw block device via tee");
8356
8619
  return maxLevel(level, "high");
8357
8620
  }
8621
+ if (gitDirectoryWriteTarget(prog, inner.slice(1))) {
8622
+ reasons.push(`'${prog}' writes to a protected or unresolved path`);
8623
+ return maxLevel(level, "high");
8624
+ }
8358
8625
  if (prog === "rm") {
8359
8626
  const flags = inner.slice(1).filter((arg) => arg.startsWith("-"));
8360
8627
  const targets = inner.slice(1).filter((arg) => !arg.startsWith("-"));
@@ -8367,12 +8634,131 @@ function classifySimpleCommand(args, reasons, depth) {
8367
8634
  reasons.push("file removal via 'rm'");
8368
8635
  return maxLevel(level, "medium");
8369
8636
  }
8637
+ if (prog === "git" && setsProgramRunningGitConfig(inner.slice(1))) {
8638
+ reasons.push("git config naming a program git runs");
8639
+ return maxLevel(level, "high");
8640
+ }
8370
8641
  if ((prog === "chmod" || prog === "chown" || prog === "chgrp") && inner.some((arg) => shortFlagContains(arg, RECURSIVE_SHORT_FLAGS) || arg === "--recursive")) {
8371
8642
  reasons.push(`recursive '${prog}'`);
8372
8643
  return maxLevel(level, "high");
8373
8644
  }
8374
8645
  return level;
8375
8646
  }
8647
+ /** Programs whose last operand is the path they write. */
8648
+ const DESTINATION_WRITERS = /* @__PURE__ */ new Set([
8649
+ "cp",
8650
+ "install",
8651
+ "ln",
8652
+ "rsync",
8653
+ "scp"
8654
+ ]);
8655
+ /** Programs that may write or remove any path operand. */
8656
+ const OPERAND_WRITERS = /* @__PURE__ */ new Set([
8657
+ "mv",
8658
+ "tee",
8659
+ "touch",
8660
+ "truncate",
8661
+ "sed",
8662
+ "chmod",
8663
+ "chown",
8664
+ "chgrp",
8665
+ "patch",
8666
+ "rm",
8667
+ "unlink"
8668
+ ]);
8669
+ function gitDirectoryWriteTarget(prog, args) {
8670
+ const operands = args.filter((arg) => !arg.startsWith("-"));
8671
+ if (DESTINATION_WRITERS.has(prog)) {
8672
+ const targets = args.flatMap((arg, index) => {
8673
+ if (arg === "-t" || arg === "--target-directory") return args[index + 1] ?? [];
8674
+ if (arg.startsWith("--target-directory=")) return arg.slice(19);
8675
+ if (/^-t./.test(arg)) return arg.slice(2);
8676
+ return [];
8677
+ });
8678
+ targets.push(operands[operands.length - 1] ?? "");
8679
+ return targets.some(isProtectedOrUnresolvedPath);
8680
+ }
8681
+ if (OPERAND_WRITERS.has(prog)) return operands.some(isProtectedOrUnresolvedPath);
8682
+ if (prog === "dd") return args.some((arg) => arg.startsWith("of=") && isProtectedOrUnresolvedPath(arg.slice(3)));
8683
+ return false;
8684
+ }
8685
+ /** Config keys whose value is a program, script or hook location git runs. */
8686
+ const PROGRAM_GIT_CONFIG_KEY = /^(core\.(hookspath|fsmonitor|sshcommand|pager|editor|askpass|gitproxy)|sequence\.editor|diff\.external|gpg(\.[^.]+)?\.program|credential(\..+)?\.helper|alias\..+|(diff|merge|filter|difftool|mergetool)\..+\.(command|cmd|textconv|driver|clean|smudge|process)|.+\.sshcommand|uploadpack\.packobjectshook|include(if\..+)?\.path)$/i;
8687
+ const GIT_GLOBAL_VALUE_OPTIONS = /* @__PURE__ */ new Set([
8688
+ "-C",
8689
+ "-c",
8690
+ "--git-dir",
8691
+ "--work-tree",
8692
+ "--namespace",
8693
+ "--super-prefix",
8694
+ "--config-env",
8695
+ "--attr-source"
8696
+ ]);
8697
+ const GIT_CONFIG_READ_OPTIONS = /* @__PURE__ */ new Set([
8698
+ "--get",
8699
+ "--get-all",
8700
+ "--get-regexp",
8701
+ "--get-urlmatch",
8702
+ "--get-color",
8703
+ "--get-colorbool",
8704
+ "--list",
8705
+ "-l"
8706
+ ]);
8707
+ const GIT_CONFIG_VALUE_OPTIONS = /* @__PURE__ */ new Set([
8708
+ "-f",
8709
+ "--file",
8710
+ "--blob",
8711
+ "--type",
8712
+ "--default",
8713
+ "--comment",
8714
+ "--value"
8715
+ ]);
8716
+ /** `git -c <key>=<value>` or a `git config` write whose key names a program git runs. */
8717
+ function setsProgramRunningGitConfig(args) {
8718
+ if (args.some((arg) => arg.includes(SUBSTITUTION_PLACEHOLDER))) return true;
8719
+ const programKey = (key) => key.includes(SUBSTITUTION_PLACEHOLDER) || PROGRAM_GIT_CONFIG_KEY.test(key);
8720
+ for (let index = 0; index < args.length; index += 1) {
8721
+ const arg = args[index];
8722
+ const configValue = arg === "-c" || arg === "--config-env" ? args[index + 1] : arg.startsWith("-c") && arg.length > 2 ? arg.slice(2) : arg.startsWith("--config-env=") ? arg.slice(13) : void 0;
8723
+ if (configValue !== void 0 && programKey(configValue.split("=")[0])) return true;
8724
+ if (GIT_GLOBAL_VALUE_OPTIONS.has(arg)) {
8725
+ index += 1;
8726
+ continue;
8727
+ }
8728
+ if (arg.startsWith("-")) continue;
8729
+ if (arg !== "config") return false;
8730
+ const words = [];
8731
+ let options = true;
8732
+ let readOnly = false;
8733
+ let unset = false;
8734
+ for (let cursor = index + 1; cursor < args.length; cursor += 1) {
8735
+ const word = args[cursor];
8736
+ if (options && word === "--") {
8737
+ options = false;
8738
+ continue;
8739
+ }
8740
+ if (options && GIT_CONFIG_READ_OPTIONS.has(word)) {
8741
+ readOnly = true;
8742
+ continue;
8743
+ }
8744
+ if (options && (word === "--unset" || word === "--unset-all")) {
8745
+ unset = true;
8746
+ continue;
8747
+ }
8748
+ if (options && GIT_CONFIG_VALUE_OPTIONS.has(word)) {
8749
+ cursor += 1;
8750
+ continue;
8751
+ }
8752
+ if (options && word.startsWith("-")) continue;
8753
+ words.push(word);
8754
+ }
8755
+ if (readOnly || words[0] === "get" || words[0] === "list") return false;
8756
+ const keyIndex = words[0] === "set" || words[0] === "unset" ? 1 : 0;
8757
+ const key = words[keyIndex];
8758
+ return (unset || words[0] === "unset" || words.length > keyIndex + 1) && key !== void 0 && programKey(key);
8759
+ }
8760
+ return false;
8761
+ }
8376
8762
  /**
8377
8763
  * Detect a fork bomb: a shell function that recursively calls itself and
8378
8764
  * backgrounds the call, e.g. `:(){ :|:& };:`. shell-quote does not model function
@@ -8419,33 +8805,56 @@ function classifyAtDepth(command, depth) {
8419
8805
  level: "high",
8420
8806
  reasons: ["fork bomb pattern"]
8421
8807
  };
8808
+ let scan;
8422
8809
  let tokens;
8423
8810
  try {
8424
- tokens = parse$1(trimmed);
8811
+ scan = scanShellCommand(trimmed);
8812
+ tokens = parse$1(scan.text, () => SUBSTITUTION_PLACEHOLDER);
8425
8813
  } catch {
8426
8814
  return {
8427
8815
  level: "high",
8428
8816
  reasons: ["command could not be parsed (fail closed)"]
8429
8817
  };
8430
8818
  }
8819
+ if (tokens.some(isComment)) return {
8820
+ level: "high",
8821
+ reasons: ["command text could not be fully analyzed (fail closed)"]
8822
+ };
8431
8823
  if (tokens.length === 0) return {
8432
8824
  level: "low",
8433
8825
  reasons: []
8434
8826
  };
8435
8827
  const reasons = [];
8436
8828
  let level = "low";
8829
+ for (const code of scan.substitutions) {
8830
+ const nested = classifyAtDepth(code, depth + 1);
8831
+ reasons.push(...nested.reasons);
8832
+ level = maxLevel(level, maxLevel(nested.level, "unclassified"));
8833
+ }
8437
8834
  const segmentProgs = [];
8438
8835
  const joinerAfter = [];
8836
+ const segmentComputedInputs = [];
8439
8837
  let current = [];
8440
8838
  let currentHerestrings = [];
8441
8839
  let pendingHerestring = false;
8840
+ let pendingRedirectOperand = false;
8841
+ let currentRedirectInput = false;
8442
8842
  const flushSegment = (joiner) => {
8843
+ if (pendingRedirectOperand || pendingHerestring) {
8844
+ reasons.push("incomplete redirection requires approval");
8845
+ level = "high";
8846
+ }
8443
8847
  if (current.length > 0) {
8444
8848
  const localReasons = [];
8445
8849
  let segmentLevel = classifySimpleCommand(current, localReasons, depth);
8446
8850
  const lead = leadingProgram(current);
8447
8851
  if (currentHerestrings.length > 0 && (INTERPRETERS.has(lead) || SOURCE_BUILTINS.has(lead))) for (const code of currentHerestrings) {
8448
8852
  localReasons.push(`inline code executed via '${lead} <<<'`);
8853
+ if (code.includes(SUBSTITUTION_PLACEHOLDER)) {
8854
+ localReasons.push("computed interpreter input requires approval");
8855
+ segmentLevel = "high";
8856
+ continue;
8857
+ }
8449
8858
  const nested = classifyAtDepth(code, depth + 1);
8450
8859
  localReasons.push(...nested.reasons);
8451
8860
  segmentLevel = maxLevel(segmentLevel, nested.level);
@@ -8453,16 +8862,24 @@ function classifyAtDepth(command, depth) {
8453
8862
  level = maxLevel(level, segmentLevel);
8454
8863
  reasons.push(...localReasons);
8455
8864
  segmentProgs.push(lead);
8865
+ segmentComputedInputs.push(current.some((arg) => arg.includes(SUBSTITUTION_PLACEHOLDER)) || currentHerestrings.length > 0 || currentRedirectInput);
8456
8866
  joinerAfter.push(joiner);
8457
8867
  }
8458
8868
  current = [];
8459
8869
  currentHerestrings = [];
8460
8870
  pendingHerestring = false;
8871
+ pendingRedirectOperand = false;
8872
+ currentRedirectInput = false;
8461
8873
  };
8462
8874
  for (const token of tokens) {
8463
8875
  if (isOperator$1(token)) {
8464
8876
  const op = token.op;
8465
8877
  if (op === "<<<") {
8878
+ level = maxLevel(level, "unclassified");
8879
+ if (/^\d+$/.test(current[current.length - 1] ?? "")) {
8880
+ reasons.push("ambiguous file descriptor requires approval");
8881
+ level = "high";
8882
+ }
8466
8883
  pendingHerestring = true;
8467
8884
  continue;
8468
8885
  }
@@ -8470,10 +8887,24 @@ function classifyAtDepth(command, depth) {
8470
8887
  flushSegment(op);
8471
8888
  continue;
8472
8889
  }
8890
+ if (WRITE_REDIRECT_OPS.has(op) || op === "<" || op === "<&" || op === ">&") {
8891
+ if (op === "<" || op === "<&" || op === "<>") currentRedirectInput = true;
8892
+ level = maxLevel(level, "unclassified");
8893
+ if (/^\d+$/.test(current[current.length - 1] ?? "")) {
8894
+ reasons.push("ambiguous file descriptor requires approval");
8895
+ level = "high";
8896
+ }
8897
+ pendingRedirectOperand = true;
8898
+ continue;
8899
+ }
8473
8900
  continue;
8474
8901
  }
8475
8902
  const str = asString(token);
8476
8903
  if (str !== null) {
8904
+ if (pendingRedirectOperand) {
8905
+ pendingRedirectOperand = false;
8906
+ continue;
8907
+ }
8477
8908
  if (pendingHerestring) {
8478
8909
  currentHerestrings.push(str);
8479
8910
  pendingHerestring = false;
@@ -8485,10 +8916,19 @@ function classifyAtDepth(command, depth) {
8485
8916
  reasons.push("fetch-and-execute: downloaded content executed by an interpreter");
8486
8917
  level = maxLevel(level, "high");
8487
8918
  }
8488
- if (writesToBlockDevice(tokens)) {
8919
+ if (groupFeedsInterpreter(segmentProgs, joinerAfter, (index) => segmentComputedInputs[index] === true)) {
8920
+ reasons.push("pipeline script input requires approval");
8921
+ level = "high";
8922
+ }
8923
+ const redirected = writeRedirectTargets(tokens);
8924
+ if (redirected.some((target) => BLOCK_DEVICE_RE.test(target))) {
8489
8925
  reasons.push("write redirected to a raw block device");
8490
8926
  level = maxLevel(level, "high");
8491
8927
  }
8928
+ if (redirected.some(isProtectedOrUnresolvedPath)) {
8929
+ reasons.push("write redirected to a protected or unresolved path");
8930
+ level = maxLevel(level, "high");
8931
+ }
8492
8932
  return {
8493
8933
  level,
8494
8934
  reasons
@@ -8512,14 +8952,20 @@ const FETCH_EXEC_CONNECTORS = /* @__PURE__ */ new Set([
8512
8952
  * pipe or a process-substitution boundary.
8513
8953
  */
8514
8954
  function isFetchAndExecute(progs, joinerAfter) {
8955
+ return groupFeedsInterpreter(progs, joinerAfter, (index) => NETWORK_FETCHERS.has(progs[index]));
8956
+ }
8957
+ function groupFeedsInterpreter(progs, joinerAfter, isSource) {
8515
8958
  let start = 0;
8516
8959
  while (start < progs.length) {
8517
8960
  let end = start;
8518
8961
  while (end < progs.length - 1 && FETCH_EXEC_CONNECTORS.has(joinerAfter[end])) end += 1;
8519
- const pipeline = progs.slice(start, end + 1);
8520
- const hasFetcher = pipeline.some((prog) => NETWORK_FETCHERS.has(prog));
8521
- const hasSink = pipeline.some((prog) => FETCH_SINK_PROGRAMS.has(prog));
8522
- if (hasFetcher && hasSink) return true;
8962
+ let source = false;
8963
+ let sink = false;
8964
+ for (let index = start; index <= end; index += 1) {
8965
+ source ||= isSource(index);
8966
+ sink ||= FETCH_SINK_PROGRAMS.has(progs[index]);
8967
+ }
8968
+ if (source && sink) return true;
8523
8969
  start = end + 1;
8524
8970
  }
8525
8971
  return false;
@@ -8544,7 +8990,8 @@ const WRITE_REDIRECT_OPS = /* @__PURE__ */ new Set([
8544
8990
  "&>>",
8545
8991
  "<>"
8546
8992
  ]);
8547
- function writesToBlockDevice(tokens) {
8993
+ function writeRedirectTargets(tokens) {
8994
+ const targets = [];
8548
8995
  for (let i = 0; i < tokens.length; i += 1) {
8549
8996
  const token = tokens[i];
8550
8997
  if (isOperator$1(token) && WRITE_REDIRECT_OPS.has(token.op)) {
@@ -8552,11 +8999,16 @@ function writesToBlockDevice(tokens) {
8552
8999
  const following = tokens[targetIndex];
8553
9000
  if (isOperator$1(following) && following.op === "|") targetIndex += 1;
8554
9001
  const target = asString(tokens[targetIndex]);
8555
- if (target && BLOCK_DEVICE_RE.test(target)) return true;
9002
+ if (target) targets.push(target);
8556
9003
  }
8557
9004
  }
8558
- return false;
9005
+ return targets;
9006
+ }
9007
+ /** A path with a `.git` segment, compared the way case-insensitive filesystems and Windows do. */
9008
+ function isGitDirectoryPath(target) {
9009
+ return target.split(/[\\/]/).some((segment) => segment.replace(/[. ]+$/, "").toLowerCase() === ".git");
8559
9010
  }
9011
+ const isProtectedOrUnresolvedPath = (target) => isGitDirectoryPath(target) || target.includes(SUBSTITUTION_PLACEHOLDER);
8560
9012
  //#endregion
8561
9013
  //#region src/tools/gateway/stages/commandRisk.ts
8562
9014
  /**
@@ -8643,7 +9095,7 @@ var ServerToolExecutor = class {
8643
9095
  const status = err?.response?.status || "unknown";
8644
9096
  if (err?.response?.data?.errorCode === "insufficient_credits") return outOfCreditsToolResult(toolName, err.response.data.error);
8645
9097
  logger.error(`[ServerToolExecutor] Request failed for ${toolName}: ${errorMessage} (status: ${status})`);
8646
- logger.debug(`[ServerToolExecutor] Full error: ${JSON.stringify(err, null, 2)}`);
9098
+ logger.debug(`[ServerToolExecutor] Error code: ${err?.code ?? "none"}`);
8647
9099
  return `Error executing ${toolName}: ${errorMessage}`;
8648
9100
  }
8649
9101
  }
@@ -9566,6 +10018,7 @@ function wrapToolWithPermission(tool, deps) {
9566
10018
  const originalFn = tool.toolFn;
9567
10019
  const toolName = tool.toolSchema.name;
9568
10020
  const isMcpTool = tool._isMcpTool === true;
10021
+ if (isMcpTool) permissionManager.catalog.markMcpTool(toolName);
9569
10022
  return {
9570
10023
  ...tool,
9571
10024
  toolFn: async (input) => {
@@ -13960,7 +14413,7 @@ async function requestShellCommandPermission(toolName, command, cwd, deps) {
13960
14413
  allowed: false,
13961
14414
  reason: "Parent session ended"
13962
14415
  };
13963
- if (!permissionManager.needsPermission(toolName)) return { allowed: true };
14416
+ if (permissionManager.isExactCommandSessionTrusted(toolName, command, cwd) || !permissionManager.needsPermission(toolName)) return { allowed: true };
13964
14417
  const risk = classifyCommandRisk(command);
13965
14418
  const reasons = risk.reasons.length ? `\nReasons: ${risk.reasons.join("; ")}` : "";
13966
14419
  const preview = `Hook shell command [${risk.level} risk] in ${cwd}:\n${command}${reasons}`;
@@ -13974,7 +14427,7 @@ async function requestShellCommandPermission(toolName, command, cwd, deps) {
13974
14427
  };
13975
14428
  switch (action) {
13976
14429
  case "allow-session":
13977
- permissionManager.trustToolForSession(toolName);
14430
+ permissionManager.trustExactCommandForSession(toolName, command, cwd);
13978
14431
  return { allowed: true };
13979
14432
  case "allow-once":
13980
14433
  case "allow-always": return { allowed: true };
@@ -15012,8 +15465,11 @@ function optionsAreReadOnly(args, grammar) {
15012
15465
  const REFUSED_OPTIONS = {
15013
15466
  go: { long: [
15014
15467
  "-exec",
15468
+ "--exec",
15015
15469
  "-toolexec",
15016
- "-vettool"
15470
+ "--toolexec",
15471
+ "-vettool",
15472
+ "--vettool"
15017
15473
  ] },
15018
15474
  cargo: { long: ["--config"] }
15019
15475
  };
@@ -15197,11 +15653,11 @@ function sessionCommandPrefixes(command) {
15197
15653
  const text = command.replace(/\s+$/, "");
15198
15654
  if (text.length === 0) return null;
15199
15655
  if (hasShellExpansion(text)) return null;
15200
- if (/[\n\r`]/.test(text) || text.includes("$(") || text.includes("<(") || text.includes(">(")) return null;
15656
+ if (/[^\S \t]/.test(text) || /`/.test(text) || text.includes("$(") || text.includes("<(") || text.includes(">(")) return null;
15201
15657
  if (classifyCommandRisk(text).level === "high") return null;
15202
15658
  let tokens;
15203
15659
  try {
15204
- tokens = parse$1(text, (key) => `$${key}`);
15660
+ tokens = parse$1(scanShellCommand(text).text, (key) => `$${key}`);
15205
15661
  } catch {
15206
15662
  return null;
15207
15663
  }
@@ -15215,6 +15671,7 @@ function sessionCommandPrefixes(command) {
15215
15671
  words = [];
15216
15672
  return true;
15217
15673
  };
15674
+ if (tokens.some(isComment)) return null;
15218
15675
  for (let index = 0; index < tokens.length; index += 1) {
15219
15676
  const token = tokens[index];
15220
15677
  if (isOperator(token)) {
@@ -15255,6 +15712,7 @@ var PermissionManager = class {
15255
15712
  this.trustedTools = /* @__PURE__ */ new Set();
15256
15713
  this.sessionTrustedTools = /* @__PURE__ */ new Set();
15257
15714
  this.sessionTrustedCommands = /* @__PURE__ */ new Map();
15715
+ this.sessionTrustedExactCommands = /* @__PURE__ */ new Map();
15258
15716
  this.deniedTools = /* @__PURE__ */ new Set();
15259
15717
  this._sandboxMode = "disabled";
15260
15718
  this._sandboxActive = false;
@@ -15318,7 +15776,7 @@ var PermissionManager = class {
15318
15776
  * Get list of all trusted tools
15319
15777
  */
15320
15778
  getTrustedTools() {
15321
- return Array.from(this.trustedTools).sort();
15779
+ return Array.from(this.trustedTools).filter((toolName) => this.catalog.canTrust(toolName)).sort();
15322
15780
  }
15323
15781
  /**
15324
15782
  * Check if a tool is currently trusted
@@ -15392,6 +15850,22 @@ var PermissionManager = class {
15392
15850
  return prefixes !== null && prefixes.every((prefix) => approved.has(prefix));
15393
15851
  }
15394
15852
  /**
15853
+ * Trust, for the current session, later calls of this tool with exactly this command text run
15854
+ * in this directory. Used where the command does not come from the model (lifecycle hooks), so
15855
+ * it is never scoped.
15856
+ */
15857
+ trustExactCommandForSession(toolName, command, cwd) {
15858
+ if (this.deniedTools.has(toolName)) return false;
15859
+ const approved = this.sessionTrustedExactCommands.get(toolName) ?? /* @__PURE__ */ new Set();
15860
+ approved.add(JSON.stringify([cwd, command]));
15861
+ this.sessionTrustedExactCommands.set(toolName, approved);
15862
+ return true;
15863
+ }
15864
+ isExactCommandSessionTrusted(toolName, command, cwd) {
15865
+ if (this.deniedTools.has(toolName)) return false;
15866
+ return this.sessionTrustedExactCommands.get(toolName)?.has(JSON.stringify([cwd, command])) ?? false;
15867
+ }
15868
+ /**
15395
15869
  * Check if a tool is trusted for the current session
15396
15870
  */
15397
15871
  isSessionTrusted(toolName) {
@@ -15410,6 +15884,7 @@ var PermissionManager = class {
15410
15884
  clearSessionTrust() {
15411
15885
  this.sessionTrustedTools.clear();
15412
15886
  this.sessionTrustedCommands.clear();
15887
+ this.sessionTrustedExactCommands.clear();
15413
15888
  this.sandboxEscalationApprovals.clear();
15414
15889
  }
15415
15890
  /**
@@ -19661,8 +20136,8 @@ async function buildSandbox(input) {
19661
20136
  const { config, sessionId, permissionManager, checkpointStore } = input;
19662
20137
  const log = input.log ?? consoleLog;
19663
20138
  const [{ createSandboxRuntime }, { SandboxOrchestrator }, { DEFAULT_SANDBOX_CONFIG }, { ProxyManager }, { ViolationLogStore }] = await Promise.all([
19664
- import("./SandboxRuntimeAdapter-CFEIywKt.mjs"),
19665
- import("./SandboxOrchestrator-CeDwd6Fj.mjs"),
20139
+ import("./SandboxRuntimeAdapter-BjJwJNfg.mjs"),
20140
+ import("./SandboxOrchestrator-yORi2eFV.mjs"),
19666
20141
  import("./types-BFIvwByC.mjs"),
19667
20142
  import("./ProxyManager-TxEKlgdO.mjs"),
19668
20143
  import("./ViolationLogStore-byEhxa2A.mjs")
@@ -19951,6 +20426,24 @@ function buildMcpChildEnv({ serverName, envVariables, hasCustomCommand = false }
19951
20426
  droppedKeys
19952
20427
  };
19953
20428
  }
20429
+ function emit(level, scope, message, fields) {
20430
+ const redacted = fields ? redactLogValue(fields) : void 0;
20431
+ console[level](`[${scope}] ${redactLogText(message)}`, ...redacted ? [redacted] : []);
20432
+ }
20433
+ /**
20434
+ * Redacting logger for code that runs inside a host process (the CLI's Ink TUI, desktop main, servers),
20435
+ * as opposed to a stdio server. Redaction happens here in `emit`; writing through `console` lets the
20436
+ * host's console patching apply. debug/info are no-ops: host-side callers do not use them.
20437
+ */
20438
+ function createConsoleLogger(scope) {
20439
+ return {
20440
+ debug: () => {},
20441
+ info: () => {},
20442
+ warn: (message, fields) => emit("warn", scope, message, fields),
20443
+ error: (message, fields) => emit("error", scope, message, fields)
20444
+ };
20445
+ }
20446
+ const log = createConsoleLogger("mcp-client");
19954
20447
  const createSdkClient = () => new Client({
19955
20448
  name: "mcp-client-cli",
19956
20449
  version: "1.0.0"
@@ -20013,14 +20506,16 @@ var MCPClient = class {
20013
20506
  const serverScriptPath = path.join(moduleDir, this.serverName, "index.mjs");
20014
20507
  if (!existsSync(serverScriptPath)) {
20015
20508
  const availableFiles = readdirSync(moduleDir, { withFileTypes: true }).map((d) => d.isDirectory() ? `${d.name}/` : d.name);
20016
- console.error(`[MCP] Server script not found at: ${serverScriptPath}`);
20017
- console.error(`[MCP] Module directory: ${moduleDir}`);
20018
- console.error(`[MCP] Available in module dir:`, availableFiles);
20509
+ log.error("server script not found", {
20510
+ server: this.serverName,
20511
+ serverScriptPath,
20512
+ moduleDir,
20513
+ availableFiles
20514
+ });
20019
20515
  throw new Error(`MCP Server script not found for ${this.serverName} at ${serverScriptPath}. Module dir: ${moduleDir}`);
20020
20516
  }
20021
20517
  command = process.execPath;
20022
20518
  args = [serverScriptPath];
20023
- console.log(`[MCP] Using server: ${this.serverName} at ${serverScriptPath}`);
20024
20519
  }
20025
20520
  const stderrMode = this.suppressStderr ? "ignore" : this.onStderrLine ? "pipe" : void 0;
20026
20521
  const { env, droppedKeys } = buildMcpChildEnv({
@@ -20028,7 +20523,10 @@ var MCPClient = class {
20028
20523
  envVariables: this.envVariables,
20029
20524
  hasCustomCommand: Boolean(customCommand)
20030
20525
  });
20031
- if (droppedKeys.length > 0) console.warn(`[MCP] Withheld ${droppedKeys.length} undeclared env variable(s) from ${this.serverName}: ${droppedKeys.join(", ")}`);
20526
+ if (droppedKeys.length > 0) log.warn("withheld undeclared env variables from server", {
20527
+ server: this.serverName,
20528
+ droppedKeys
20529
+ });
20032
20530
  const transportConfig = {
20033
20531
  command,
20034
20532
  args,
@@ -20038,7 +20536,10 @@ var MCPClient = class {
20038
20536
  const stdioTransport = new StdioClientTransport(transportConfig);
20039
20537
  this.transport = stdioTransport;
20040
20538
  stdioTransport.onerror = (error) => {
20041
- console.error(`[MCP] Transport error for ${this.serverName}:`, error);
20539
+ log.error("transport error", {
20540
+ server: this.serverName,
20541
+ error
20542
+ });
20042
20543
  };
20043
20544
  if (this.onStderrLine && stdioTransport.stderr) this.readStderr(stdioTransport.stderr);
20044
20545
  await this.mcp.connect(stdioTransport);
@@ -20072,7 +20573,10 @@ var MCPClient = class {
20072
20573
  sessionExpired = true;
20073
20574
  return;
20074
20575
  }
20075
- console.error(`[MCP] Transport error for ${this.serverName}: ${error.message}`);
20576
+ log.error("transport error", {
20577
+ server: this.serverName,
20578
+ detail: error.message
20579
+ });
20076
20580
  };
20077
20581
  this.transport = transport;
20078
20582
  await client.connect(transport);
@@ -20206,7 +20710,10 @@ var MCPClient = class {
20206
20710
  }
20207
20711
  } catch (error) {
20208
20712
  if (error instanceof Error && (error.message.includes("Connection closed") || error.message.includes("-32000") || error.message.includes("EPIPE"))) {
20209
- console.error(`[MCP] Connection lost while calling tool ${toolName} on ${this.serverName}`);
20713
+ log.error("connection lost while calling tool", {
20714
+ server: this.serverName,
20715
+ toolName
20716
+ });
20210
20717
  throw new Error(`MCP connection lost for ${this.serverName}. Please retry the operation.`);
20211
20718
  }
20212
20719
  throw error;
@@ -20222,7 +20729,10 @@ var MCPClient = class {
20222
20729
  if (this.transport) await this.mcp.close();
20223
20730
  } catch (error) {
20224
20731
  if (!(error instanceof Error && (error.message.includes("Connection closed") || error.message.includes("-32000") || error.message.includes("EPIPE") || error.message.includes("ECONNRESET")))) {
20225
- console.error("Error during MCP disconnect:", error);
20732
+ log.error("error during disconnect", {
20733
+ server: this.serverName,
20734
+ error
20735
+ });
20226
20736
  throw error;
20227
20737
  }
20228
20738
  } finally {