rulesync 43.9.2 → 43.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -382,36 +382,36 @@ function formatError(error) {
382
382
  return boundErrorMessage(String(error));
383
383
  }
384
384
  // src/constants/rulesync-paths.ts
385
- const { join: join$357 } = node_path.posix;
385
+ const { join: join$358 } = node_path.posix;
386
386
  const RULESYNC_CONFIG_RELATIVE_FILE_PATH = "rulesync.jsonc";
387
387
  const RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH = "rulesync.local.jsonc";
388
388
  const RULESYNC_USER_CONFIG_DIR_NAME = "rulesync";
389
389
  const RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME = ".config";
390
390
  const RULESYNC_RELATIVE_DIR_PATH = ".rulesync";
391
391
  const RULES_FEATURE_SUBDIR = "rules";
392
- const CURATED_RULES_FEATURE_SUBDIR = join$357(RULES_FEATURE_SUBDIR, ".curated");
392
+ const CURATED_RULES_FEATURE_SUBDIR = join$358(RULES_FEATURE_SUBDIR, ".curated");
393
393
  const COMMANDS_FEATURE_SUBDIR = "commands";
394
394
  const SUBAGENTS_FEATURE_SUBDIR = "subagents";
395
395
  const CHECKS_FEATURE_SUBDIR = "checks";
396
396
  const SKILLS_FEATURE_SUBDIR = "skills";
397
- const CURATED_SKILLS_FEATURE_SUBDIR = join$357(SKILLS_FEATURE_SUBDIR, ".curated");
398
- const RULESYNC_RULES_RELATIVE_DIR_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, RULES_FEATURE_SUBDIR);
399
- const RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, CURATED_RULES_FEATURE_SUBDIR);
400
- const RULESYNC_COMMANDS_RELATIVE_DIR_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, COMMANDS_FEATURE_SUBDIR);
401
- const RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, SUBAGENTS_FEATURE_SUBDIR);
402
- const RULESYNC_CHECKS_RELATIVE_DIR_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, CHECKS_FEATURE_SUBDIR);
403
- const RULESYNC_MCP_RELATIVE_FILE_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, "mcp.jsonc");
404
- const RULESYNC_HOOKS_RELATIVE_FILE_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, "hooks.jsonc");
405
- const RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, "permissions.jsonc");
406
- join$357(RULESYNC_RELATIVE_DIR_PATH, "mcp.json");
407
- const RULESYNC_HOOKS_LEGACY_RELATIVE_FILE_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, "hooks.json");
408
- const RULESYNC_PERMISSIONS_LEGACY_RELATIVE_FILE_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, "permissions.json");
397
+ const CURATED_SKILLS_FEATURE_SUBDIR = join$358(SKILLS_FEATURE_SUBDIR, ".curated");
398
+ const RULESYNC_RULES_RELATIVE_DIR_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, RULES_FEATURE_SUBDIR);
399
+ const RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, CURATED_RULES_FEATURE_SUBDIR);
400
+ const RULESYNC_COMMANDS_RELATIVE_DIR_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, COMMANDS_FEATURE_SUBDIR);
401
+ const RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, SUBAGENTS_FEATURE_SUBDIR);
402
+ const RULESYNC_CHECKS_RELATIVE_DIR_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, CHECKS_FEATURE_SUBDIR);
403
+ const RULESYNC_MCP_RELATIVE_FILE_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, "mcp.jsonc");
404
+ const RULESYNC_HOOKS_RELATIVE_FILE_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, "hooks.jsonc");
405
+ const RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, "permissions.jsonc");
406
+ join$358(RULESYNC_RELATIVE_DIR_PATH, "mcp.json");
407
+ const RULESYNC_HOOKS_LEGACY_RELATIVE_FILE_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, "hooks.json");
408
+ const RULESYNC_PERMISSIONS_LEGACY_RELATIVE_FILE_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, "permissions.json");
409
409
  const RULESYNC_AIIGNORE_FILE_NAME = ".aiignore";
410
- const RULESYNC_AIIGNORE_RELATIVE_FILE_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, ".aiignore");
410
+ const RULESYNC_AIIGNORE_RELATIVE_FILE_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, ".aiignore");
411
411
  const RULESYNC_IGNORE_RELATIVE_FILE_PATH = ".rulesyncignore";
412
412
  const RULESYNC_OVERVIEW_FILE_NAME = "overview.md";
413
- const RULESYNC_SKILLS_RELATIVE_DIR_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, SKILLS_FEATURE_SUBDIR);
414
- const RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH = join$357(RULESYNC_RELATIVE_DIR_PATH, CURATED_SKILLS_FEATURE_SUBDIR);
413
+ const RULESYNC_SKILLS_RELATIVE_DIR_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, SKILLS_FEATURE_SUBDIR);
414
+ const RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH = join$358(RULESYNC_RELATIVE_DIR_PATH, CURATED_SKILLS_FEATURE_SUBDIR);
415
415
  const RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH = "rulesync.lock";
416
416
  const RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH = "rulesync-npm.lock.json";
417
417
  const RULESYNC_MCP_FILE_NAME = "mcp.jsonc";
@@ -849,7 +849,8 @@ const skillsProcessorToolTargetTuple = [
849
849
  "zed",
850
850
  "zoocode",
851
851
  "dsh",
852
- "lettacode"
852
+ "lettacode",
853
+ "openclaw"
853
854
  ];
854
855
  const hooksProcessorToolTargetTuple = [
855
856
  "amp",
@@ -5205,7 +5206,8 @@ const HookDefinitionSchema = zod_mini.z.looseObject({
5205
5206
  asyncRewake: zod_mini.z.optional(zod_mini.z.boolean()),
5206
5207
  rewakeMessage: zod_mini.z.optional(safeString),
5207
5208
  rewakeSummary: zod_mini.z.optional(safeString),
5208
- continueOnBlock: zod_mini.z.optional(zod_mini.z.boolean())
5209
+ continueOnBlock: zod_mini.z.optional(zod_mini.z.boolean()),
5210
+ strictJsonOutput: zod_mini.z.optional(zod_mini.z.boolean())
5209
5211
  });
5210
5212
  /**
5211
5213
  * All canonical hook event names.
@@ -6846,41 +6848,55 @@ const JUNIE_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_JUNIE_EVENT_NAM
6846
6848
  /**
6847
6849
  * Map canonical camelCase event names to Mistral Vibe snake_case.
6848
6850
  *
6849
- * Vibe documents three hook events. The canonical `stop` and `subagentStop`
6850
- * events both map to Vibe's `post_agent` (fires after every assistant turn
6851
- * ending without pending tool calls); the adapter tells them apart with the
6852
- * hook's `match` on the agent name (`main` for the main agent).
6851
+ * The canonical `stop` and `subagentStop` events both map to Vibe's
6852
+ * `post_agent` (fires after every assistant turn ending without pending tool
6853
+ * calls); the adapter tells them apart with the hook's `match` on the agent
6854
+ * name (`main` for the main agent). v3.1.1 added `pre_agent`, `notification`,
6855
+ * `session_start` and `session_end`, and v3.1.3 added `pre_llm` and
6856
+ * `post_llm`.
6853
6857
  *
6854
- * These are the v2.21.0 names; the pre-2.21.0 spellings (`before_tool`,
6858
+ * These are the v2.21.0+ names; the pre-2.21.0 spellings (`before_tool`,
6855
6859
  * `after_tool`, `post_agent_turn`) are rejected by Vibe's strict `HookType`
6856
6860
  * enum.
6857
- * @see https://github.com/mistralai/mistral-vibe/blob/main/README.md
6861
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/hooks/models.py
6858
6862
  */
6859
6863
  const CANONICAL_TO_VIBE_EVENT_NAMES = {
6860
6864
  preToolUse: "pre_tool",
6861
6865
  postToolUse: "post_tool",
6862
6866
  stop: "post_agent",
6863
- subagentStop: "post_agent"
6867
+ subagentStop: "post_agent",
6868
+ beforeSubmitPrompt: "pre_agent",
6869
+ notification: "notification",
6870
+ sessionStart: "session_start",
6871
+ sessionEnd: "session_end",
6872
+ preModelInvocation: "pre_llm",
6873
+ postModelInvocation: "post_llm"
6864
6874
  };
6865
6875
  /**
6866
6876
  * Hook events supported by Mistral Vibe (mistral-vibe).
6867
6877
  *
6868
- * Vibe exposes three hook events in `.vibe/hooks.toml`: `pre_tool` ←
6869
- * `preToolUse`, `post_tool` ← `postToolUse`, and `post_agent` ← `stop` /
6870
- * `subagentStop`. `post_agent` fires after every assistant turn that ends
6871
- * without pending tool calls, for the main agent and (since v3.0.2) for every
6872
- * subagent. v3.0.3 lets a `post_agent` hook take a `match` on the agent that
6873
- * finished its turn: the reserved alias `main` selects the main agent, so
6874
- * canonical `stop` becomes `post_agent` with `match = "main"`, and a canonical
6875
- * `subagentStop` with a matcher becomes `post_agent` with that agent name as
6876
- * `match`. Only the tool events (`pre_tool`/`post_tool`) carry the `strict`
6877
- * flag. Only `type: "command"` hooks are relevant.
6878
- *
6879
- * v2.21.0 graduated hooks from experimental and renamed all three types
6880
- * (`before_tool` → `pre_tool`, `after_tool` → `post_tool`, `post_agent_turn` →
6881
- * `post_agent`). `HookType` is a strict enum, so an entry using an old name is
6882
- * rejected outright and reported as a `HookConfigIssue`.
6883
- * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.3/README.md
6878
+ * Vibe reads hooks from `.vibe/hooks.toml`: `pre_tool` ← `preToolUse`,
6879
+ * `post_tool` ← `postToolUse`, `post_agent` ← `stop` / `subagentStop`,
6880
+ * `pre_agent` ← `beforeSubmitPrompt`, `notification` ← `notification`,
6881
+ * `session_start` ← `sessionStart`, `session_end` ← `sessionEnd`, `pre_llm` ←
6882
+ * `preModelInvocation` and `post_llm` ← `postModelInvocation`.
6883
+ *
6884
+ * `post_agent`, `pre_agent`, `pre_llm` and `post_llm` take a `match` on the
6885
+ * agent whose turn it is: the reserved alias `main` selects the main agent, so
6886
+ * canonical `stop` and `beforeSubmitPrompt` are written with `match = "main"`.
6887
+ * `session_start` matches the source (`startup` / `resume` / `clear` /
6888
+ * `fork`), `session_end` the reason (`exit` / `clear` / `other`) and
6889
+ * `notification` the notification type (`approval_requested` /
6890
+ * `question_asked` / `turn_completed` / `turn_failed`). The `strict` flag is
6891
+ * valid on `pre_tool`, `post_tool`, `pre_agent`, `pre_llm` and `post_llm`
6892
+ * (`STRICT_HOOK_TYPES`). Only `type: "command"` hooks are relevant.
6893
+ *
6894
+ * v2.21.0 graduated hooks from experimental and renamed all three original
6895
+ * types (`before_tool` → `pre_tool`, `after_tool` → `post_tool`,
6896
+ * `post_agent_turn` → `post_agent`). `HookType` is a strict enum, so an entry
6897
+ * using an old name is rejected outright and reported as a `HookConfigIssue`.
6898
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/hooks/models.py
6899
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/plugins/builtins/vibe/skills/vibe/SKILL.md
6884
6900
  */
6885
6901
  const VIBE_HOOK_EVENTS = eventsOf(CANONICAL_TO_VIBE_EVENT_NAMES);
6886
6902
  /**
@@ -8450,6 +8466,31 @@ const ClaudecodePermissionsOverrideSchema = zod_mini.z.looseObject({
8450
8466
  sandbox: zod_mini.z.optional(zod_mini.z.looseObject({}))
8451
8467
  });
8452
8468
  /**
8469
+ * Tool-scoped override block for Command Code. The `permissions` object of
8470
+ * `.commandcode/settings.json` carries three documented non-list fields with
8471
+ * no canonical permission category: `defaultMode` (the session-start mode:
8472
+ * `default`, `accept-edits`, `plan`, `yolo` or `dont-ask`, plus the aliases
8473
+ * Command Code accepts such as `bypassPermissions` or `acceptEdits`),
8474
+ * `additionalDirectories` (extra directories treated as inside the workspace)
8475
+ * and `disableBypass` (`"disable"` or `true` makes `yolo` impossible to enter). Only
8476
+ * these three are written; the managed `allow`/`ask`/`deny` lists stay driven
8477
+ * by the shared `permission` block, and any other key placed here is ignored
8478
+ * with a warning. Values that widen trust are written with a warning.
8479
+ *
8480
+ * @example
8481
+ * { "permissions": { "defaultMode": "plan", "disableBypass": true } }
8482
+ * @see https://commandcode.ai/docs/permissions
8483
+ */
8484
+ const CommandcodePermissionsFieldsSchema = zod_mini.z.looseObject({
8485
+ defaultMode: zod_mini.z.optional(zod_mini.z.string()),
8486
+ additionalDirectories: zod_mini.z.optional(zod_mini.z.array(zod_mini.z.string())),
8487
+ disableBypass: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.literal("disable"), zod_mini.z.boolean()]))
8488
+ });
8489
+ const CommandcodePermissionsOverrideSchema = zod_mini.z.looseObject({
8490
+ permission: zod_mini.z.optional(ToolScopedPermissionSchema),
8491
+ permissions: zod_mini.z.optional(CommandcodePermissionsFieldsSchema)
8492
+ });
8493
+ /**
8453
8494
  * Tool-scoped override block for Mistral Vibe. Vibe's per-tool `BaseToolConfig`
8454
8495
  * carries a `sensitive_patterns` list — patterns that escalate to ASK even when
8455
8496
  * the tool's base permission is ALWAYS (allow). The canonical model can only set
@@ -9725,7 +9766,7 @@ const PermissionsConfigSchema = zod_mini.z.looseObject({
9725
9766
  continue: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9726
9767
  copilot: zod_mini.z.optional(CopilotPermissionsOverrideSchema),
9727
9768
  codebuddy: zod_mini.z.optional(CodebuddyPermissionsOverrideSchema),
9728
- commandcode: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9769
+ commandcode: zod_mini.z.optional(CommandcodePermissionsOverrideSchema),
9729
9770
  lettacode: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9730
9771
  crush: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9731
9772
  goose: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
@@ -11566,6 +11607,15 @@ const RulesyncSkillFrontmatterSchema = zod_mini.z.looseObject({
11566
11607
  "disable-model-invocation": zod_mini.z.optional(zod_mini.z.boolean()),
11567
11608
  "user-invocable": zod_mini.z.optional(zod_mini.z.boolean())
11568
11609
  })),
11610
+ openclaw: zod_mini.z.optional(zod_mini.z.looseObject({
11611
+ homepage: zod_mini.z.optional(zod_mini.z.string()),
11612
+ "user-invocable": zod_mini.z.optional(zod_mini.z.boolean()),
11613
+ "disable-model-invocation": zod_mini.z.optional(zod_mini.z.boolean()),
11614
+ "command-dispatch": zod_mini.z.optional(zod_mini.z.string()),
11615
+ "command-tool": zod_mini.z.optional(zod_mini.z.string()),
11616
+ "command-arg-mode": zod_mini.z.optional(zod_mini.z.string()),
11617
+ metadata: zod_mini.z.optional(zod_mini.z.looseObject({}))
11618
+ })),
11569
11619
  reasonix: zod_mini.z.optional(zod_mini.z.looseObject({
11570
11620
  invocation: zod_mini.z.optional(zod_mini.z.string()),
11571
11621
  "disable-model-invocation": zod_mini.z.optional(zod_mini.z.boolean()),
@@ -11645,6 +11695,13 @@ const RulesyncSkillFrontmatterSchema = zod_mini.z.looseObject({
11645
11695
  "when-to-use": zod_mini.z.optional(zod_mini.z.string()),
11646
11696
  paths: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.string(), zod_mini.z.array(zod_mini.z.string())]))
11647
11697
  })),
11698
+ firebender: zod_mini.z.optional(zod_mini.z.looseObject({
11699
+ version: zod_mini.z.optional(zod_mini.z.unknown()),
11700
+ autoTrigger: zod_mini.z.optional(zod_mini.z.boolean()),
11701
+ "disable-model-invocation": zod_mini.z.optional(zod_mini.z.boolean()),
11702
+ projectTypes: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.string(), zod_mini.z.array(zod_mini.z.string())])),
11703
+ icon: zod_mini.z.optional(zod_mini.z.string())
11704
+ })),
11648
11705
  zcode: zod_mini.z.optional(zod_mini.z.looseObject({
11649
11706
  when_to_use: zod_mini.z.optional(zod_mini.z.string()),
11650
11707
  license: zod_mini.z.optional(zod_mini.z.string()),
@@ -11934,9 +11991,9 @@ async function getLocalSkillDirNames(sourceTree) {
11934
11991
  * The rulesync skill frontmatter exposes a root-level `disable-model-invocation`
11935
11992
  * default that applies to every tool supporting the flag (claudecode, codebuddy, copilot,
11936
11993
  * copilotcli, crush, cursor, zed, pi, omp, qwencode, vibe, grokcli, factorydroid, dsh, reasonix,
11937
- * commandcode, lettacode, opencode, opencodev1, mimocode, xum). Each tool's own section may override that
11938
- * default with a per-target value. A defined section value (including `false`)
11939
- * always wins over the root default.
11994
+ * commandcode, lettacode, opencode, opencodev1, mimocode, xum, firebender). Each tool's own section
11995
+ * may override that default with a per-target value. A defined section value
11996
+ * (including `false`) always wins over the root default.
11940
11997
  *
11941
11998
  * `devin` also consumes the root-level value — it maps `true` onto a user-only
11942
11999
  * `triggers` list (see `devin-skill.ts`) — but has no section key of the same
@@ -17511,7 +17568,7 @@ const COMMANDCODE_SKILLS_DIR_PATH = (0, node_path.join)(COMMANDCODE_DIR, "skills
17511
17568
  * (Command Code would send it as prompt text; a rulesync command carries its
17512
17569
  * own frontmatter) and only the body is kept.
17513
17570
  *
17514
- * @see https://commandcode.ai/docs/custom-slash-commands
17571
+ * @see https://commandcode.ai/docs/reference/slash-commands#custom-slash-commands
17515
17572
  */
17516
17573
  var CommandcodeCommand = class CommandcodeCommand extends ToolCommand {
17517
17574
  static getSettablePaths(_options = {}) {
@@ -26459,18 +26516,86 @@ var FactorydroidSkill = class FactorydroidSkill extends ToolSkill {
26459
26516
  };
26460
26517
  // src/features/skills/firebender-skill.ts
26461
26518
  /**
26519
+ * The Agent Skills standard keys the `agentsskills` section carries. On import
26520
+ * they go back there, exactly as for the `agentsskills` target, and every other
26521
+ * key besides `name` / `description` goes into the `firebender` section.
26522
+ */
26523
+ const AGENT_SKILLS_STANDARD_KEYS$1 = /* @__PURE__ */ new Set([
26524
+ "name",
26525
+ "description",
26526
+ "license",
26527
+ "compatibility",
26528
+ "metadata",
26529
+ "allowed-tools"
26530
+ ]);
26531
+ /**
26462
26532
  * Firebender skills follow the Agent Skills layout (`<name>/SKILL.md` with the
26463
26533
  * required `name` and `description` frontmatter, plus optional supporting
26464
26534
  * files), so this target reuses {@link AgentsSkillsSkill} with Firebender's
26465
26535
  * recommended locations: `.firebender/skills/` (project) and
26466
26536
  * `~/.firebender/skills/` (user).
26467
26537
  *
26538
+ * On top of the standard fields, Firebender reads `version`, `autoTrigger`,
26539
+ * `disable-model-invocation` (the inverse of `autoTrigger`, which wins when
26540
+ * both are set), `projectTypes` and `icon`. Those come from the `firebender`
26541
+ * section of the rulesync skill and are written verbatim;
26542
+ * `disable-model-invocation` falls back to the root-level rulesync value.
26543
+ *
26468
26544
  * @see https://docs.firebender.com/api-reference/skills
26469
26545
  */
26470
- var FirebenderSkill = class extends AgentsSkillsSkill {
26546
+ var FirebenderSkill = class FirebenderSkill extends AgentsSkillsSkill {
26471
26547
  static getSettablePaths(_options = {}) {
26472
26548
  return { relativeDirPath: FIREBENDER_SKILLS_DIR_PATH };
26473
26549
  }
26550
+ toRulesyncSkill() {
26551
+ const base = super.toRulesyncSkill();
26552
+ const firebenderSection = Object.fromEntries(Object.entries(this.getFrontmatter()).filter(([key]) => !AGENT_SKILLS_STANDARD_KEYS$1.has(key)));
26553
+ if (Object.keys(firebenderSection).length === 0) return base;
26554
+ const rulesyncFrontmatter = {
26555
+ ...base.getFrontmatter(),
26556
+ firebender: firebenderSection
26557
+ };
26558
+ return this.toRulesyncSkillWith(rulesyncFrontmatter);
26559
+ }
26560
+ static fromRulesyncSkill({ outputRoot = process.cwd(), rulesyncSkill, validate = true, global = false, logger }) {
26561
+ const settablePaths = FirebenderSkill.getSettablePaths({ global });
26562
+ const rulesyncFrontmatter = rulesyncSkill.getFrontmatter();
26563
+ const dirName = rulesyncSkill.getDirName();
26564
+ const firebenderSection = {};
26565
+ const ignoredKeys = [];
26566
+ for (const [key, value] of Object.entries(rulesyncFrontmatter.firebender ?? {})) if (AGENT_SKILLS_STANDARD_KEYS$1.has(key)) ignoredKeys.push(key);
26567
+ else firebenderSection[key] = value;
26568
+ if (ignoredKeys.length > 0) warnWithFallback(logger, `${(0, node_path.join)(outputRoot, settablePaths.relativeDirPath, dirName, SKILL_FILE_NAME)}: the firebender section sets ${ignoredKeys.map(quoteValueForWarning).join(", ")}, which ${ignoredKeys.length === 1 ? "is" : "are"} ignored there; set name/description at the root and the Agent Skills standard fields at the root or in the agentsskills section.`);
26569
+ const disableModelInvocation = resolveDisableModelInvocation({
26570
+ rootFrontmatter: rulesyncFrontmatter,
26571
+ section: rulesyncFrontmatter.firebender
26572
+ });
26573
+ const frontmatter = {
26574
+ name: rulesyncFrontmatter.name,
26575
+ description: rulesyncFrontmatter.description,
26576
+ ...toSpecConformantAgentSkillFields(resolveAgentsSkillsSection(rulesyncFrontmatter)),
26577
+ ...firebenderSection,
26578
+ ...disableModelInvocation !== void 0 && { "disable-model-invocation": disableModelInvocation }
26579
+ };
26580
+ AgentsSkillsSkill.reportSpecViolations({
26581
+ outputRoot,
26582
+ relativeDirPath: settablePaths.relativeDirPath,
26583
+ dirName,
26584
+ frontmatter,
26585
+ sourceAllowedTools: rulesyncFrontmatter.agentsskills?.["allowed-tools"],
26586
+ logger
26587
+ });
26588
+ return new FirebenderSkill({
26589
+ outputRoot,
26590
+ relativeDirPath: settablePaths.relativeDirPath,
26591
+ dirName,
26592
+ frontmatter,
26593
+ body: rulesyncSkill.getBody(),
26594
+ otherFiles: rulesyncSkill.getOtherFiles(),
26595
+ validate,
26596
+ global
26597
+ });
26598
+ }
26474
26599
  static toolTarget = "firebender";
26475
26600
  };
26476
26601
  // src/features/skills/gitlabduo-skill.ts
@@ -26697,39 +26822,22 @@ var GrokcliSkill = class GrokcliSkill extends ToolSkill {
26697
26822
  return new GrokcliSkill(this.forDeletionParams(params));
26698
26823
  }
26699
26824
  };
26700
- // src/features/skills/junie-skill.ts
26701
- const JunieSkillFrontmatterSchema = zod_mini.z.looseObject({
26702
- name: zod_mini.z.string(),
26703
- description: zod_mini.z.string()
26704
- });
26825
+ // src/utils/markdown-paragraph.ts
26705
26826
  /** An ATX markdown heading line (`#` … `######`). */
26706
26827
  const HEADING_LINE = /^#{1,6}(\s|$)/;
26707
26828
  /**
26708
- * Junie's own fallback for a `SKILL.md` with no `description`: "If
26709
- * `description` is not provided in the frontmatter, Junie CLI extracts the
26710
- * first paragraph of the body content as the description." Headings do not
26711
- * count as that paragraph — "If the body is also empty or contains only
26712
- * headings, the skill will fail to load."
26713
- *
26714
- * This is import-only. The canonical `RulesyncSkillFrontmatter` requires a
26715
- * description, so without the fallback a skill Junie itself loads fine aborts
26716
- * the whole import; generation keeps emitting an explicit description, which
26717
- * the same docs recommend.
26718
- *
26719
- * Heading lines are therefore skipped rather than taken: a body opening with
26720
- * `# Skill Name` would otherwise import that title as the description and —
26721
- * because the next generate writes it out explicitly — replace Junie's own
26722
- * correct fallback with the wrong value everywhere, canonical config included.
26723
- *
26724
- * A paragraph runs to the first blank line or heading, and is collapsed onto
26725
- * one line because it becomes a YAML frontmatter value. A fenced code block is
26726
- * not treated specially: it is ordinary content, so a body whose first
26727
- * paragraph is a fence yields the fence text. Returns an empty string when the
26728
- * body holds no such paragraph, which the caller turns into a skipped skill.
26829
+ * The first non-heading paragraph of a Markdown body, collapsed onto one line.
26729
26830
  *
26730
- * @see https://junie.jetbrains.com/docs/agent-skills.html
26831
+ * JetBrains Junie falls back to this paragraph as the description of a skill
26832
+ * or subagent whose frontmatter omits one. Heading lines are skipped rather
26833
+ * than taken, so a body opening with `# Title` does not yield the title. A
26834
+ * paragraph runs to the first blank line or heading, and is collapsed onto one
26835
+ * line because callers store it as a YAML frontmatter value. A fenced code
26836
+ * block is not treated specially: it is ordinary content, so a body whose
26837
+ * first paragraph is a fence yields the fence text. Returns an empty string
26838
+ * when the body holds no such paragraph.
26731
26839
  */
26732
- function deriveDescriptionFromBody(body) {
26840
+ function firstNonHeadingParagraph(body) {
26733
26841
  const paragraph = [];
26734
26842
  for (const rawLine of body.split(/\r?\n/)) {
26735
26843
  const line = rawLine.trim();
@@ -26743,6 +26851,11 @@ function deriveDescriptionFromBody(body) {
26743
26851
  }
26744
26852
  return paragraph.join(" ").trim();
26745
26853
  }
26854
+ // src/features/skills/junie-skill.ts
26855
+ const JunieSkillFrontmatterSchema = zod_mini.z.looseObject({
26856
+ name: zod_mini.z.string(),
26857
+ description: zod_mini.z.string()
26858
+ });
26746
26859
  /**
26747
26860
  * Represents a JetBrains Junie skill directory.
26748
26861
  * Skills are stored under the .junie/skills directory with SKILL.md files.
@@ -26813,7 +26926,7 @@ var JunieSkill = class JunieSkill extends ToolSkill {
26813
26926
  });
26814
26927
  let frontmatter = loaded.frontmatter;
26815
26928
  if (isRecord(frontmatter) && frontmatter.description === void 0) {
26816
- const derived = deriveDescriptionFromBody(loaded.body);
26929
+ const derived = firstNonHeadingParagraph(loaded.body);
26817
26930
  if (derived === "") throw new Error(`Cannot import ${(0, node_path.join)(loaded.outputRoot, loaded.relativeDirPath, loaded.dirName, SKILL_FILE_NAME)}: it has no description and its body has no paragraph to derive one from, so Junie cannot load it either. Add a description to the frontmatter.`);
26818
26931
  frontmatter = {
26819
26932
  ...frontmatter,
@@ -27847,6 +27960,125 @@ var PiSkill = class extends ToolSkill {
27847
27960
  var OmpSkill = class extends PiSkill {
27848
27961
  static layout = OMP_LAYOUT;
27849
27962
  };
27963
+ // src/constants/openclaw-paths.ts
27964
+ const OPENCLAW_WORKSPACE_DIR_PATH = (0, node_path.join)(".openclaw", "workspace");
27965
+ const OPENCLAW_RULE_FILE_NAME = "AGENTS.md";
27966
+ const OPENCLAW_CONFIG_DIR_PATH = ".openclaw";
27967
+ const OPENCLAW_CONFIG_FILE_NAME = "openclaw.json";
27968
+ const OPENCLAW_MCP_SERVERS_KEY = "servers";
27969
+ const OPENCLAW_PROJECT_SKILLS_DIR_PATH = (0, node_path.join)(".agents", "skills");
27970
+ const OPENCLAW_GLOBAL_SKILLS_DIR_PATH = (0, node_path.join)(OPENCLAW_CONFIG_DIR_PATH, "skills");
27971
+ // src/features/skills/openclaw-skill.ts
27972
+ const OpenclawSkillFrontmatterSchema = zod_mini.z.looseObject({
27973
+ name: zod_mini.z.string(),
27974
+ description: zod_mini.z.string(),
27975
+ homepage: zod_mini.z.optional(zod_mini.z.string()),
27976
+ "user-invocable": zod_mini.z.optional(zod_mini.z.boolean()),
27977
+ "disable-model-invocation": zod_mini.z.optional(zod_mini.z.boolean()),
27978
+ "command-dispatch": zod_mini.z.optional(zod_mini.z.string()),
27979
+ "command-tool": zod_mini.z.optional(zod_mini.z.string()),
27980
+ "command-arg-mode": zod_mini.z.optional(zod_mini.z.string()),
27981
+ metadata: zod_mini.z.optional(zod_mini.z.looseObject({}))
27982
+ });
27983
+ /**
27984
+ * Represents an OpenClaw skill directory.
27985
+ *
27986
+ * Project mode writes the execution folder's `.agents/skills/<name>/SKILL.md`,
27987
+ * which OpenClaw loads when a session runs from that folder (the same mechanism
27988
+ * that loads the folder's `AGENTS.md`). Global mode writes the managed/local
27989
+ * `~/.openclaw/skills/<name>/SKILL.md` root, visible to every agent sharing the
27990
+ * default state directory. The execution folder's `skills/` and the personal
27991
+ * `~/.agents/skills` roots are left alone (see `openclaw-paths.ts`).
27992
+ *
27993
+ * Every key beyond `name`/`description` is carried in the `openclaw` section of
27994
+ * the rulesync skill; the two invocation flags and `metadata` fall back to the
27995
+ * shared root-level defaults when the section omits them.
27996
+ *
27997
+ * @see https://docs.openclaw.ai/tools/skills
27998
+ */
27999
+ var OpenclawSkill = class OpenclawSkill extends ToolSkill {
28000
+ constructor({ outputRoot = process.cwd(), relativeDirPath = OPENCLAW_PROJECT_SKILLS_DIR_PATH, dirName, frontmatter, body, otherFiles = [], validate = true, global = false }) {
28001
+ super({
28002
+ outputRoot,
28003
+ relativeDirPath,
28004
+ dirName,
28005
+ mainFile: {
28006
+ name: SKILL_FILE_NAME,
28007
+ body,
28008
+ frontmatter: { ...frontmatter }
28009
+ },
28010
+ otherFiles,
28011
+ global
28012
+ });
28013
+ if (validate) {
28014
+ const result = this.validate();
28015
+ if (!result.success) throw result.error;
28016
+ }
28017
+ }
28018
+ static getSettablePaths({ global = false } = {}) {
28019
+ return { relativeDirPath: global ? OPENCLAW_GLOBAL_SKILLS_DIR_PATH : OPENCLAW_PROJECT_SKILLS_DIR_PATH };
28020
+ }
28021
+ getFrontmatter() {
28022
+ return OpenclawSkillFrontmatterSchema.parse(this.requireMainFileFrontmatter());
28023
+ }
28024
+ validate() {
28025
+ return this.validateMainFileFrontmatter(OpenclawSkillFrontmatterSchema);
28026
+ }
28027
+ toRulesyncSkill() {
28028
+ const { name, description, ...section } = this.getFrontmatter();
28029
+ const rulesyncFrontmatter = {
28030
+ name,
28031
+ description,
28032
+ targets: ["*"],
28033
+ ...Object.keys(section).length > 0 && { openclaw: section }
28034
+ };
28035
+ return this.toRulesyncSkillWith(rulesyncFrontmatter);
28036
+ }
28037
+ static fromRulesyncSkill({ outputRoot = process.cwd(), rulesyncSkill, validate = true, global = false }) {
28038
+ const rulesyncFrontmatter = rulesyncSkill.getFrontmatter();
28039
+ const { name: _sectionName, description: _sectionDescription, ...section } = rulesyncFrontmatter.openclaw ?? {};
28040
+ const disableModelInvocation = resolveDisableModelInvocation({
28041
+ rootFrontmatter: rulesyncFrontmatter,
28042
+ section
28043
+ });
28044
+ const userInvocable = resolveUserInvocable({
28045
+ rootFrontmatter: rulesyncFrontmatter,
28046
+ section
28047
+ });
28048
+ const metadata = resolveMetadata({
28049
+ rootFrontmatter: rulesyncFrontmatter,
28050
+ section
28051
+ });
28052
+ const frontmatter = {
28053
+ ...section,
28054
+ name: rulesyncFrontmatter.name,
28055
+ description: rulesyncFrontmatter.description,
28056
+ ...metadata !== void 0 && { metadata },
28057
+ ...disableModelInvocation !== void 0 && { "disable-model-invocation": disableModelInvocation },
28058
+ ...userInvocable !== void 0 && { "user-invocable": userInvocable }
28059
+ };
28060
+ return new OpenclawSkill({
28061
+ outputRoot,
28062
+ relativeDirPath: OpenclawSkill.getSettablePaths({ global }).relativeDirPath,
28063
+ dirName: rulesyncSkill.getDirName(),
28064
+ frontmatter,
28065
+ body: rulesyncSkill.getBody(),
28066
+ otherFiles: rulesyncSkill.getOtherFiles(),
28067
+ validate,
28068
+ global
28069
+ });
28070
+ }
28071
+ static toolTarget = "openclaw";
28072
+ static async fromDir(params) {
28073
+ return new OpenclawSkill(await this.loadStandardSkillParams({
28074
+ params,
28075
+ schema: OpenclawSkillFrontmatterSchema
28076
+ }));
28077
+ }
28078
+ static forDeletion(params) {
28079
+ return new OpenclawSkill(this.forDeletionParams(params));
28080
+ }
28081
+ };
27850
28082
  // src/features/skills/opencodev1-skill.ts
27851
28083
  /**
27852
28084
  * Skill generator for **OpenCode V1** (OpenCode 1.x). Skills live in the same
@@ -29910,6 +30142,14 @@ const toolSkillFactories = /* @__PURE__ */ new Map([
29910
30142
  supportsSimulated: false,
29911
30143
  supportsGlobal: true
29912
30144
  }
30145
+ }],
30146
+ ["openclaw", {
30147
+ class: OpenclawSkill,
30148
+ meta: {
30149
+ supportsProject: true,
30150
+ supportsSimulated: false,
30151
+ supportsGlobal: true
30152
+ }
29913
30153
  }]
29914
30154
  ]);
29915
30155
  const defaultGetFactory$5 = (target) => {
@@ -32403,7 +32643,7 @@ function warnAboutReservedAgentName({ name, relativeFilePath, logger }) {
32403
32643
  * `.commandcode/agents/` (project) or `~/.commandcode/agents/` (user); the
32404
32644
  * body is the agent's system prompt.
32405
32645
  *
32406
- * @see https://commandcode.ai/docs/custom-agents
32646
+ * @see https://commandcode.ai/docs/agents
32407
32647
  */
32408
32648
  var CommandcodeSubagent = class extends FrontmatterMarkdownToolSubagent {
32409
32649
  static getSettablePaths(_options = {}) {
@@ -34157,7 +34397,7 @@ var HermesagentSubagent = class HermesagentSubagent extends ToolSubagent {
34157
34397
  */
34158
34398
  const JunieSubagentFrontmatterSchema = zod_mini.z.looseObject({
34159
34399
  name: zod_mini.z.optional(zod_mini.z.string()),
34160
- description: zod_mini.z.string(),
34400
+ description: zod_mini.z.optional(zod_mini.z.string()),
34161
34401
  tools: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.string(), zod_mini.z.array(zod_mini.z.string())])),
34162
34402
  disallowedTools: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.string(), zod_mini.z.array(zod_mini.z.string())])),
34163
34403
  mcpServers: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.string(), zod_mini.z.array(zod_mini.z.string())])),
@@ -34168,6 +34408,34 @@ const JunieSubagentFrontmatterSchema = zod_mini.z.looseObject({
34168
34408
  skills: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.string(), zod_mini.z.array(zod_mini.z.string())])),
34169
34409
  allowPromptArgument: zod_mini.z.optional(zod_mini.z.boolean())
34170
34410
  });
34411
+ /** Junie truncates a body-derived subagent description to this many characters. */
34412
+ const JUNIE_DERIVED_DESCRIPTION_MAX_LENGTH = 1024;
34413
+ /**
34414
+ * Junie's fallback when a subagent's frontmatter has no `description`: the
34415
+ * first non-heading paragraph of the body, truncated to 1,024 characters.
34416
+ * Returns `undefined` when the body has no such paragraph.
34417
+ *
34418
+ * @see https://junie.jetbrains.com/docs/junie-cli-subagents.html
34419
+ */
34420
+ function deriveDescriptionFromBody(body) {
34421
+ const paragraph = firstNonHeadingParagraph(body);
34422
+ if (paragraph === "") return void 0;
34423
+ return truncateText({
34424
+ text: paragraph,
34425
+ maxLength: JUNIE_DERIVED_DESCRIPTION_MAX_LENGTH,
34426
+ suffix: ""
34427
+ });
34428
+ }
34429
+ function isMissingDescription(value) {
34430
+ return value === void 0 || value === null || typeof value === "string" && value.trim() === "";
34431
+ }
34432
+ /**
34433
+ * Junie's fallback subagent name: the file name without its `.agent.md` or
34434
+ * `.md` extension.
34435
+ */
34436
+ function nameFromFileName(relativeFilePath) {
34437
+ return relativeFilePath.replace(/(\.agent)?\.md$/, "");
34438
+ }
34171
34439
  var JunieSubagent = class JunieSubagent extends ToolSubagent {
34172
34440
  frontmatter;
34173
34441
  body;
@@ -34199,8 +34467,8 @@ var JunieSubagent = class JunieSubagent extends ToolSubagent {
34199
34467
  outputRoot: ".",
34200
34468
  frontmatter: {
34201
34469
  targets: ["*"],
34202
- name: name ?? this.getRelativeFilePath().replace(/\.md$/, ""),
34203
- description,
34470
+ name: name ?? nameFromFileName(this.getRelativeFilePath()),
34471
+ ...description !== void 0 && { description },
34204
34472
  ...Object.keys(junieSection).length > 0 && { junie: junieSection }
34205
34473
  },
34206
34474
  body: this.body,
@@ -34259,7 +34527,16 @@ var JunieSubagent = class JunieSubagent extends ToolSubagent {
34259
34527
  const dirPath = relativeDirPath ?? this.getSettablePaths({ global }).relativeDirPath;
34260
34528
  const filePath = (0, node_path.join)(outputRoot, dirPath, relativeFilePath);
34261
34529
  const fileContent = await readFileContent(filePath);
34262
- const { frontmatter, body: content } = parseFrontmatter(fileContent, filePath);
34530
+ const { frontmatter: parsedFrontmatter, body: content } = parseFrontmatter(fileContent, filePath);
34531
+ let frontmatter = parsedFrontmatter;
34532
+ if (isRecord(frontmatter) && isMissingDescription(frontmatter.description)) {
34533
+ const { description: _missing, ...rest } = frontmatter;
34534
+ const derived = deriveDescriptionFromBody(content);
34535
+ frontmatter = derived === void 0 ? rest : {
34536
+ ...rest,
34537
+ description: derived
34538
+ };
34539
+ }
34263
34540
  const result = JunieSubagentFrontmatterSchema.safeParse(frontmatter);
34264
34541
  if (!result.success) throw new Error(`Invalid frontmatter in ${filePath}: ${formatError(result.error)}`);
34265
34542
  return new JunieSubagent({
@@ -46081,12 +46358,6 @@ var OmpRule = class OmpRule extends ToolRule {
46081
46358
  }
46082
46359
  static toolTarget = "omp";
46083
46360
  };
46084
- // src/constants/openclaw-paths.ts
46085
- const OPENCLAW_WORKSPACE_DIR_PATH = (0, node_path.join)(".openclaw", "workspace");
46086
- const OPENCLAW_RULE_FILE_NAME = "AGENTS.md";
46087
- const OPENCLAW_CONFIG_DIR_PATH = ".openclaw";
46088
- const OPENCLAW_CONFIG_FILE_NAME = "openclaw.json";
46089
- const OPENCLAW_MCP_SERVERS_KEY = "servers";
46090
46361
  // src/features/rules/openclaw-rule.ts
46091
46362
  /**
46092
46363
  * Rule generator for OpenClaw, the always-on assistant gateway.
@@ -54616,12 +54887,23 @@ function toolMatcherEntryToCanonical({ rawEntry, eventName, converterConfig, war
54616
54887
  * tool-native keys through verbatim — so documented native triggers (e.g.
54617
54888
  * kiro-ide's `PostFileSave`) survive an import → generate round-trip instead
54618
54889
  * of failing canonical validation.
54890
+ *
54891
+ * An event key named `__proto__`, `constructor` or `prototype` is dropped with
54892
+ * a warning: no tool documents such an event, and carrying it into
54893
+ * `.rulesync/hooks.jsonc` would make the next `generate` fail the
54894
+ * prototype-pollution key validation.
54619
54895
  */
54620
- function buildImportedHooksConfig({ hooks, overrideKey, version = 1, extraOverride }) {
54896
+ function buildImportedHooksConfig({ hooks, overrideKey, version = 1, extraOverride, logger }) {
54621
54897
  const canonical = {};
54622
54898
  const native = {};
54623
- for (const [event, defs] of Object.entries(hooks)) if (isHookEvent(event)) canonical[event] = defs;
54624
- else native[event] = defs;
54899
+ for (const [event, defs] of Object.entries(hooks)) {
54900
+ if (isPrototypePollutionKey(event)) {
54901
+ logger?.warn(`Skipping imported ${overrideKey} hooks event ${quoteValueForWarning(event)}: reserved key names cannot be used as hook events.`);
54902
+ continue;
54903
+ }
54904
+ if (isHookEvent(event)) canonical[event] = defs;
54905
+ else native[event] = defs;
54906
+ }
54625
54907
  const override = { ...extraOverride };
54626
54908
  if (Object.keys(native).length > 0) override.hooks = native;
54627
54909
  const config = {
@@ -54871,6 +55153,7 @@ var AntigravityHooks = class extends ToolHooks {
54871
55153
  });
54872
55154
  const overrideKey = this.constructor.getOverrideKey();
54873
55155
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
55156
+ logger,
54874
55157
  hooks,
54875
55158
  overrideKey
54876
55159
  }), null, 2) });
@@ -55255,6 +55538,7 @@ var AugmentcodeHooks = class AugmentcodeHooks extends ToolHooks {
55255
55538
  converterConfig: AUGMENTCODE_CONVERTER_CONFIG
55256
55539
  });
55257
55540
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
55541
+ logger,
55258
55542
  hooks,
55259
55543
  overrideKey: "augmentcode"
55260
55544
  }), null, 2) });
@@ -55331,6 +55615,7 @@ var AugmentcodePluginHooks = class AugmentcodePluginHooks extends ToolHooks {
55331
55615
  converterConfig: AUGMENTCODE_PLUGIN_CONVERTER_CONFIG
55332
55616
  });
55333
55617
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
55618
+ logger,
55334
55619
  hooks,
55335
55620
  overrideKey: "augmentcode"
55336
55621
  }), null, 2) });
@@ -55892,6 +56177,7 @@ var SettingsJsonHooks = class extends ToolHooks {
55892
56177
  converterConfig: ctor.getConverterConfig()
55893
56178
  });
55894
56179
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
56180
+ logger,
55895
56181
  hooks,
55896
56182
  overrideKey: spec.overrideKey
55897
56183
  }), null, 2) });
@@ -56685,13 +56971,14 @@ var CodewhaleHooks = class CodewhaleHooks extends ToolHooks {
56685
56971
  global
56686
56972
  });
56687
56973
  }
56688
- toRulesyncHooks() {
56974
+ toRulesyncHooks({ logger } = {}) {
56689
56975
  const parsed = this.parseFileContentOrThrow({
56690
56976
  displayName: "Codewhale",
56691
56977
  parse: (fileContent) => parseCodewhaleToml(fileContent)
56692
56978
  });
56693
56979
  const rawHooks = this.global ? isPlainObject(parsed.hooks) ? parsed.hooks.hooks : void 0 : parsed.hooks;
56694
56980
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
56981
+ logger,
56695
56982
  hooks: codewhaleHooksToCanonical(rawHooks),
56696
56983
  overrideKey: "codewhale"
56697
56984
  }), null, 2) });
@@ -56929,6 +57216,7 @@ var CodexcliHooks = class CodexcliHooks extends ToolHooks {
56929
57216
  logger
56930
57217
  });
56931
57218
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
57219
+ logger,
56932
57220
  hooks,
56933
57221
  overrideKey: "codexcli"
56934
57222
  }), null, 2) });
@@ -57025,6 +57313,7 @@ var CommandcodeHooks = class CommandcodeHooks extends ToolHooks {
57025
57313
  converterConfig: COMMANDCODE_CONVERTER_CONFIG
57026
57314
  });
57027
57315
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
57316
+ logger,
57028
57317
  hooks,
57029
57318
  overrideKey: "commandcode"
57030
57319
  }), null, 2) });
@@ -57324,6 +57613,7 @@ var CopilotHooks = class CopilotHooks extends ToolHooks {
57324
57613
  parse: (fileContent) => JSON.parse(fileContent)
57325
57614
  }).hooks, options?.logger);
57326
57615
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
57616
+ logger: options?.logger,
57327
57617
  hooks,
57328
57618
  overrideKey: "copilot"
57329
57619
  }), null, 2) });
@@ -57776,6 +58066,7 @@ var CopilotcliHooks = class CopilotcliHooks extends ToolHooks {
57776
58066
  parse: (fileContent) => JSON.parse(fileContent)
57777
58067
  }).hooks, options?.logger);
57778
58068
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
58069
+ logger: options?.logger,
57779
58070
  hooks,
57780
58071
  overrideKey: "copilotcli",
57781
58072
  ...this.disableAllHooks !== void 0 && { extraOverride: { disableAllHooks: this.disableAllHooks } }
@@ -58221,9 +58512,10 @@ var CrushHooks = class CrushHooks extends ToolHooks {
58221
58512
  global
58222
58513
  });
58223
58514
  }
58224
- toRulesyncHooks() {
58515
+ toRulesyncHooks({ logger } = {}) {
58225
58516
  const hooks = crushHooksToCanonical(this.json[CRUSH_HOOKS_KEY]);
58226
58517
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
58518
+ logger,
58227
58519
  hooks,
58228
58520
  overrideKey: "crush"
58229
58521
  }), null, 2) });
@@ -58320,7 +58612,7 @@ var CursorHooks = class CursorHooks extends ToolHooks {
58320
58612
  static supportsPreserveUnowned() {
58321
58613
  return true;
58322
58614
  }
58323
- toRulesyncHooks() {
58615
+ toRulesyncHooks({ logger } = {}) {
58324
58616
  const content = this.getFileContent();
58325
58617
  const parsed = JSON.parse(content);
58326
58618
  const cursorHooks = parsed.hooks ?? {};
@@ -58334,6 +58626,7 @@ var CursorHooks = class CursorHooks extends ToolHooks {
58334
58626
  }
58335
58627
  const version = parsed.version ?? 1;
58336
58628
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
58629
+ logger,
58337
58630
  hooks: canonicalHooks,
58338
58631
  overrideKey: "cursor",
58339
58632
  version
@@ -58351,6 +58644,22 @@ var CursorHooks = class CursorHooks extends ToolHooks {
58351
58644
  };
58352
58645
  // src/features/hooks/deepagents-hooks.ts
58353
58646
  /**
58647
+ * deepagents-code 0.2.11+ spells the canonical `failClosed` as a per-handler
58648
+ * `onError: "continue" | "deny"`. Only `"deny"` changes behavior: a failed,
58649
+ * timed-out or invalid-output `PreToolUse` handler then denies the tool call.
58650
+ * `"continue"` is the default, so `false` is omitted; upstream ignores the
58651
+ * field on every other event, so a `true` there is dropped with a warning.
58652
+ * Older dcode versions ignore the field and keep failing open.
58653
+ * https://github.com/langchain-ai/deepagents/blob/main/libs/code/HOOKS.md
58654
+ */
58655
+ const DEEPAGENTS_KEYWORD_FIELDS = [{
58656
+ canonical: "failClosed",
58657
+ tool: "onError",
58658
+ trueValue: "deny",
58659
+ falseValue: "continue",
58660
+ events: /* @__PURE__ */ new Set(["preToolUse"])
58661
+ }];
58662
+ /**
58354
58663
  * Convert the canonical hooks config to the deepagents Hooks v2 document.
58355
58664
  *
58356
58665
  * ```json
@@ -58360,7 +58669,8 @@ var CursorHooks = class CursorHooks extends ToolHooks {
58360
58669
  * Definitions sharing an event and matcher land in one group, preserving their
58361
58670
  * authored order — upstream runs a group's handlers in sequence.
58362
58671
  */
58363
- function canonicalToDeepagentsHooks(config) {
58672
+ function canonicalToDeepagentsHooks(config, logger) {
58673
+ const warn = warnOnce(logger);
58364
58674
  const supported = new Set(DEEPAGENTS_HOOK_EVENTS);
58365
58675
  const effectiveHooks = {
58366
58676
  ...config.hooks,
@@ -58383,6 +58693,13 @@ function canonicalToDeepagentsHooks(config) {
58383
58693
  };
58384
58694
  if (def.timeout !== void 0 && def.timeout !== null && def.timeout > 0) handler.timeout = def.timeout;
58385
58695
  if (def.statusMessage !== void 0 && def.statusMessage !== null) handler.statusMessage = def.statusMessage;
58696
+ Object.assign(handler, emitKeywordFields({
58697
+ def,
58698
+ hookType: "command",
58699
+ eventName: canonicalEvent,
58700
+ fields: DEEPAGENTS_KEYWORD_FIELDS,
58701
+ warn
58702
+ }));
58386
58703
  const matcher = def.matcher !== void 0 && def.matcher !== null && def.matcher !== "" ? def.matcher : void 0;
58387
58704
  const groups = hooks[deepagentsEvent] ??= [];
58388
58705
  const group = groups.find((candidate) => candidate.matcher === matcher);
@@ -58398,7 +58715,8 @@ function canonicalToDeepagentsHooks(config) {
58398
58715
  /**
58399
58716
  * Convert the Hooks v2 document back to the canonical hooks record.
58400
58717
  */
58401
- function deepagentsToCanonicalHooks(hooks) {
58718
+ function deepagentsToCanonicalHooks(hooks, logger) {
58719
+ const warn = warnOnce(logger);
58402
58720
  const canonical = {};
58403
58721
  for (const [deepagentsEvent, groups] of Object.entries(hooks)) {
58404
58722
  const canonicalEvent = lookupOwn({
@@ -58417,6 +58735,19 @@ function deepagentsToCanonicalHooks(hooks) {
58417
58735
  if (typeof group.matcher === "string" && group.matcher !== "") def.matcher = group.matcher;
58418
58736
  if (typeof handler.timeout === "number") def.timeout = handler.timeout;
58419
58737
  if (typeof handler.statusMessage === "string") def.statusMessage = handler.statusMessage;
58738
+ let keywordSource = handler;
58739
+ if (canonicalEvent === "preToolUse" && handler.onError !== void 0 && handler.onError !== "deny" && handler.onError !== "continue") {
58740
+ warn(`Dropping "onError" from an imported "command" hook on "${canonicalEvent}": ${quoteValueForWarning(handler.onError)} is not "deny" or "continue", so the hook is imported without "failClosed" and fails open on the next generate.`);
58741
+ const { onError: _dropped, ...rest } = handler;
58742
+ keywordSource = rest;
58743
+ }
58744
+ Object.assign(def, importKeywordFields({
58745
+ h: keywordSource,
58746
+ hookType: "command",
58747
+ eventName: canonicalEvent,
58748
+ fields: DEEPAGENTS_KEYWORD_FIELDS,
58749
+ warn
58750
+ }));
58420
58751
  (canonical[canonicalEvent] ??= []).push(def);
58421
58752
  }
58422
58753
  }
@@ -58475,8 +58806,8 @@ var DeepagentsHooks = class DeepagentsHooks extends ToolHooks {
58475
58806
  global
58476
58807
  });
58477
58808
  }
58478
- static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false }) {
58479
- const hooks = canonicalToDeepagentsHooks(rulesyncHooks.getJson());
58809
+ static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false, logger }) {
58810
+ const hooks = canonicalToDeepagentsHooks(rulesyncHooks.getJson(), logger);
58480
58811
  const fileContent = JSON.stringify({ hooks }, null, 2);
58481
58812
  const paths = DeepagentsHooks.getSettablePaths({ global });
58482
58813
  return new DeepagentsHooks({
@@ -58487,19 +58818,20 @@ var DeepagentsHooks = class DeepagentsHooks extends ToolHooks {
58487
58818
  validate
58488
58819
  });
58489
58820
  }
58490
- toRulesyncHooks() {
58821
+ toRulesyncHooks({ logger } = {}) {
58491
58822
  const parsed = this.parseFileContentOrThrow({
58492
58823
  displayName: "deepagents",
58493
58824
  parse: (fileContent) => JSON.parse(fileContent)
58494
58825
  });
58495
58826
  const rawHooks = isRecord(parsed) ? parsed.hooks : void 0;
58496
- const hooks = Array.isArray(rawHooks) ? deepagentsLegacyToCanonicalHooks(rawHooks) : isRecord(rawHooks) ? deepagentsToCanonicalHooks(rawHooks) : {};
58827
+ const hooks = Array.isArray(rawHooks) ? deepagentsLegacyToCanonicalHooks(rawHooks) : isRecord(rawHooks) ? deepagentsToCanonicalHooks(rawHooks, logger) : {};
58497
58828
  return this.toRulesyncHooksDefault({
58498
58829
  outputRoot: getDeepagentsRulesyncOutputRoot({
58499
58830
  nativeOutputRoot: this.outputRoot,
58500
58831
  global: this.global
58501
58832
  }),
58502
58833
  fileContent: JSON.stringify(buildImportedHooksConfig({
58834
+ logger,
58503
58835
  hooks,
58504
58836
  overrideKey: "deepagents"
58505
58837
  }), null, 2)
@@ -58605,6 +58937,7 @@ var DevinHooks = class extends ToolHooks {
58605
58937
  logger
58606
58938
  });
58607
58939
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
58940
+ logger,
58608
58941
  hooks,
58609
58942
  overrideKey: "devin"
58610
58943
  }), null, 2) });
@@ -58830,6 +59163,7 @@ var FactorydroidHooks = class FactorydroidHooks extends ToolHooks {
58830
59163
  logger
58831
59164
  });
58832
59165
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59166
+ logger,
58833
59167
  hooks,
58834
59168
  overrideKey: "factorydroid"
58835
59169
  }), null, 2) });
@@ -58914,9 +59248,10 @@ var FirebenderHooks = class FirebenderHooks extends ToolHooks {
58914
59248
  static supportsPreserveUnowned() {
58915
59249
  return true;
58916
59250
  }
58917
- toRulesyncHooks() {
59251
+ toRulesyncHooks({ logger } = {}) {
58918
59252
  const parsed = JSON.parse(this.getFileContent());
58919
59253
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59254
+ logger,
58920
59255
  hooks: parsed.hooks ?? {},
58921
59256
  overrideKey: "firebender",
58922
59257
  version: parsed.version ?? 1
@@ -58984,6 +59319,7 @@ var GitlabduoHooks = class GitlabduoHooks extends ToolHooks {
58984
59319
  logger
58985
59320
  });
58986
59321
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59322
+ logger,
58987
59323
  hooks,
58988
59324
  overrideKey: "gitlabduo"
58989
59325
  }), null, 2) });
@@ -59053,6 +59389,7 @@ var GooseHooks = class GooseHooks extends ToolHooks {
59053
59389
  logger
59054
59390
  });
59055
59391
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59392
+ logger,
59056
59393
  hooks,
59057
59394
  overrideKey: "goose"
59058
59395
  }), null, 2) });
@@ -59135,6 +59472,7 @@ var GrokcliHooks = class GrokcliHooks extends ToolHooks {
59135
59472
  logger
59136
59473
  });
59137
59474
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59475
+ logger,
59138
59476
  hooks,
59139
59477
  overrideKey: "grokcli"
59140
59478
  }), null, 2) });
@@ -59428,7 +59766,7 @@ var HermesagentHooks = class HermesagentHooks extends ToolHooks {
59428
59766
  }) }
59429
59767
  });
59430
59768
  }
59431
- toRulesyncHooks() {
59769
+ toRulesyncHooks({ logger } = {}) {
59432
59770
  const hooks = hermesHooksToCanonical(parseSharedConfig({
59433
59771
  format: "yaml",
59434
59772
  fileContent: this.getFileContent()
@@ -59439,6 +59777,7 @@ var HermesagentHooks = class HermesagentHooks extends ToolHooks {
59439
59777
  global: this.global
59440
59778
  }),
59441
59779
  fileContent: JSON.stringify(buildImportedHooksConfig({
59780
+ logger,
59442
59781
  hooks,
59443
59782
  overrideKey: "hermesagent"
59444
59783
  }), null, 2)
@@ -59468,13 +59807,20 @@ const JUNIE_CONVERTER_CONFIG = {
59468
59807
  projectDirVar: "",
59469
59808
  supportedHookTypes: /* @__PURE__ */ new Set(["command"]),
59470
59809
  noMatcherEvents: /* @__PURE__ */ new Set(["beforeSubmitPrompt", "stop"]),
59471
- booleanPassthroughFields: [{
59472
- canonical: "failClosed",
59473
- tool: "blockOnError"
59474
- }, {
59475
- canonical: "async",
59476
- tool: "async"
59477
- }]
59810
+ booleanPassthroughFields: [
59811
+ {
59812
+ canonical: "failClosed",
59813
+ tool: "blockOnError"
59814
+ },
59815
+ {
59816
+ canonical: "async",
59817
+ tool: "async"
59818
+ },
59819
+ {
59820
+ canonical: "strictJsonOutput",
59821
+ tool: "strictJsonOutput"
59822
+ }
59823
+ ]
59478
59824
  };
59479
59825
  var JunieHooks = class JunieHooks extends ToolHooks {
59480
59826
  isDeletable() {
@@ -59526,6 +59872,7 @@ var JunieHooks = class JunieHooks extends ToolHooks {
59526
59872
  logger
59527
59873
  });
59528
59874
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59875
+ logger,
59529
59876
  hooks,
59530
59877
  overrideKey: "junie"
59531
59878
  }), null, 2) });
@@ -59664,33 +60011,255 @@ const SHELL_EVENT_TOOL_GATES = {
59664
60011
  }
59665
60012
  };
59666
60013
  /**
59667
- * Canonical events whose command receives a Claude Code-style JSON payload on
59668
- * stdin and whose result can deny the call, mapped to the `hook_event_name`
59669
- * the payload carries. Only `preToolUse` (`tool.execute.before`) takes part:
59670
- * it is the one named hook where throwing aborts the call — OpenCode rejects
59671
- * the tool call and returns the error message to the model (the `.env`
59672
- * protection example in the plugins doc).
59673
- *
59674
- * The payload mirrors Claude Code's `PreToolUse` input: `hook_event_name`,
59675
- * `session_id` (`input.sessionID`), `tool_use_id` (`input.callID`),
59676
- * `tool_name` (the raw OpenCode tool name — `bash`, `edit`, `<server>_<tool>`
59677
- * for MCP — the same subject a `matcher` is tested against), `tool_input`
59678
- * (`output.args`) and `cwd` (the plugin context's `directory`, falling back to
59679
- * `process.cwd()`). It is serialized lazily, on the first handler whose
59680
- * matcher matches, so a tool call no hook applies to pays nothing for it.
59681
- *
59682
- * Bun Shell has no stdin option on a command and rejects redirections on a
59683
- * subshell, so the payload is piped in by the shell's builtin `echo`
59684
- * (`echo ${payload} | <command>`); Bun escapes the interpolated value, so the
59685
- * payload never reaches the shell as syntax. The pipe feeds the first
59686
- * pipeline of the command — a compound `a && b` or `a; b` gives the payload
59687
- * to `a` only, so multi-step guards belong in a script.
60014
+ * Canonical events whose command receives Claude Code's JSON input for the
60015
+ * event on stdin (every other command gets an empty stdin), with the fields
60016
+ * besides `hook_event_name` and `cwd`. `tool_name` is the raw OpenCode tool
60017
+ * name, the subject a `matcher` is tested against. A payload is serialized
60018
+ * lazily, once per invocation, by the first handler that runs.
59688
60019
  *
59689
60020
  * @see https://opencode.ai/docs/plugins/
59690
60021
  * @see https://bun.sh/docs/runtime/shell
59691
60022
  * @see https://code.claude.com/docs/en/hooks
59692
60023
  */
59693
- const STDIN_PAYLOAD_EVENTS = { preToolUse: "PreToolUse" };
60024
+ const STDIN_PAYLOADS = {
60025
+ preToolUse: {
60026
+ name: "PreToolUse",
60027
+ fields: [
60028
+ "session_id: input.sessionID",
60029
+ "tool_use_id: input.callID",
60030
+ "tool_name: input.tool",
60031
+ "tool_input: output?.args"
60032
+ ]
60033
+ },
60034
+ postToolUse: {
60035
+ name: "PostToolUse",
60036
+ fields: [
60037
+ "session_id: input.sessionID",
60038
+ "tool_use_id: input.callID",
60039
+ "tool_name: input.tool",
60040
+ "tool_input: input.args",
60041
+ "tool_response: output"
60042
+ ]
60043
+ },
60044
+ stop: {
60045
+ name: "Stop",
60046
+ fields: ["session_id: event.properties?.sessionID"]
60047
+ }
60048
+ };
60049
+ /**
60050
+ * V1 hooks that run before the action they belong to — every named hook but
60051
+ * `tool.execute.after`: like the Bun Shell call earlier versions emitted, a
60052
+ * failing command throws there, which aborts the action. Everywhere else a
60053
+ * failure is only logged.
60054
+ */
60055
+ const BLOCKING_HOOKS = new Set(Object.keys(NAMED_HOOK_MATCHER_SUBJECTS).filter((hook) => hook !== "tool.execute.after"));
60056
+ /**
60057
+ * Helpers of every plugin with a handler. Bun Shell cannot give a command a
60058
+ * stdin of its own, and one that inherits OpenCode's (the TTY, or the pipe of
60059
+ * `opencode serve --stdio`) blocks forever once any part of it reads stdin. So
60060
+ * `__rulesyncRunCommand` runs the command in the host's own Bun-compiled binary
60061
+ * as the Bun CLI (`BUN_BE_BUN=1`, without the project's `.env`): `exec` runs it
60062
+ * with the same Bun Shell, parsing the text the template literal of earlier
60063
+ * versions held, with the payload as stdin. The script clears `BUN_BE_BUN` for
60064
+ * the programs the command starts: Bun Shell has no `unset`, so it exports an
60065
+ * empty value, which Bun treats as unset (only a non-empty value other than
60066
+ * `0` makes a Bun-compiled binary act as the Bun CLI). A host without the Bun
60067
+ * CLI fails the probe and falls back to Bun Shell, piping the payload into the
60068
+ * first command only (a probe still running after 10 s is killed; it, a
60069
+ * failing one or one that prints anything but `rulesync` means no Bun CLI for
60070
+ * 5 minutes). Ordinary commands write to the host's stdout and stderr, as Bun
60071
+ * Shell echoed them; a `preToolUse` command's are read, 1 MiB each kept (more
60072
+ * stdout denies; on the Bun Shell fallback the whole output is buffered before
60073
+ * that check). Output
60074
+ * pipes a background process keeps open are read for 1 s after the command
60075
+ * exits; what arrived by then is kept, and the reads are then cancelled, as
60076
+ * they are at a timeout. The OpenCode 1.x-style `event` hooks (`inProcess`)
60077
+ * take the Bun Shell path too: starting the child takes about
60078
+ * 250 ms, and OpenCode 1.x's one-shot `opencode run` exits right after
60079
+ * `session.idle`, before a `stop` command run that way could start.
60080
+ * A command that outlives its timeout (counted from its start) resolves to
60081
+ * `null` and is killed. On POSIX its process tree, read from procfs or else
60082
+ * `ps`, gets SIGTERM and, 2 s later, SIGKILL for each of those processes still
60083
+ * alive (same start time, wherever it was reparented) and what it started
60084
+ * since; the command's own process is signalled through its Bun handle only,
60085
+ * so a PID reused after it exited is never signalled. The command keeps
60086
+ * OpenCode's process group, so it keeps the terminal
60087
+ * and Ctrl-C, but a process that left the tree before the timeout (orphaned or
60088
+ * `setsid`) escapes, and without procfs and `ps` only
60089
+ * the command's own process is killed (logged). The pending SIGKILL keeps the
60090
+ * host alive for those 2 s. On Windows, `taskkill /T /F` ends the tree as
60091
+ * linked by parent PID at that moment, then the child is ended through its
60092
+ * handle; a process whose parent had already exited is not reached. Bun Shell
60093
+ * (the fallback) cannot kill: it stops waiting, and the command keeps running.
60094
+ * On a failure, `__rulesyncRunHook` throws in a blocking hook or logs it
60095
+ * otherwise.
60096
+ *
60097
+ * @see https://bun.sh/docs/bundler/executables
60098
+ */
60099
+ function buildRunHelperLinesFor(cwdExpression) {
60100
+ const spawn = (script, stdin, stdout = "\"pipe\"", stderr = stdout) => `Bun.spawn([process.execPath, "--no-env-file", "exec", ${script}], { cwd: ${cwdExpression}, env: { ...process.env, BUN_BE_BUN: "1" }, stdin: ${stdin}, stdout: ${stdout}, stderr: ${stderr}, windowsHide: true })`;
60101
+ return [
60102
+ "const __rulesyncRead = (stream, limit = 1048576) => {",
60103
+ " const chunks = [];",
60104
+ " let size = 0;",
60105
+ " const reader = stream.getReader();",
60106
+ " let reading = true;",
60107
+ " const done = (async () => {",
60108
+ " for (let read; reading && !(read = await reader.read()).done; ) {",
60109
+ " if (reading && (size += read.value.length) <= limit) chunks.push(read.value);",
60110
+ " }",
60111
+ " })().catch(() => {});",
60112
+ " const stop = () => {",
60113
+ " if (reading) (reading = false), reader.cancel().catch(() => {});",
60114
+ " };",
60115
+ " return { done, stop, text: () => Buffer.concat(chunks).toString(), overflow: () => size > limit };",
60116
+ "};",
60117
+ "let __rulesyncCanExec;",
60118
+ "let __rulesyncRetryAt = 0;",
60119
+ "// pid -> [ppid, start time], from procfs or else ps; a reused PID gets a new start time.",
60120
+ "const __rulesyncProcesses = () => {",
60121
+ " const processes = new Map();",
60122
+ " try {",
60123
+ " const fs = require(\"node:fs\");",
60124
+ " for (const pid of fs.readdirSync(\"/proc\").filter((name) => /^\\d+$/.test(name))) {",
60125
+ " try {",
60126
+ " const stat = fs.readFileSync(\"/proc/\" + pid + \"/stat\", \"utf8\");",
60127
+ " const fields = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \");",
60128
+ " processes.set(pid, [fields[1], fields[19]]);",
60129
+ " } catch {}",
60130
+ " }",
60131
+ " if (processes.size > 0) return processes;",
60132
+ " } catch {}",
60133
+ " try {",
60134
+ " // The C locale keeps `lstart` in one format; it is compared as text, never parsed.",
60135
+ " const env = { ...process.env, LC_ALL: \"C\", LANG: \"C\" };",
60136
+ " const ps = Bun.spawnSync([\"ps\", \"-A\", \"-o\", \"pid=,ppid=,lstart=\"], { env, timeout: 5000 });",
60137
+ " if (ps.exitCode === 0) {",
60138
+ " for (const line of ps.stdout.toString().trim().split(\"\\n\")) {",
60139
+ " const [pid, ppid, ...started] = line.trim().split(/\\s+/);",
60140
+ " processes.set(pid, [ppid, started.join(\" \")]);",
60141
+ " }",
60142
+ " return processes;",
60143
+ " }",
60144
+ " } catch {}",
60145
+ " console.error(\"[rulesync-hooks] neither /proc nor ps is available: only the hook process is killed\");",
60146
+ "};",
60147
+ "const __rulesyncTree = (roots, processes) => {",
60148
+ " const tree = [...roots];",
60149
+ " for (let size = -1; size !== tree.length; ) {",
60150
+ " size = tree.length;",
60151
+ " for (const [pid, [ppid]] of processes ?? []) if (tree.includes(ppid) && !tree.includes(pid)) tree.push(pid);",
60152
+ " }",
60153
+ " return tree;",
60154
+ "};",
60155
+ "// The child itself is signalled only through its handle, a no-op once Bun has reaped it, so a",
60156
+ "// reused PID is never signalled; its descendants only while it is running (not reaped, its PID",
60157
+ "// cannot be reused), and in the SIGKILL round only with both snapshots: the first snapshot's",
60158
+ "// descendants that are the same processes (same start time), and what they and the child,",
60159
+ "// if it ran across the second snapshot, have started since.",
60160
+ "const __rulesyncKillTree = (proc) => {",
60161
+ " const kill = (pids, signal) => pids.forEach((pid) => { try { process.kill(Number(pid), signal); } catch {} });",
60162
+ " const running = () => proc.exitCode === null && proc.signalCode === null;",
60163
+ " const root = String(proc.pid);",
60164
+ " const before = running() ? __rulesyncProcesses() : undefined;",
60165
+ " const first = before && running() ? __rulesyncTree([root], before).slice(1) : [];",
60166
+ " proc.kill(\"SIGTERM\");",
60167
+ " kill(first, \"SIGTERM\");",
60168
+ " setTimeout(() => {",
60169
+ " const alive = running();",
60170
+ " const now = before && __rulesyncProcesses();",
60171
+ " if (!now) return proc.kill(\"SIGKILL\");",
60172
+ " // Every first-snapshot descendant that is still the same process, wherever it was",
60173
+ " // reparented (to PID 1 or a subreaper), and the child if it survived SIGTERM, with what",
60174
+ " // they have started since. The child is killed first, so it starts nothing more.",
60175
+ " const same = first.filter((pid) => now.get(pid)?.[1] === before.get(pid)?.[1]);",
60176
+ " const own = alive && running() && now.get(root)?.[1] === before.get(root)?.[1];",
60177
+ " proc.kill(\"SIGKILL\");",
60178
+ " kill(__rulesyncTree(own ? [root, ...same] : same, now).filter((pid) => pid !== root), \"SIGKILL\");",
60179
+ " }, 2000);",
60180
+ "};",
60181
+ "// `proc.kill()` is TerminateProcess on the child alone. A libuv program (node) that dies takes",
60182
+ "// the children it spawned along through its job object, but not ones started through another",
60183
+ "// program (cmd.exe) or detached. taskkill /T ends the tree as linked by parent PID at that",
60184
+ "// moment; System32's copy, so a taskkill earlier on PATH is never run.",
60185
+ "const __rulesyncKillWindowsTree = (proc) => {",
60186
+ " if (proc.exitCode === null && proc.signalCode === null) {",
60187
+ " const taskkill = (process.env.SystemRoot ?? \"C:\\\\Windows\") + \"\\\\System32\\\\taskkill.exe\";",
60188
+ " try {",
60189
+ " Bun.spawnSync([taskkill, \"/T\", \"/F\", \"/PID\", String(proc.pid)], { stdout: \"ignore\", stderr: \"ignore\", windowsHide: true, timeout: 5000 });",
60190
+ " } catch {}",
60191
+ " }",
60192
+ " proc.kill();",
60193
+ "};",
60194
+ "const __rulesyncRunCommand = async ({ command, input, seconds, inProcess = false, echo = false }) => {",
60195
+ " // A probe that printed `rulesync` is kept; one past its deadline, failing or printing",
60196
+ " // anything else means no Bun CLI for 5 minutes; one that threw is dropped, so the next",
60197
+ " // command probes again.",
60198
+ " if (!inProcess && (__rulesyncCanExec === undefined || (__rulesyncRetryAt && Date.now() >= __rulesyncRetryAt))) {",
60199
+ " __rulesyncRetryAt = 0;",
60200
+ " const probing = (__rulesyncCanExec = (async () => {",
60201
+ ` const probe = ${spawn("\"echo rulesync\"", "\"ignore\"", "\"pipe\"", "\"ignore\"")};`,
60202
+ " const output = __rulesyncRead(probe.stdout, 1024);",
60203
+ " let timer;",
60204
+ " // Settles on its own, even if the probe ignores the kill or a process holds its stdout.",
60205
+ " const deadline = new Promise((resolve) => (timer = setTimeout(resolve, 10000, null)));",
60206
+ " const exited = Promise.all([probe.exited, output.done]).then(([code]) => code);",
60207
+ " const exitCode = await Promise.race([exited, deadline]).finally(() => clearTimeout(timer));",
60208
+ " if (exitCode === null) probe.kill(\"SIGKILL\"), output.stop();",
60209
+ " const found = exitCode === 0 && output.text().trim() === \"rulesync\";",
60210
+ " if (!found) __rulesyncRetryAt = Date.now() + 300000;",
60211
+ " return found;",
60212
+ " })().catch(() => {",
60213
+ " if (__rulesyncCanExec === probing) __rulesyncCanExec = undefined;",
60214
+ " return false;",
60215
+ " }));",
60216
+ " }",
60217
+ " let timer;",
60218
+ " const timeout = () => new Promise((resolve) => (timer = setTimeout(resolve, seconds * 1000, null)));",
60219
+ " if (inProcess || !(await __rulesyncCanExec)) {",
60220
+ ` const run = Bun.$\`echo \${input} | \${{ raw: command }}\`.cwd(${cwdExpression}).nothrow();`,
60221
+ " const result = await Promise.race([echo ? run : run.quiet(), timeout()]).finally(() => clearTimeout(timer));",
60222
+ " if (!result || echo) return result && { exitCode: result.exitCode };",
60223
+ " const { exitCode, stdout, stderr } = result;",
60224
+ " return { exitCode, stdout: stdout.toString(), stderr: stderr.toString(), overflow: stdout.length > 1048576 };",
60225
+ " }",
60226
+ " // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read.",
60227
+ " const output = echo ? \"inherit\" : \"pipe\";",
60228
+ ` const proc = ${spawn("\"export BUN_BE_BUN=\\n\" + command", "new TextEncoder().encode(input + \"\\n\")", "output")};`,
60229
+ " const [stdout, stderr] = echo ? [] : [__rulesyncRead(proc.stdout), __rulesyncRead(proc.stderr)];",
60230
+ " const exitCode = await Promise.race([proc.exited, timeout()]).finally(() => clearTimeout(timer));",
60231
+ " if (exitCode === null) {",
60232
+ " stdout?.stop(), stderr?.stop();",
60233
+ " if (process.platform === \"win32\") __rulesyncKillWindowsTree(proc);",
60234
+ " else __rulesyncKillTree(proc);",
60235
+ " return null;",
60236
+ " }",
60237
+ " if (echo) return { exitCode };",
60238
+ " await Promise.race([Promise.all([stdout.done, stderr.done]), Bun.sleep(1000)]);",
60239
+ " stdout.stop(), stderr.stop();",
60240
+ " return { exitCode, stdout: stdout.text(), stderr: stderr.text(), overflow: stdout.overflow() };",
60241
+ "};",
60242
+ "const __rulesyncRunHook = async ({ label, command, input, blocking, seconds, inProcess = false }) => {",
60243
+ " let result;",
60244
+ " try {",
60245
+ " result = await __rulesyncRunCommand({ command, input, seconds, inProcess, echo: true });",
60246
+ " } catch (error) {",
60247
+ " if (blocking) throw error;",
60248
+ " console.error(\"[rulesync-hooks] \" + label + \" hook failed:\", error);",
60249
+ " return;",
60250
+ " }",
60251
+ " if (result === null) {",
60252
+ " const message = \"[rulesync-hooks] \" + label + \" hook timed out after \" + seconds + \"s\";",
60253
+ " if (blocking) throw new Error(message);",
60254
+ " return console.error(message);",
60255
+ " }",
60256
+ " if (result.exitCode === 0) return;",
60257
+ " const message = \"[rulesync-hooks] \" + label + \" hook exited with code \" + result.exitCode;",
60258
+ " if (blocking) throw new Error(message);",
60259
+ " console.error(message);",
60260
+ "};"
60261
+ ];
60262
+ }
59694
60263
  /**
59695
60264
  * Name of the helper the generated plugin defines when a `preToolUse` handler
59696
60265
  * is present. It interprets the command's result like Claude Code does for a
@@ -59700,7 +60269,10 @@ const STDIN_PAYLOAD_EVENTS = { preToolUse: "PreToolUse" };
59700
60269
  * - exit code 0 with JSON stdout whose `hookSpecificOutput.permissionDecision`
59701
60270
  * is `"deny"` → deny, with `permissionDecisionReason` as the reason;
59702
60271
  * - exit code 0 otherwise → allow;
59703
- * - any other non-zero exit → deny too, with stderr or the exit code.
60272
+ * - any other non-zero exit → deny too, with stderr or the exit code;
60273
+ * - more than 1 MiB of stdout → deny, without parsing it;
60274
+ * - a command past its timeout → deny, like a non-zero exit, unless the hook
60275
+ * sets `failClosed: false`, which allows the call and logs the timeout.
59704
60276
  *
59705
60277
  * Every reason goes through the `sanitizeBlockReason` helper shared with the
59706
60278
  * Pi extension (`hook-block-reason.ts`): control and format characters are
@@ -59716,7 +60288,12 @@ const PRE_TOOL_USE_RESULT_HELPER = "__rulesyncEnforcePreToolUseResult";
59716
60288
  const PRE_TOOL_USE_RESULT_HELPER_LINES = [
59717
60289
  ...buildBlockReasonSanitizerLines({ typed: false }),
59718
60290
  "",
59719
- `const ${PRE_TOOL_USE_RESULT_HELPER} = (result) => {`,
60291
+ `const ${PRE_TOOL_USE_RESULT_HELPER} = (result, failClosed) => {`,
60292
+ " if (result === null) {",
60293
+ " if (failClosed !== false) throw new Error(\"preToolUse hook timed out.\");",
60294
+ " return console.error(\"[rulesync-hooks] preToolUse hook timed out\");",
60295
+ " }",
60296
+ " if (result.overflow) throw new Error(\"preToolUse hook wrote more than 1 MiB to stdout.\");",
59720
60297
  " const stderr = result.stderr.toString();",
59721
60298
  " if (result.exitCode === 0) {",
59722
60299
  " let parsed;",
@@ -59750,15 +60327,70 @@ function escapeForTemplateLiteral(command) {
59750
60327
  function validateAndSanitizeMatcher(matcher) {
59751
60328
  return sanitizeMatcherRegex(matcher).replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
59752
60329
  }
59753
- /** The per-canonical-event gates and payload flag every handler of it carries. */
60330
+ /**
60331
+ * A hook's `timeout` in seconds, Claude Code's default of 600 when it sets none,
60332
+ * capped at what `setTimeout` can wait (larger values fire at once), and its
60333
+ * `failClosed` as written: unset is not `false`.
60334
+ */
60335
+ function hookTimingOf(def) {
60336
+ const timeout = def.timeout !== void 0 && def.timeout > 0 ? def.timeout : 600;
60337
+ return {
60338
+ timeout: Math.min(timeout, 2147483),
60339
+ failClosed: def.failClosed
60340
+ };
60341
+ }
60342
+ const FAIL_CLOSED_TOOL_LABELS = {
60343
+ kilo: "Kilo Code",
60344
+ mimocode: "MiMo Code",
60345
+ opencode: "OpenCode",
60346
+ opencodev1: "OpenCode V1"
60347
+ };
60348
+ /**
60349
+ * Canonical events other than `preToolUse` whose hook runs before its action in
60350
+ * every OpenCode-style plugin (V1 and V2): a failing or timed-out command always
60351
+ * aborts the action there. A test checks it against `BLOCKING_HOOKS` and the V2
60352
+ * generator's `isBlockingOpencodeV2Target`.
60353
+ */
60354
+ const ALWAYS_BLOCKING_EVENTS = /* @__PURE__ */ new Set([
60355
+ "beforeShellExecution",
60356
+ "beforeSubmitPrompt",
60357
+ "preModelInvocation",
60358
+ "userPromptExpansion",
60359
+ "preCompact"
60360
+ ]);
60361
+ /**
60362
+ * Warn about each `failClosed` the generated plugin ignores where it changes
60363
+ * the outcome: the plugin only reads it on `preToolUse`, to decide what a
60364
+ * timed-out command does. Elsewhere a hook that runs before its action always
60365
+ * fails on a timeout, so a `false` there is ignored (a `true` already holds),
60366
+ * and any other hook only logs it, so a `true` there is ignored (a `false`
60367
+ * already holds, like the other targets treat an omitted `false`).
60368
+ */
60369
+ function warnIgnoredFailClosed({ config, supportedEvents, toolConfigKey, logger }) {
60370
+ const configHooks = {
60371
+ ...config.hooks,
60372
+ ...config[toolConfigKey]?.hooks
60373
+ };
60374
+ const plugin = `the generated ${FAIL_CLOSED_TOOL_LABELS[toolConfigKey]} plugin`;
60375
+ for (const [event, definitions] of Object.entries(configHooks)) {
60376
+ if (event === "preToolUse" || !supportedEvents.includes(event)) continue;
60377
+ const blocking = ALWAYS_BLOCKING_EVENTS.has(event);
60378
+ for (const def of definitions) {
60379
+ if (def.failClosed !== !blocking) continue;
60380
+ logger?.warn(blocking ? `failClosed: false on "${event}" hook will be ignored — ${plugin} always blocks the action when this hook fails or times out, and only supports failClosed on preToolUse` : `failClosed on "${event}" hook will be ignored — ${plugin} only supports failClosed on preToolUse`);
60381
+ }
60382
+ }
60383
+ }
60384
+ /** The per-canonical-event gates and payload every handler of it carries. */
59754
60385
  function handlerExtrasFor(canonicalEvent) {
59755
60386
  const shellGate = SHELL_EVENT_TOOL_GATES[canonicalEvent];
59756
60387
  const propertyGate = GENERIC_EVENT_PROPERTY_GATES[canonicalEvent];
59757
- const stdinEvent = shellGate ? void 0 : STDIN_PAYLOAD_EVENTS[canonicalEvent];
60388
+ const payload = shellGate ? void 0 : STDIN_PAYLOADS[canonicalEvent];
59758
60389
  return {
60390
+ event: canonicalEvent,
59759
60391
  ...shellGate ? { toolGate: shellGate.tool } : {},
59760
60392
  ...propertyGate ? { propertyGate } : {},
59761
- ...stdinEvent ? { stdinEvent } : {}
60393
+ ...payload ? { payload } : {}
59762
60394
  };
59763
60395
  }
59764
60396
  /**
@@ -59771,7 +60403,8 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
59771
60403
  const extras = handlerExtrasFor(canonicalEvent);
59772
60404
  const toolEvent = shellGate?.toolEvent ?? eventMap[canonicalEvent];
59773
60405
  if (!toolEvent) continue;
59774
- const matcherSupported = !shellGate && Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent) && NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] !== null;
60406
+ const isNamedHook = Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent);
60407
+ const matcherSupported = !shellGate && isNamedHook && NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] !== null;
59775
60408
  const handlers = [];
59776
60409
  for (const def of definitions) {
59777
60410
  if ((def.type ?? "command") !== "command") continue;
@@ -59780,11 +60413,14 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
59780
60413
  handlers.push({
59781
60414
  command: def.command,
59782
60415
  matcher: def.matcher ? def.matcher : void 0,
60416
+ blocking: BLOCKING_HOOKS.has(toolEvent),
60417
+ ...hookTimingOf(def),
60418
+ inProcess: !isNamedHook,
59783
60419
  ...extras
59784
60420
  });
59785
60421
  }
59786
60422
  if (handlers.length > 0) {
59787
- const grouped = Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent) ? namedEventHandlers : genericEventHandlers;
60423
+ const grouped = isNamedHook ? namedEventHandlers : genericEventHandlers;
59788
60424
  const existing = grouped[toolEvent];
59789
60425
  if (existing) existing.push(...handlers);
59790
60426
  else grouped[toolEvent] = handlers;
@@ -59800,13 +60436,17 @@ function buildGenericEventBodyLines(genericEventHandlers) {
59800
60436
  for (const [eventName, handlers] of Object.entries(genericEventHandlers)) {
59801
60437
  bodyLines.push(` ${isFirst ? "if" : "else if"} (event.type === "${eventName}") {`);
59802
60438
  isFirst = false;
60439
+ for (const line of buildPayloadClosureLines({
60440
+ handlers,
60441
+ cwdExpression: V1_CWD_EXPRESSION
60442
+ })) bodyLines.push(` ${line}`);
59803
60443
  for (const handler of handlers) {
59804
- const escapedCommand = escapeForTemplateLiteral(handler.command);
60444
+ const runStatement = buildRunStatement(handler);
59805
60445
  if (handler.propertyGate) {
59806
60446
  bodyLines.push(` if (${handler.propertyGate}) {`);
59807
- bodyLines.push(` await $\`${escapedCommand}\`;`);
60447
+ bodyLines.push(` ${runStatement}`);
59808
60448
  bodyLines.push(" }");
59809
- } else bodyLines.push(` await $\`${escapedCommand}\`;`);
60449
+ } else bodyLines.push(` ${runStatement}`);
59810
60450
  }
59811
60451
  bodyLines.push(" }");
59812
60452
  }
@@ -59816,39 +60456,61 @@ function buildGenericEventBodyLines(genericEventHandlers) {
59816
60456
  function stdinPayloadVariable(stdinEvent) {
59817
60457
  return `__rulesync${stdinEvent}Input`;
59818
60458
  }
60459
+ /** The `cwd` a V1 payload reports: the session directory, else the process's. */
60460
+ const V1_CWD_EXPRESSION = "directory ?? process.cwd()";
60461
+ /** Lazily serialized closures for the payloads the handlers use (internal tables only). */
60462
+ function buildPayloadClosureLines({ handlers, cwdExpression }) {
60463
+ const payloads = /* @__PURE__ */ new Map();
60464
+ for (const handler of handlers) if (handler.payload) payloads.set(handler.payload.name, handler.payload);
60465
+ const lines = [];
60466
+ for (const payload of payloads.values()) {
60467
+ const variable = stdinPayloadVariable(payload.name);
60468
+ lines.push(`let ${variable}Cache;`, `const ${variable} = () =>`);
60469
+ lines.push(` (${variable}Cache ??= JSON.stringify({`);
60470
+ lines.push(` hook_event_name: "${payload.name}",`);
60471
+ lines.push(...payload.fields.map((field) => ` ${field},`));
60472
+ lines.push(` cwd: ${cwdExpression},`, " }));");
60473
+ }
60474
+ return lines;
60475
+ }
59819
60476
  /**
59820
- * The statement that runs a handler's command. A handler with a stdin payload
59821
- * pipes the payload in and hands the result to the deny-aware helper; every
59822
- * other handler keeps Bun Shell's default mode, where a non-zero exit throws.
60477
+ * The statement that runs a handler's command with its stdin payload, or an
60478
+ * empty stdin. The command keeps the escaping it had in the template literal
60479
+ * earlier versions emitted, so `bun exec` parses the same text.
59823
60480
  */
59824
60481
  function buildRunStatement(handler) {
59825
- const escapedCommand = escapeForTemplateLiteral(handler.command);
59826
- if (handler.stdinEvent) {
59827
- const payload = stdinPayloadVariable(handler.stdinEvent);
59828
- return `${PRE_TOOL_USE_RESULT_HELPER}(await $\`echo \${${payload}()} | ${escapedCommand}\`.nothrow().quiet());`;
59829
- }
59830
- return `await $\`${escapedCommand}\`;`;
60482
+ const command = JSON.stringify(escapeForTemplateLiteral(handler.command));
60483
+ const input = handler.payload ? `${stdinPayloadVariable(handler.payload.name)}()` : "\"\"";
60484
+ if (handler.payload?.name === "PreToolUse") {
60485
+ const failClosed = handler.failClosed === void 0 ? "" : `, ${handler.failClosed}`;
60486
+ return `${PRE_TOOL_USE_RESULT_HELPER}(await __rulesyncRunCommand({ command: ${command}, input: ${input}, seconds: ${handler.timeout} })${failClosed});`;
60487
+ }
60488
+ return `await __rulesyncRunHook({ ${[
60489
+ `label: ${JSON.stringify(handler.event)}`,
60490
+ `command: ${command}`,
60491
+ `input: ${input}`,
60492
+ `blocking: ${handler.blocking}`,
60493
+ `seconds: ${handler.timeout}`,
60494
+ ...handler.inProcess ? ["inProcess: true"] : []
60495
+ ].join(", ")} });`;
60496
+ }
60497
+ /** The helpers a plugin body defines before its handlers, run in `cwdExpression`. */
60498
+ function buildRunHelperLines({ handlers, cwdExpression }) {
60499
+ if (handlers.length === 0) return [];
60500
+ const usesPreToolUse = handlers.some((handler) => handler.payload?.name === "PreToolUse");
60501
+ return [...buildRunHelperLinesFor(cwdExpression), ...usesPreToolUse ? ["", ...PRE_TOOL_USE_RESULT_HELPER_LINES] : []];
59831
60502
  }
59832
60503
  /** Emit the named (`tool.execute.*`) handler blocks. */
59833
60504
  function buildNamedEventBodyLines(namedEventHandlers) {
59834
60505
  const bodyLines = [];
59835
60506
  for (const [eventName, handlers] of Object.entries(namedEventHandlers)) {
59836
60507
  const matcherSubject = NAMED_HOOK_MATCHER_SUBJECTS[eventName] ?? null;
59837
- const stdinEvents = [...new Set(handlers.flatMap((handler) => handler.stdinEvent ? [handler.stdinEvent] : []))];
59838
- bodyLines.push(` "${eventName}": async (${stdinEvents.length > 0 ? "input, output" : "input"}) => {`);
59839
- for (const stdinEvent of stdinEvents) {
59840
- const payload = stdinPayloadVariable(stdinEvent);
59841
- bodyLines.push(` let ${payload}Cache;`);
59842
- bodyLines.push(` const ${payload} = () =>`);
59843
- bodyLines.push(` (${payload}Cache ??= JSON.stringify({`);
59844
- bodyLines.push(` hook_event_name: "${stdinEvent}",`);
59845
- bodyLines.push(" session_id: input.sessionID,");
59846
- bodyLines.push(" tool_use_id: input.callID,");
59847
- bodyLines.push(" tool_name: input.tool,");
59848
- bodyLines.push(" tool_input: output?.args,");
59849
- bodyLines.push(" cwd: directory ?? process.cwd(),");
59850
- bodyLines.push(" }));");
59851
- }
60508
+ const payloadLines = buildPayloadClosureLines({
60509
+ handlers,
60510
+ cwdExpression: V1_CWD_EXPRESSION
60511
+ });
60512
+ bodyLines.push(` "${eventName}": async (${payloadLines.length > 0 ? "input, output" : "input"}) => {`);
60513
+ bodyLines.push(...payloadLines.map((line) => ` ${line}`));
59852
60514
  for (const handler of handlers) {
59853
60515
  const runStatement = buildRunStatement(handler);
59854
60516
  if (handler.toolGate) {
@@ -59871,7 +60533,7 @@ function buildNamedEventBodyLines(namedEventHandlers) {
59871
60533
  }
59872
60534
  /** Wrap the handler body lines in the requested export shape. */
59873
60535
  function wrapInExportShape({ preambleLines, bodyLines, exportStyle }) {
59874
- const pluginContextPattern = preambleLines.length > 0 ? "{ $, directory }" : "{ $ }";
60536
+ const pluginContextPattern = preambleLines.length > 0 ? "{ directory }" : "{ $ }";
59875
60537
  const lines = [];
59876
60538
  if (exportStyle === "default") {
59877
60539
  lines.push("export default {");
@@ -59912,7 +60574,10 @@ function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey,
59912
60574
  });
59913
60575
  const bodyLines = [...buildGenericEventBodyLines(genericEventHandlers), ...buildNamedEventBodyLines(namedEventHandlers)];
59914
60576
  return wrapInExportShape({
59915
- preambleLines: Object.values(namedEventHandlers).some((handlers) => handlers.some((handler) => handler.stdinEvent !== void 0)) ? PRE_TOOL_USE_RESULT_HELPER_LINES : [],
60577
+ preambleLines: buildRunHelperLines({
60578
+ handlers: [...Object.values(namedEventHandlers), ...Object.values(genericEventHandlers)].flat(),
60579
+ cwdExpression: V1_CWD_EXPRESSION
60580
+ }),
59916
60581
  bodyLines,
59917
60582
  exportStyle
59918
60583
  }).join("\n");
@@ -59946,8 +60611,15 @@ var KiloHooks = class KiloHooks extends ToolHooks {
59946
60611
  validate
59947
60612
  });
59948
60613
  }
59949
- static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false }) {
59950
- const fileContent = generateOpencodeStylePluginCode(rulesyncHooks.getJson(), KILO_HOOK_EVENTS, "kilo", CANONICAL_TO_KILO_EVENT_NAMES, "default");
60614
+ static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false, logger }) {
60615
+ const config = rulesyncHooks.getJson();
60616
+ warnIgnoredFailClosed({
60617
+ config,
60618
+ supportedEvents: KILO_HOOK_EVENTS,
60619
+ toolConfigKey: "kilo",
60620
+ logger
60621
+ });
60622
+ const fileContent = generateOpencodeStylePluginCode(config, KILO_HOOK_EVENTS, "kilo", CANONICAL_TO_KILO_EVENT_NAMES, "default");
59951
60623
  const paths = KiloHooks.getSettablePaths({ global });
59952
60624
  return new KiloHooks({
59953
60625
  outputRoot,
@@ -60155,7 +60827,7 @@ var KimiCodeHooks = class KimiCodeHooks extends ToolHooks {
60155
60827
  global: true
60156
60828
  });
60157
60829
  }
60158
- toRulesyncHooks() {
60830
+ toRulesyncHooks({ logger } = {}) {
60159
60831
  const config = parseSharedConfig({
60160
60832
  format: "toml",
60161
60833
  fileContent: this.getFileContent()
@@ -60168,6 +60840,7 @@ var KimiCodeHooks = class KimiCodeHooks extends ToolHooks {
60168
60840
  relativeDirPath: RULESYNC_RELATIVE_DIR_PATH,
60169
60841
  relativeFilePath: RULESYNC_HOOKS_FILE_NAME,
60170
60842
  fileContent: JSON.stringify(buildImportedHooksConfig({
60843
+ logger,
60171
60844
  hooks: kimiCodeHooksToCanonical(config.hooks),
60172
60845
  overrideKey: "kimi-code"
60173
60846
  }), null, 2)
@@ -60392,12 +61065,13 @@ var KiroIdeHooks = class extends ToolHooks {
60392
61065
  validate
60393
61066
  });
60394
61067
  }
60395
- toRulesyncHooks() {
61068
+ toRulesyncHooks({ logger } = {}) {
60396
61069
  const hooks = kiroIdeHooksToCanonical(this.parseFileContentOrThrow({
60397
61070
  displayName: "Kiro IDE",
60398
61071
  parse: (fileContent) => KiroIdeHooksFileSchema.parse(JSON.parse(fileContent))
60399
61072
  }).hooks ?? []);
60400
61073
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
61074
+ logger,
60401
61075
  hooks,
60402
61076
  overrideKey: KIRO_HOOKS_OVERRIDE_KEY
60403
61077
  }), null, 2) });
@@ -60582,12 +61256,13 @@ var KiroHooks = class KiroHooks extends ToolHooks {
60582
61256
  validate
60583
61257
  });
60584
61258
  }
60585
- toRulesyncHooks() {
61259
+ toRulesyncHooks({ logger } = {}) {
60586
61260
  const hooks = kiroHooksToCanonical(this.parseFileContentOrThrow({
60587
61261
  displayName: "Kiro",
60588
61262
  parse: (fileContent) => JSON.parse(fileContent)
60589
61263
  }).hooks);
60590
61264
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
61265
+ logger,
60591
61266
  hooks,
60592
61267
  overrideKey: "kiro"
60593
61268
  }), null, 2) });
@@ -60741,6 +61416,7 @@ var LettacodeHooks = class LettacodeHooks extends ToolHooks {
60741
61416
  converterConfig: LETTACODE_CONVERTER_CONFIG
60742
61417
  });
60743
61418
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
61419
+ logger,
60744
61420
  hooks,
60745
61421
  overrideKey: "lettacode"
60746
61422
  }), null, 2) });
@@ -60759,10 +61435,7 @@ var LettacodeHooks = class LettacodeHooks extends ToolHooks {
60759
61435
  * option; the per-type checks inside the loop stay, so an older 2.x that
60760
61436
  * ignores it still runs each command only for its own event).
60761
61437
  *
60762
- * Commands run through a private Bun Shell instance (`new Bun.$.Shell()`, the
60763
- * plugin runs inside the Bun-built OpenCode binary) whose working directory is
60764
- * the plugin location's directory, so the global `Bun.$` defaults other
60765
- * plugins see are left alone.
61438
+ * Commands run in the plugin location's directory (see `buildRunHelperLines`).
60766
61439
  *
60767
61440
  * @see https://opencode.ai/v2/docs/build/plugins/
60768
61441
  */
@@ -60785,13 +61458,33 @@ const OPENCODE_V2_HANDLER_GATES = {
60785
61458
  permissionDenied: "event.data?.reply === \"reject\""
60786
61459
  };
60787
61460
  /**
60788
- * Canonical events whose command receives a Claude Code-style `PreToolUse`
60789
- * JSON payload on stdin and whose result can deny the call. Throwing from an
60790
- * `execute.before` hook fails the tool call with the error message, which the
60791
- * model sees — the same contract the V1 plugin implements, interpreted by the
60792
- * shared `PRE_TOOL_USE_RESULT_HELPER`.
61461
+ * The V2 counterparts of the V1 stdin payloads (`STDIN_PAYLOADS`), plus
61462
+ * Claude Code's `PostToolUseFailure` input for a failed call.
60793
61463
  */
60794
- const OPENCODE_V2_STDIN_PAYLOAD_EVENTS = { preToolUse: "PreToolUse" };
61464
+ const TOOL_CALL_FIELDS = [
61465
+ "session_id: event.sessionID",
61466
+ "tool_use_id: event.id",
61467
+ "tool_name: event.tool",
61468
+ "tool_input: event.input"
61469
+ ];
61470
+ const OPENCODE_V2_STDIN_PAYLOADS = {
61471
+ preToolUse: {
61472
+ name: "PreToolUse",
61473
+ fields: TOOL_CALL_FIELDS
61474
+ },
61475
+ postToolUse: {
61476
+ name: "PostToolUse",
61477
+ fields: [...TOOL_CALL_FIELDS, "tool_response: event.result"]
61478
+ },
61479
+ postToolUseFailure: {
61480
+ name: "PostToolUseFailure",
61481
+ fields: [...TOOL_CALL_FIELDS, "error: event.error?.message ?? event.error"]
61482
+ },
61483
+ stop: {
61484
+ name: "Stop",
61485
+ fields: ["session_id: event.data?.sessionID"]
61486
+ }
61487
+ };
60795
61488
  /**
60796
61489
  * Helper the generated plugin defines when a handler has a matcher. A matcher
60797
61490
  * is tested against the V2 tool name and, for a tool OpenCode 2.x renamed,
@@ -60828,28 +61521,21 @@ function buildHookRegistrationLines(hookPoint, handlers) {
60828
61521
  const lines = [];
60829
61522
  lines.push("__rulesyncRegistrations.push(");
60830
61523
  lines.push(` await ctx.${domain}.hook("${name}", async (event) => {`);
60831
- const stdinEvents = [...new Set(handlers.flatMap((handler) => handler.stdinEvent ? [handler.stdinEvent] : []))];
60832
- for (const stdinEvent of stdinEvents) {
60833
- const payload = stdinPayloadVariable(stdinEvent);
60834
- lines.push(` let ${payload}Cache;`);
60835
- lines.push(` const ${payload} = () =>`);
60836
- lines.push(` (${payload}Cache ??= JSON.stringify({`);
60837
- lines.push(` hook_event_name: "${stdinEvent}",`);
60838
- lines.push(" session_id: event.sessionID,");
60839
- lines.push(" tool_use_id: event.id,");
60840
- lines.push(" tool_name: event.tool,");
60841
- lines.push(" tool_input: event.input,");
60842
- lines.push(" cwd: directory,");
60843
- lines.push(" }));");
60844
- }
61524
+ lines.push(...buildPayloadClosureLines({
61525
+ handlers,
61526
+ cwdExpression: "directory"
61527
+ }).map((line) => ` ${line}`));
60845
61528
  for (const handler of handlers) lines.push(...wrapInConditions(handler, buildRunStatement(handler), " "));
60846
61529
  lines.push(" }),");
60847
61530
  lines.push(");");
60848
61531
  return lines;
60849
61532
  }
60850
61533
  /**
60851
- * Emit the event-stream loop. Each command is isolated in its own try/catch so
60852
- * a failing hook neither skips its siblings nor ends the subscription. The
61534
+ * Emit the event-stream loop. Event handlers are non-blocking, so
61535
+ * `__rulesyncRunHook` logs a failing command instead of throwing, and it
61536
+ * neither skips its siblings nor ends the subscription. Each handler also runs
61537
+ * in its own try/catch, so a throw while evaluating its gate or building its
61538
+ * payload, outside `__rulesyncRunHook`, is logged the same way. The
60853
61539
  * subscription passes `types` so the server delivers only the handled events.
60854
61540
  */
60855
61541
  function buildEventLoopLines(eventHandlers) {
@@ -60865,11 +61551,16 @@ function buildEventLoopLines(eventHandlers) {
60865
61551
  for (const [eventType, handlers] of eventHandlers) {
60866
61552
  lines.push(` ${isFirst ? "if" : "} else if"} (event.type === "${eventType}") {`);
60867
61553
  isFirst = false;
61554
+ lines.push(...buildPayloadClosureLines({
61555
+ handlers,
61556
+ cwdExpression: "directory"
61557
+ }).map((line) => ` ${line}`));
60868
61558
  for (const handler of handlers) {
60869
61559
  lines.push(" try {");
60870
61560
  lines.push(...wrapInConditions(handler, buildRunStatement(handler), " "));
60871
61561
  lines.push(" } catch (error) {");
60872
- lines.push(` console.error("[rulesync-hooks] ${eventType} hook failed:", error);`);
61562
+ const message = JSON.stringify(`[rulesync-hooks] ${handler.event} hook failed:`);
61563
+ lines.push(` console.error(${message}, error);`);
60873
61564
  lines.push(" }");
60874
61565
  }
60875
61566
  }
@@ -60878,10 +61569,17 @@ function buildEventLoopLines(eventHandlers) {
60878
61569
  lines.push("})().catch(() => {});");
60879
61570
  return lines;
60880
61571
  }
61572
+ /**
61573
+ * Every hook point but `execute.after` runs before its action, which a throw
61574
+ * aborts; the event stream only observes.
61575
+ */
61576
+ function isBlockingOpencodeV2Target(target) {
61577
+ return !target.startsWith("event:") && target !== "tool:execute.after";
61578
+ }
60881
61579
  /** Build the handlers of one canonical event's command definitions. */
60882
61580
  function buildHandlersFor({ canonicalEvent, definitions, target }) {
60883
61581
  const gate = OPENCODE_V2_HANDLER_GATES[canonicalEvent];
60884
- const stdinEvent = OPENCODE_V2_STDIN_PAYLOAD_EVENTS[canonicalEvent];
61582
+ const payload = OPENCODE_V2_STDIN_PAYLOADS[canonicalEvent];
60885
61583
  const matcherSupported = !(canonicalEvent === "beforeShellExecution" || canonicalEvent === "afterShellExecution") && OPENCODE_V2_MATCHABLE_HOOKS.has(target);
60886
61584
  const handlers = [];
60887
61585
  for (const def of definitions) {
@@ -60890,9 +61588,12 @@ function buildHandlersFor({ canonicalEvent, definitions, target }) {
60890
61588
  if (def.matcher && !matcherSupported) continue;
60891
61589
  handlers.push({
60892
61590
  command: def.command,
61591
+ event: canonicalEvent,
61592
+ blocking: isBlockingOpencodeV2Target(target),
61593
+ ...hookTimingOf(def),
60893
61594
  ...def.matcher ? { matcher: def.matcher } : {},
60894
61595
  ...gate ? { gate } : {},
60895
- ...stdinEvent ? { stdinEvent } : {}
61596
+ ...payload ? { payload } : {}
60896
61597
  });
60897
61598
  }
60898
61599
  return handlers;
@@ -60900,13 +61601,14 @@ function buildHandlersFor({ canonicalEvent, definitions, target }) {
60900
61601
  /** Emit the statements of the `setup` function body. */
60901
61602
  function buildSetupBodyLines({ hookHandlers, eventHandlers }) {
60902
61603
  if (hookHandlers.size === 0 && eventHandlers.size === 0) return [];
60903
- const usesStdinPayload = [...hookHandlers.values()].some((handlers) => handlers.some((handler) => handler.stdinEvent !== void 0));
60904
61604
  const body = [
60905
61605
  "const directory = ctx.location?.directory ?? process.cwd();",
60906
- "const $ = new Bun.$.Shell();",
60907
- "$.cwd(directory);"
61606
+ "",
61607
+ ...buildRunHelperLines({
61608
+ handlers: [...hookHandlers.values(), ...eventHandlers.values()].flat(),
61609
+ cwdExpression: "directory"
61610
+ })
60908
61611
  ];
60909
- if (usesStdinPayload) body.push("", ...PRE_TOOL_USE_RESULT_HELPER_LINES);
60910
61612
  if ([...hookHandlers.values()].some((handlers) => handlers.some((handler) => handler.matcher !== void 0))) body.push("", ...TOOL_MATCHER_HELPER_LINES);
60911
61613
  const cleanup = [];
60912
61614
  if (hookHandlers.size > 0) {
@@ -60979,8 +61681,14 @@ var OpencodeHooks = class extends ToolHooks {
60979
61681
  validate
60980
61682
  });
60981
61683
  }
60982
- static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false }) {
61684
+ static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false, logger }) {
60983
61685
  const config = rulesyncHooks.getJson();
61686
+ warnIgnoredFailClosed({
61687
+ config,
61688
+ supportedEvents: this.layout.configVersion === "v2" ? OPENCODE_V2_HOOK_EVENTS : OPENCODE_HOOK_EVENTS,
61689
+ toolConfigKey: this.layout.toolTarget,
61690
+ logger
61691
+ });
60984
61692
  const fileContent = this.layout.configVersion === "v2" ? generateOpencodeV2PluginCode({
60985
61693
  config,
60986
61694
  supportedEvents: OPENCODE_V2_HOOK_EVENTS,
@@ -61733,9 +62441,10 @@ var PoolHooks = class PoolHooks extends ToolHooks {
61733
62441
  global
61734
62442
  });
61735
62443
  }
61736
- toRulesyncHooks() {
62444
+ toRulesyncHooks({ logger } = {}) {
61737
62445
  const hooks = poolHooksToCanonical(this.settings[POOL_HOOKS_KEY]);
61738
62446
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
62447
+ logger,
61739
62448
  hooks,
61740
62449
  overrideKey: "pool"
61741
62450
  }), null, 2) });
@@ -62132,12 +62841,13 @@ var QwencodeHooks = class QwencodeHooks extends ToolHooks {
62132
62841
  static supportsPreserveUnowned() {
62133
62842
  return true;
62134
62843
  }
62135
- toRulesyncHooks() {
62844
+ toRulesyncHooks({ logger } = {}) {
62136
62845
  const settings = this.parseFileContentOrThrow({
62137
62846
  displayName: "Qwen Code",
62138
62847
  parse: (fileContent) => JSON.parse(fileContent)
62139
62848
  });
62140
62849
  const canonical = buildImportedHooksConfig({
62850
+ logger,
62141
62851
  hooks: qwencodeHooksToCanonical(settings.hooks),
62142
62852
  overrideKey: "qwencode",
62143
62853
  ...typeof settings.disableAllHooks === "boolean" && { extraOverride: { disableAllHooks: settings.disableAllHooks } }
@@ -62342,12 +63052,13 @@ var ReasonixHooks = class ReasonixHooks extends ToolHooks {
62342
63052
  validate
62343
63053
  });
62344
63054
  }
62345
- toRulesyncHooks() {
63055
+ toRulesyncHooks({ logger } = {}) {
62346
63056
  const hooks = reasonixHooksToCanonical(this.parseFileContentOrThrow({
62347
63057
  displayName: "Reasonix",
62348
63058
  parse: (fileContent) => JSON.parse(fileContent)
62349
63059
  }).hooks);
62350
63060
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
63061
+ logger,
62351
63062
  hooks,
62352
63063
  overrideKey: "reasonix"
62353
63064
  }), null, 2) });
@@ -62572,13 +63283,14 @@ var TabnineHooks = class TabnineHooks extends ToolHooks {
62572
63283
  validate
62573
63284
  });
62574
63285
  }
62575
- toRulesyncHooks() {
63286
+ toRulesyncHooks({ logger } = {}) {
62576
63287
  const configPath = (0, node_path.join)(this.getRelativeDirPath(), this.getRelativeFilePath());
62577
63288
  const hooks = tabnineHooksToCanonical(this.parseFileContentOrThrow({
62578
63289
  displayName: "Tabnine CLI",
62579
63290
  parse: (fileContent) => parseTabnineSettings(fileContent, configPath)
62580
63291
  }).hooks);
62581
63292
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
63293
+ logger,
62582
63294
  hooks,
62583
63295
  overrideKey: "tabnine"
62584
63296
  }), null, 2) });
@@ -62643,13 +63355,31 @@ var TraeHooks = class extends SettingsJsonHooks {
62643
63355
  const VIBE_DIR = ".vibe";
62644
63356
  const VIBE_HOOKS_FILE_NAME = "hooks.toml";
62645
63357
  /**
62646
- * Vibe scopes the tool-name `match` glob and the `strict` flag to tool hooks
62647
- * (`pre_tool` / `post_tool`). `post_agent` takes a `match` too since v3.0.3,
62648
- * but on the name of the agent that finished its turn, not a tool name (see
62649
- * {@link VIBE_MAIN_AGENT_MATCH}).
62650
- * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.3/README.md
63358
+ * Vibe scopes the tool-name `match` glob to tool hooks (`pre_tool` /
63359
+ * `post_tool`). The other events take a `match` too, on something other than a
63360
+ * tool name: the agent whose turn it is on `post_agent` / `pre_agent` /
63361
+ * `pre_llm` / `post_llm`, and the source, reason or notification type on
63362
+ * `session_start` / `session_end` / `notification`.
63363
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/plugins/builtins/vibe/skills/vibe/SKILL.md
62651
63364
  */
62652
63365
  const VIBE_TOOL_EVENTS = /* @__PURE__ */ new Set(["pre_tool", "post_tool"]);
63366
+ /**
63367
+ * The events where a failing hook may block, and so the only ones that accept
63368
+ * `strict`. Vibe's `HookConfig` validator rejects a `strict` entry of any
63369
+ * other type.
63370
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/hooks/models.py
63371
+ */
63372
+ const VIBE_STRICT_EVENTS = /* @__PURE__ */ new Set([
63373
+ "pre_tool",
63374
+ "post_tool",
63375
+ "pre_agent",
63376
+ "pre_llm",
63377
+ "post_llm"
63378
+ ]);
63379
+ /** The canonical matcher for a `pre_agent` hook that runs for every agent. */
63380
+ const VIBE_ANY_AGENT_MATCHER = "*";
63381
+ /** The Vibe event canonical `beforeSubmitPrompt` becomes. */
63382
+ const VIBE_PRE_AGENT_EVENT = "pre_agent";
62653
63383
  /** The Vibe event both canonical `stop` and `subagentStop` become. */
62654
63384
  const VIBE_POST_AGENT_EVENT = "post_agent";
62655
63385
  /**
@@ -62697,11 +63427,69 @@ function fromVibeHookMatch(match) {
62697
63427
  return match.toLowerCase() === VIBE_SHELL_HOOK_MATCH ? "Bash" : match;
62698
63428
  }
62699
63429
  /**
63430
+ * The `match` for an event whose matcher is not a tool name, or `undefined`
63431
+ * when the canonical matcher selects everything.
63432
+ */
63433
+ function toVibeOptionalMatch(matcher) {
63434
+ if (typeof matcher !== "string" || matcher === "" || matcher === "*") return;
63435
+ return matcher;
63436
+ }
63437
+ /**
63438
+ * The `match` of the Vibe entry a canonical hook becomes: a string, `undefined`
63439
+ * to leave the key out, or null to skip the hook.
63440
+ */
63441
+ function toVibeEntryMatch({ event, vibeEvent, matcher, logger }) {
63442
+ if (VIBE_TOOL_EVENTS.has(vibeEvent)) return toVibeHookMatch(matcher);
63443
+ if (event === "subagentStop") return toVibeSubagentMatch({
63444
+ matcher,
63445
+ logger
63446
+ });
63447
+ if (vibeEvent === VIBE_POST_AGENT_EVENT) return VIBE_MAIN_AGENT_MATCH;
63448
+ if (vibeEvent === VIBE_PRE_AGENT_EVENT) {
63449
+ if (typeof matcher !== "string" || matcher === "") return VIBE_MAIN_AGENT_MATCH;
63450
+ return toVibeOptionalMatch(matcher);
63451
+ }
63452
+ return toVibeOptionalMatch(matcher);
63453
+ }
63454
+ /**
63455
+ * The canonical event and matcher a Vibe entry's `type` and `match` become.
63456
+ */
63457
+ function fromVibeEntryMatch({ vibeEvent, canonicalEvent, match }) {
63458
+ if (VIBE_TOOL_EVENTS.has(vibeEvent)) return {
63459
+ canonicalEvent,
63460
+ matcher: fromVibeHookMatch(match)
63461
+ };
63462
+ const optionalMatch = toVibeOptionalMatch(match);
63463
+ const isMainAgent = optionalMatch === void 0 || optionalMatch.toLowerCase() === VIBE_MAIN_AGENT_MATCH;
63464
+ if (vibeEvent === VIBE_POST_AGENT_EVENT) return isMainAgent ? {
63465
+ canonicalEvent,
63466
+ matcher: void 0
63467
+ } : {
63468
+ canonicalEvent: "subagentStop",
63469
+ matcher: optionalMatch
63470
+ };
63471
+ if (vibeEvent === VIBE_PRE_AGENT_EVENT) {
63472
+ if (optionalMatch === void 0) return {
63473
+ canonicalEvent,
63474
+ matcher: VIBE_ANY_AGENT_MATCHER
63475
+ };
63476
+ return {
63477
+ canonicalEvent,
63478
+ matcher: isMainAgent ? void 0 : optionalMatch
63479
+ };
63480
+ }
63481
+ return {
63482
+ canonicalEvent,
63483
+ matcher: optionalMatch
63484
+ };
63485
+ }
63486
+ /**
62700
63487
  * Build the flat `[[hooks]]` array for `.vibe/hooks.toml` from a canonical
62701
63488
  * hooks config. Vibe uses a flat array where each entry carries its own event
62702
- * `type`, `match` glob/regex (a tool name for tool hooks, an agent name
62703
- * for `post_agent`), and `command`. Only `type: "command"`
62704
- * canonical hooks are emitted: a Vibe hook is a shell command line. (v2.25.1
63489
+ * `type`, `match` glob/regex (a tool name for tool hooks, an agent name for
63490
+ * `post_agent` / `pre_agent` / `pre_llm` / `post_llm`, a source, reason or
63491
+ * notification type for the session and notification hooks), and `command`.
63492
+ * Only `type: "command"` canonical hooks are emitted: a Vibe hook is a shell command line. (v2.25.1
62705
63493
  * to v2.25.4 briefly exec'd it without a shell under the unified harness and
62706
63494
  * skipped any command containing a backslash; v2.25.5 restored shell
62707
63495
  * execution — "Hook commands using pipes, `&&`, redirects, globs or `$VAR`
@@ -62726,27 +63514,23 @@ function canonicalToVibeHooks({ config, toolOverride, logger }) {
62726
63514
  for (const def of defs) {
62727
63515
  if ((def.type ?? "command") !== "command") continue;
62728
63516
  if (typeof def.command !== "string") continue;
62729
- const isToolEvent = VIBE_TOOL_EVENTS.has(vibeEvent);
62730
- let match;
62731
- if (isToolEvent) match = toVibeHookMatch(def.matcher);
62732
- else if (event === "subagentStop") {
62733
- const subagentMatch = toVibeSubagentMatch({
62734
- matcher: def.matcher,
62735
- logger
62736
- });
62737
- if (subagentMatch === null) continue;
62738
- match = subagentMatch;
62739
- } else match = VIBE_MAIN_AGENT_MATCH;
63517
+ const match = toVibeEntryMatch({
63518
+ event,
63519
+ vibeEvent,
63520
+ matcher: def.matcher,
63521
+ logger
63522
+ });
63523
+ if (match === null) continue;
62740
63524
  const index = nextIndexByVibeEvent.get(vibeEvent) ?? 0;
62741
63525
  const entry = {
62742
63526
  name: typeof def.name === "string" ? def.name : `${vibeEvent}-${index}`,
62743
63527
  type: vibeEvent,
62744
- match,
63528
+ ...match !== void 0 && { match },
62745
63529
  command: def.command
62746
63530
  };
62747
63531
  if (typeof def.timeout === "number") entry.timeout = def.timeout;
62748
63532
  const strict = def.strict;
62749
- if (isToolEvent && typeof strict === "boolean") entry.strict = strict;
63533
+ if (VIBE_STRICT_EVENTS.has(vibeEvent) && typeof strict === "boolean") entry.strict = strict;
62750
63534
  if (typeof def.description === "string") entry.description = def.description;
62751
63535
  hooks.push(entry);
62752
63536
  nextIndexByVibeEvent.set(vibeEvent, index + 1);
@@ -62761,22 +63545,22 @@ function vibeEntryToCanonicalDef(raw) {
62761
63545
  const vibeEvent = typeof entry.type === "string" ? entry.type : void 0;
62762
63546
  if (vibeEvent === void 0) return null;
62763
63547
  if (isPrototypePollutionKey(vibeEvent)) return null;
62764
- let canonicalEvent = lookupOwn({
63548
+ const mappedEvent = lookupOwn({
62765
63549
  record: VIBE_TO_CANONICAL_EVENT_NAMES,
62766
63550
  key: vibeEvent
62767
63551
  }) ?? vibeEvent;
62768
63552
  const def = { type: "command" };
62769
63553
  if (typeof entry.command === "string") def.command = entry.command;
62770
- if (vibeEvent === VIBE_POST_AGENT_EVENT) {
62771
- const agentMatch = typeof entry.match === "string" ? entry.match : "";
62772
- if (agentMatch !== "" && agentMatch !== "*" && agentMatch.toLowerCase() !== VIBE_MAIN_AGENT_MATCH) {
62773
- canonicalEvent = "subagentStop";
62774
- def.matcher = agentMatch;
62775
- }
62776
- } else {
62777
- const matcher = fromVibeHookMatch(entry.match);
62778
- if (matcher !== void 0) def.matcher = matcher;
62779
- }
63554
+ const resolved = fromVibeEntryMatch({
63555
+ vibeEvent: lookupOwn({
63556
+ record: CANONICAL_TO_VIBE_EVENT_NAMES,
63557
+ key: mappedEvent
63558
+ }) ?? vibeEvent,
63559
+ canonicalEvent: mappedEvent,
63560
+ match: entry.match
63561
+ });
63562
+ const canonicalEvent = resolved.canonicalEvent;
63563
+ if (resolved.matcher !== void 0) def.matcher = resolved.matcher;
62780
63564
  if (typeof entry.timeout === "number") def.timeout = entry.timeout;
62781
63565
  if (typeof entry.name === "string") def.name = entry.name;
62782
63566
  if (typeof entry.description === "string") def.description = entry.description;
@@ -62810,22 +63594,55 @@ function vibeHooksToCanonical(parsed) {
62810
63594
  /** Vibe reads a `match` with a `re:` prefix or glob metacharacters as a pattern. */
62811
63595
  const VIBE_PATTERN_MATCH = /^re:|[*?[]/;
62812
63596
  /**
62813
- * Move the imported `subagentStop` hooks into the `vibe` override when any of
62814
- * them matches agents by a regex or glob rather than by a literal name. Such a
62815
- * pattern can also select the main agent (a main session answers to its mode
62816
- * name, e.g. `accept-edits`), and other tools would read it as their own
62817
- * matcher syntax, so it is kept Vibe-only. The override replaces the shared
63597
+ * The canonical events whose imported hooks are kept Vibe-only once any of
63598
+ * them carries a matcher, with the reason for the warning. Their matcher
63599
+ * selects Vibe agents, which other tools either drop (Claude Code, with a
63600
+ * warning) or read as their own matcher syntax, so a hook scoped to one agent
63601
+ * — or, for `pre_agent`, to every agent including subagents — would fire
63602
+ * everywhere there. A `subagentStop` hook needs a matcher anyway, so only a
63603
+ * pattern (which may also select the main agent) moves it.
63604
+ */
63605
+ const VIBE_ONLY_AGENT_SCOPED_EVENTS = [
63606
+ {
63607
+ event: "subagentStop",
63608
+ vibeEvent: "post_agent",
63609
+ isVibeOnly: (matcher) => VIBE_PATTERN_MATCH.test(matcher)
63610
+ },
63611
+ {
63612
+ event: "beforeSubmitPrompt",
63613
+ vibeEvent: "pre_agent",
63614
+ isVibeOnly: () => true
63615
+ },
63616
+ {
63617
+ event: "preModelInvocation",
63618
+ vibeEvent: "pre_llm",
63619
+ isVibeOnly: () => true
63620
+ },
63621
+ {
63622
+ event: "postModelInvocation",
63623
+ vibeEvent: "post_llm",
63624
+ isVibeOnly: () => true
63625
+ }
63626
+ ];
63627
+ /**
63628
+ * Move the imported hooks of an agent-matched event into the `vibe` override
63629
+ * when any of them is scoped in a way other tools cannot express (see
63630
+ * {@link VIBE_ONLY_AGENT_SCOPED_EVENTS}). The override replaces the shared
62818
63631
  * list for its event, so the whole list moves to keep every entry on Vibe.
62819
63632
  */
62820
- function takeVibeOnlySubagentStop({ hooks, logger }) {
62821
- const defs = lookupOwn({
62822
- record: hooks,
62823
- key: "subagentStop"
62824
- });
62825
- if (defs === void 0 || !defs.some((def) => typeof def.matcher === "string" && VIBE_PATTERN_MATCH.test(def.matcher))) return;
62826
- delete hooks.subagentStop;
62827
- logger?.warn("Vibe hooks: a post_agent hook matches agents by a pattern, so its subagentStop hooks are imported into the vibe override instead of the shared hooks.");
62828
- return defs;
63633
+ function takeVibeOnlyAgentScopedHooks({ hooks, logger }) {
63634
+ const taken = {};
63635
+ for (const { event, vibeEvent, isVibeOnly } of VIBE_ONLY_AGENT_SCOPED_EVENTS) {
63636
+ const defs = lookupOwn({
63637
+ record: hooks,
63638
+ key: event
63639
+ });
63640
+ if (defs === void 0 || !defs.some((def) => typeof def.matcher === "string" && isVibeOnly(def.matcher))) continue;
63641
+ delete hooks[event];
63642
+ taken[event] = defs;
63643
+ logger?.warn(`Vibe hooks: a ${vibeEvent} hook is scoped by agent in a way other tools cannot express, so its ${event} hooks are imported into the vibe override instead of the shared hooks.`);
63644
+ }
63645
+ return taken;
62829
63646
  }
62830
63647
  function parseVibeToml(fileContent) {
62831
63648
  const parsed = smol_toml.parse(fileContent || smol_toml.stringify({}));
@@ -62877,21 +63694,22 @@ var VibeHooks = class extends ToolHooks {
62877
63694
  displayName: "Vibe",
62878
63695
  parse: (fileContent) => parseVibeToml(fileContent)
62879
63696
  }));
62880
- const vibeOnlySubagentStop = takeVibeOnlySubagentStop({
63697
+ const vibeOnly = takeVibeOnlyAgentScopedHooks({
62881
63698
  hooks,
62882
63699
  logger: options.logger
62883
63700
  });
62884
63701
  const config = buildImportedHooksConfig({
63702
+ logger: options.logger,
62885
63703
  hooks,
62886
63704
  overrideKey: "vibe"
62887
63705
  });
62888
- if (vibeOnlySubagentStop !== void 0) {
63706
+ if (Object.keys(vibeOnly).length > 0) {
62889
63707
  const override = config.vibe ?? {};
62890
63708
  config.vibe = {
62891
63709
  ...override,
62892
63710
  hooks: {
62893
63711
  ...override.hooks,
62894
- subagentStop: vibeOnlySubagentStop
63712
+ ...vibeOnly
62895
63713
  }
62896
63714
  };
62897
63715
  }
@@ -63099,6 +63917,7 @@ var ZcodeHooks = class ZcodeHooks extends ToolHooks {
63099
63917
  logger
63100
63918
  });
63101
63919
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
63920
+ logger,
63102
63921
  hooks,
63103
63922
  overrideKey: "zcode"
63104
63923
  }), null, 2) });
@@ -63183,6 +64002,7 @@ var ZcodePluginHooks = class ZcodePluginHooks extends ToolHooks {
63183
64002
  logger
63184
64003
  });
63185
64004
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
64005
+ logger,
63186
64006
  hooks,
63187
64007
  overrideKey: "zcode"
63188
64008
  }), null, 2) });
@@ -78748,6 +79568,15 @@ const PERMISSION_ACTION_PRIORITY = {
78748
79568
  deny: 2
78749
79569
  };
78750
79570
  /**
79571
+ * A pattern map reordered allow, then ask, then deny, keeping the authored
79572
+ * order within each action. A tool that applies the last matching pattern
79573
+ * then lets the strictest matching rule win. `Object.fromEntries` defines own
79574
+ * properties, so even a `__proto__` pattern survives.
79575
+ */
79576
+ function sortRulesByActionPriority(rules) {
79577
+ return Object.fromEntries(Object.entries(rules).toSorted(([, a], [, b]) => PERMISSION_ACTION_PRIORITY[a] - PERMISSION_ACTION_PRIORITY[b]));
79578
+ }
79579
+ /**
78751
79580
  * Whether `action` should replace `existing` when two canonical rules collapse
78752
79581
  * onto one entry: an empty slot always takes it, otherwise only a strictly
78753
79582
  * stricter action (deny > ask > allow) does.
@@ -80418,7 +81247,13 @@ function splitUrlPattern(withoutScheme) {
80418
81247
  * (so an allowed `example.com` overlaps a restricted `*.pdf`), and an overlap
80419
81248
  * from any of them counts. A host ending in a DNS root dot (`example.com.`)
80420
81249
  * is also compared with one and with all trailing dots removed, in addition
80421
- * to its original reading, so this only ever adds overlaps. A pattern holding
81250
+ * to its original reading, so this only ever adds overlaps. The allow is also
81251
+ * compared without its userinfo, query and fragment
81252
+ * (`https://user@example.com/x?y=1#z` as `example.com/x`), which name no other
81253
+ * host or path, again in addition to its original reading. Only a `?` or `#`
81254
+ * in the path counts as a query or fragment start there, so a `?` glob in the
81255
+ * host is left alone (one in the path is read as a query start for this extra
81256
+ * reading, which can only add overlaps). A pattern holding
80422
81257
  * whitespace names no URL. Callers pass the restriction as `left` and the
80423
81258
  * allow as `right`.
80424
81259
  */
@@ -80441,12 +81276,7 @@ function urlPatternsOverlap(left, right) {
80441
81276
  */
80442
81277
  function wholeStringsOverlap(left, right) {
80443
81278
  const normalizedLeft = normalizeUrlPattern(left);
80444
- const normalizedRight = normalizeUrlPattern(right);
80445
- return [
80446
- [left, right],
80447
- [normalizedLeft, normalizedRight],
80448
- ...normalizedLeft.includes("/") ? [] : [[normalizedLeft, withAnyPath(normalizedRight)]]
80449
- ].some(([restriction = "", allow = ""]) => createShadowingRestrictionsTest([{
81279
+ return [[left, right], ...allowReadings(normalizeUrlPattern(right)).flatMap((normalizedRight) => [[normalizedLeft, normalizedRight], ...normalizedLeft.includes("/") ? [] : [[normalizedLeft, withAnyPath(normalizedRight)]]])].some(([restriction = "", allow = ""]) => createShadowingRestrictionsTest([{
80450
81280
  pattern: restriction,
80451
81281
  fromAllToolsCategory: false
80452
81282
  }])(allow).length > 0);
@@ -80455,8 +81285,25 @@ function wholeStringsOverlap(left, right) {
80455
81285
  function withAnyPath(withoutScheme) {
80456
81286
  return stripUrlSchemeKeepingPathCase(withoutScheme).includes("/") ? withoutScheme : `${withoutScheme}/*`;
80457
81287
  }
81288
+ /**
81289
+ * A scheme-less allow pattern as written, plus (when they differ) the same
81290
+ * pattern without the userinfo before its host and the query and fragment
81291
+ * after its path, so `user:pass@example.com/x?y=1` is also read as
81292
+ * `example.com/x`. A `?` is a single-character glob in Rulesync patterns, so
81293
+ * only a `?` or `#` in the path (after the first `/`) is read as a query or
81294
+ * fragment start; the host keeps it (`git?ub.com` is not cut to `git`). The
81295
+ * original reading stays first, so a caller that ORs the readings only ever
81296
+ * gains overlaps.
81297
+ */
81298
+ function allowReadings(withoutScheme) {
81299
+ const slash = withoutScheme.indexOf("/");
81300
+ const hostPort = slash === -1 ? withoutScheme : withoutScheme.slice(0, slash);
81301
+ const path = slash === -1 ? "" : withoutScheme.slice(slash).replace(/[?#].*$/s, "");
81302
+ const stripped = `${hostPort.slice(hostPort.lastIndexOf("@") + 1)}${path}`;
81303
+ return stripped === withoutScheme || stripped === "" ? [withoutScheme] : [withoutScheme, stripped];
81304
+ }
80458
81305
  function urlPartsOverlap(left, right) {
80459
- const readings = (pattern) => [.../* @__PURE__ */ new Set([stripUrlSchemeKeepingPathCase(pattern), stripUrlSchemeLoosely(pattern)])].map(splitUrlPattern).flatMap((parts) => parts.host.endsWith(".") ? [
81306
+ const readings = (pattern, { asAllow = false } = {}) => [.../* @__PURE__ */ new Set([stripUrlSchemeKeepingPathCase(pattern), stripUrlSchemeLoosely(pattern)])].flatMap((withoutScheme) => asAllow ? allowReadings(withoutScheme) : [withoutScheme]).map(splitUrlPattern).flatMap((parts) => parts.host.endsWith(".") ? [
80460
81307
  parts,
80461
81308
  {
80462
81309
  ...parts,
@@ -80467,7 +81314,8 @@ function urlPartsOverlap(left, right) {
80467
81314
  host: parts.host.replace(/\.+$/, "")
80468
81315
  }
80469
81316
  ] : [parts]);
80470
- return readings(left).some((a) => readings(right).some((b) => urlPartsPairOverlap(a, b)));
81317
+ const allowParts = readings(right, { asAllow: true });
81318
+ return readings(left).some((a) => allowParts.some((b) => urlPartsPairOverlap(a, b)));
80471
81319
  }
80472
81320
  function urlPartsPairOverlap(a, b) {
80473
81321
  const hosts = (host) => [host, `*.${host}`];
@@ -87536,6 +88384,173 @@ function parseCommandcodeRuleLists(permissions) {
87536
88384
  return permission;
87537
88385
  }
87538
88386
  /**
88387
+ * The non-list `permissions` fields rulesync authors through the
88388
+ * `commandcode.permissions` override and imports back. Every other key of the
88389
+ * file's `permissions` object is kept as it is, never written from the source.
88390
+ */
88391
+ const COMMANDCODE_PERMISSIONS_FIELD_KEYS = [
88392
+ "defaultMode",
88393
+ "additionalDirectories",
88394
+ "disableBypass"
88395
+ ];
88396
+ const ACCEPT_EDITS_REASON = "workspace edits and safe filesystem shell commands then run without a prompt";
88397
+ const YOLO_REASON = "every session then starts in permission bypass, where only deny and ask rules still stop a tool";
88398
+ /**
88399
+ * The `permissions.defaultMode` values (aliases included) that start a session
88400
+ * with fewer prompts than `default`. `plan` and `dont-ask` are absent: `plan`
88401
+ * is read-only, and `dont-ask` is a fail-closed allowlist that denies whatever
88402
+ * policy does not already allow, so neither widens anything.
88403
+ *
88404
+ * @see https://commandcode.ai/docs/permissions
88405
+ */
88406
+ const COMMANDCODE_WIDENING_DEFAULT_MODES = {
88407
+ "accept-edits": ACCEPT_EDITS_REASON,
88408
+ "auto-accept": ACCEPT_EDITS_REASON,
88409
+ acceptEdits: ACCEPT_EDITS_REASON,
88410
+ yolo: YOLO_REASON,
88411
+ bypass: YOLO_REASON,
88412
+ bypassPermissions: YOLO_REASON
88413
+ };
88414
+ /**
88415
+ * How many prompts each documented `defaultMode` (aliases included) removes:
88416
+ * `plan` and `dont-ask` (fail-closed) < `default` < `accept-edits` < `yolo`.
88417
+ * Used to notice an override that replaces a stricter mode already in the file.
88418
+ */
88419
+ const COMMANDCODE_DEFAULT_MODE_LOOSENESS = {
88420
+ plan: 0,
88421
+ "dont-ask": 0,
88422
+ dontAsk: 0,
88423
+ default: 1,
88424
+ manual: 1,
88425
+ standard: 1,
88426
+ "accept-edits": 2,
88427
+ "auto-accept": 2,
88428
+ acceptEdits: 2,
88429
+ yolo: 3,
88430
+ bypass: 3,
88431
+ bypassPermissions: 3
88432
+ };
88433
+ /**
88434
+ * Command Code resolves settings project-local > project > user-global, and a
88435
+ * scalar from the more specific file overwrites the others (only the rule
88436
+ * lists and `additionalDirectories` union across files). A project-scope
88437
+ * `defaultMode` or `disableBypass` therefore replaces whatever the user set in
88438
+ * `~/.commandcode/settings.json`.
88439
+ *
88440
+ * @see https://commandcode.ai/docs/settings
88441
+ */
88442
+ const PROJECT_SCALAR_OVERRIDES_GLOBAL = "a project value overrides ~/.commandcode/settings.json, so it also replaces a stricter user-global mode such as dont-ask or plan";
88443
+ /**
88444
+ * The widening entry for a `commandcode.permissions.defaultMode`, or `null`
88445
+ * when it does not widen. A mode that removes prompts always widens; at
88446
+ * project scope so does any mode looser than the strictest ones (`plan`,
88447
+ * `dont-ask`), because it overrides the user-global mode; and so does a mode
88448
+ * looser than the one already in the file. An undocumented mode is warned
88449
+ * about on its own.
88450
+ */
88451
+ function defaultModeWideningEntry({ defaultMode, replaced, global, logger }) {
88452
+ const label = `permissions.defaultMode: "${defaultMode}"`;
88453
+ const projectNote = global ? [] : [PROJECT_SCALAR_OVERRIDES_GLOBAL];
88454
+ const reason = lookupOwn({
88455
+ record: COMMANDCODE_WIDENING_DEFAULT_MODES,
88456
+ key: defaultMode
88457
+ });
88458
+ if (reason !== void 0) return `${label} (${[reason, ...projectNote].join("; ")})`;
88459
+ const looseness = lookupOwn({
88460
+ record: COMMANDCODE_DEFAULT_MODE_LOOSENESS,
88461
+ key: defaultMode
88462
+ });
88463
+ if (looseness === void 0) {
88464
+ logger?.warn(`Command Code permissions: '${label}' is not a mode Command Code documents (default, accept-edits, plan, yolo, dont-ask and their aliases); it was written as authored.`);
88465
+ return null;
88466
+ }
88467
+ const replacedLooseness = typeof replaced === "string" ? lookupOwn({
88468
+ record: COMMANDCODE_DEFAULT_MODE_LOOSENESS,
88469
+ key: replaced
88470
+ }) : void 0;
88471
+ const notes = replacedLooseness !== void 0 && looseness > replacedLooseness ? [`replaces the stricter "${String(replaced)}" already in the file`] : [];
88472
+ if (looseness > 0) notes.push(...projectNote);
88473
+ return notes.length > 0 ? `${label} (${notes.join("; ")})` : null;
88474
+ }
88475
+ /**
88476
+ * Name, in one warning, every `commandcode.permissions` value that widens what
88477
+ * Command Code trusts. At project scope the scalars also override the
88478
+ * user-global file, which the warning says explicitly.
88479
+ */
88480
+ function warnWideningCommandcodeFields({ fields, existingPermissions, global, logger }) {
88481
+ const widening = [];
88482
+ const { defaultMode, additionalDirectories, disableBypass } = fields;
88483
+ if (typeof defaultMode === "string") {
88484
+ const entry = defaultModeWideningEntry({
88485
+ defaultMode,
88486
+ replaced: existingPermissions.defaultMode,
88487
+ global,
88488
+ logger
88489
+ });
88490
+ if (entry !== null) widening.push(entry);
88491
+ }
88492
+ if (Array.isArray(additionalDirectories) && additionalDirectories.length > 0) widening.push("permissions.additionalDirectories (each directory then counts as inside the workspace for reads and writes)");
88493
+ if (disableBypass !== void 0 && disableBypass !== true && disableBypass !== "disable") widening.push(`permissions.disableBypass: ${JSON.stringify(disableBypass)} (` + (global ? "yolo mode then stays enterable from this file" : "a project value overrides the user-global setting, so yolo becomes enterable again even if ~/.commandcode/settings.json disables it") + ")");
88494
+ if (widening.length > 0) logger?.warn(`Command Code permissions: the commandcode override widens what Command Code trusts: ${widening.join("; ")}.`);
88495
+ }
88496
+ /**
88497
+ * The fields of the `commandcode.permissions` override to merge into the
88498
+ * settings file's `permissions` object. Only the documented
88499
+ * `COMMANDCODE_PERMISSIONS_FIELD_KEYS` are written: the `allow`/`ask`/`deny`
88500
+ * lists are rulesync's (built from the shared `permission` block) and any
88501
+ * other key is ignored, so the override can never smuggle a grant past the
88502
+ * list handling. A value that widens trust — a `defaultMode` that removes
88503
+ * prompts (or replaces a stricter one already in the file or, at project
88504
+ * scope, in the user-global file), a non-empty `additionalDirectories`, a
88505
+ * `disableBypass` that does not disable — is still written, but named in one
88506
+ * warning: this file is
88507
+ * shareable through `rulesync fetch`, and a loosening should not be silent.
88508
+ */
88509
+ function commandcodePermissionsFields({ config, existingPermissions, global, logger }) {
88510
+ const override = config.commandcode?.permissions;
88511
+ if (!isRecord(override)) return {};
88512
+ const fields = {};
88513
+ for (const [key, value] of Object.entries(override)) {
88514
+ if (isPrototypePollutionKey(key) || value === void 0) continue;
88515
+ if (!COMMANDCODE_PERMISSIONS_FIELD_KEYS.includes(key)) {
88516
+ logger?.warn(`Command Code permissions: 'commandcode.permissions.${key}' is not written; only ${COMMANDCODE_PERMISSIONS_FIELD_KEYS.join(", ")} are authored there${key === "allow" || key === "ask" || key === "deny" ? " (the shared 'permission' block drives the allow/ask/deny lists)" : ""}.`);
88517
+ continue;
88518
+ }
88519
+ fields[key] = value;
88520
+ }
88521
+ warnWideningCommandcodeFields({
88522
+ fields,
88523
+ existingPermissions,
88524
+ global,
88525
+ logger
88526
+ });
88527
+ return fields;
88528
+ }
88529
+ /**
88530
+ * Read the documented non-list `permissions` fields back for the
88531
+ * `commandcode.permissions` override, verbatim. A value of a type Command Code
88532
+ * does not document is skipped with a warning rather than imported into a
88533
+ * source that would then fail validation; it stays in the settings file,
88534
+ * which a regenerate leaves untouched. Nothing here reaches the shared
88535
+ * `permission` block, so a mode or directory set for Command Code never turns
88536
+ * into a grant for another target.
88537
+ */
88538
+ function importCommandcodePermissionsFields(permissions) {
88539
+ const fields = {};
88540
+ const skip = (key) => fallbackLogger.warn(`Command Code permissions: 'permissions.${key}' holds a value of a type Command Code does not document, so it was not imported; it stays in the Command Code settings.`);
88541
+ const { defaultMode, additionalDirectories, disableBypass } = permissions;
88542
+ if (typeof defaultMode === "string") fields.defaultMode = defaultMode;
88543
+ else if (defaultMode !== void 0) skip("defaultMode");
88544
+ if (Array.isArray(additionalDirectories)) {
88545
+ const directories = additionalDirectories.filter((entry) => typeof entry === "string");
88546
+ if (directories.length < additionalDirectories.length) fallbackLogger.warn("Command Code permissions: 'permissions.additionalDirectories' holds entries that are not strings; only the string entries were imported.");
88547
+ fields.additionalDirectories = directories;
88548
+ } else if (additionalDirectories !== void 0) skip("additionalDirectories");
88549
+ if (typeof disableBypass === "boolean" || disableBypass === "disable") fields.disableBypass = disableBypass;
88550
+ else if (disableBypass !== void 0) skip("disableBypass");
88551
+ return fields;
88552
+ }
88553
+ /**
87539
88554
  * Permissions generator for Command Code.
87540
88555
  *
87541
88556
  * Rules live under the `permissions` key of `.commandcode/settings.json`
@@ -87543,8 +88558,10 @@ function parseCommandcodeRuleLists(permissions) {
87543
88558
  * Claude-style entries: `deny` (always wins), `ask`, `allow`. The same key
87544
88559
  * also carries `defaultMode`, `additionalDirectories` and `disableBypass`,
87545
88560
  * and the file holds `hooks` and other settings, so writes go through the
87546
- * shared-config gateway: rulesync replaces the three lists, keeps every
87547
- * sibling key, and never deletes the file.
88561
+ * shared-config gateway: rulesync replaces the three lists, merges those
88562
+ * three fields from the `commandcode.permissions` override (warning on values
88563
+ * that widen trust), keeps every other sibling key, and never deletes the
88564
+ * file. Import reads the three fields back into that override.
87548
88565
  *
87549
88566
  * Generate: `permission.<category>.<pattern>` becomes `Tool(pattern)` with
87550
88567
  * the friendly names (`Shell`, `Read`, `Edit`, `Write`, `WebFetch`,
@@ -87595,12 +88612,21 @@ var CommandcodePermissions = class CommandcodePermissions extends ToolPermission
87595
88612
  relativePath: (0, node_path.join)(paths.relativeDirPath, paths.relativeFilePath)
87596
88613
  });
87597
88614
  const existingPermissions = isRecord(existing[COMMANDCODE_PERMISSIONS_KEY]) ? existing[COMMANDCODE_PERMISSIONS_KEY] : {};
88615
+ const config = rulesyncPermissions.getJson();
87598
88616
  const lists = buildCommandcodeRuleLists({
87599
- config: rulesyncPermissions.getJson(),
88617
+ config,
87600
88618
  existingPermissions,
87601
88619
  logger
87602
88620
  });
87603
- const permissions = { ...existingPermissions };
88621
+ const permissions = {
88622
+ ...existingPermissions,
88623
+ ...commandcodePermissionsFields({
88624
+ config,
88625
+ existingPermissions,
88626
+ global,
88627
+ logger
88628
+ })
88629
+ };
87604
88630
  for (const key of [
87605
88631
  "allow",
87606
88632
  "ask",
@@ -87628,7 +88654,10 @@ var CommandcodePermissions = class CommandcodePermissions extends ToolPermission
87628
88654
  relativePath: (0, node_path.join)(this.getRelativeDirPath(), this.getRelativeFilePath())
87629
88655
  });
87630
88656
  const permissions = isRecord(settings[COMMANDCODE_PERMISSIONS_KEY]) ? settings[COMMANDCODE_PERMISSIONS_KEY] : {};
87631
- return this.toRulesyncPermissionsDefault({ fileContent: JSON.stringify({ permission: parseCommandcodeRuleLists(permissions) }, null, 2) });
88657
+ const imported = { permission: parseCommandcodeRuleLists(permissions) };
88658
+ const fields = importCommandcodePermissionsFields(permissions);
88659
+ if (Object.keys(fields).length > 0) imported.commandcode = { permissions: fields };
88660
+ return this.toRulesyncPermissionsDefault({ fileContent: JSON.stringify(imported, null, 2) });
87632
88661
  }
87633
88662
  };
87634
88663
  /**
@@ -88728,9 +89757,11 @@ function effectiveSafeCommandLine(entry) {
88728
89757
  * and without a Windows executable suffix. A `*` in the command word may
88729
89758
  * stand for a directory and part of a name, so when what follows it is the
88730
89759
  * tail of a wrapper name, everything before it collapses into `*`
88731
- * (`b*nice` -> `*nice`, `/u*v` -> `*v`; `rm*` is left alone). The rest of the pattern is lower-cased as well, for a
88732
- * nested wrapper spelled in another case. Used only to compare against the
88733
- * wrapper spellings of a safe line, where it can only withhold more.
89760
+ * (`b*nice` -> `*nice`, `/u*v` -> `*v`; `rm*` is left alone). The rest of
89761
+ * the pattern is lower-cased as well, for a nested wrapper spelled in another
89762
+ * case. Used only to compare against a lower-cased safe line, its `--` form
89763
+ * and its wrapper spellings. Lower-casing the arguments too can only withhold
89764
+ * more: a `go BUILD` deny also withholds `go build` (fail-closed).
88734
89765
  */
88735
89766
  function normalizeRestrictionCommandWord(pattern) {
88736
89767
  const space = pattern.indexOf(" ");
@@ -88747,9 +89778,9 @@ function normalizeRestrictionCommandWord(pattern) {
88747
89778
  * rules govern a command Crush would approve through it? Besides the line
88748
89779
  * itself, Crush approves it followed by `--` and behind a wrapper (or the
88749
89780
  * `time` keyword), whose name it normalizes (`./nice`, `/usr/bin/env`, `NICE`,
88750
- * `nohup.exe`). The line and its wrapper spellings are compared against the
88751
- * restrictions as written, and the wrapper spellings also against the
88752
- * restrictions with their command word normalized the same way — which keeps
89781
+ * `nohup.exe`). The line, its `--` form and its wrapper spellings are compared
89782
+ * against both the restrictions as written and those with their command word
89783
+ * normalized like Crush (including executable paths and case) — which keeps
88753
89784
  * an unrelated `rm *` from withholding the line, as a leading wildcard on the
88754
89785
  * spelling would. Canonically the stricter rule wins whatever its width
88755
89786
  * (`deny > ask > allow`), so any overlap withholds the line.
@@ -88773,7 +89804,7 @@ function createSafeCommandShadowTest(permission) {
88773
89804
  });
88774
89805
  const withSeparator = (spellings) => spellings.flatMap((spelling) => [spelling, `${spelling} --*`]);
88775
89806
  const wrapped = (base) => CRUSH_COMMAND_PREFIXES.map((prefix) => `${prefix}*${base}`);
88776
- return (line) => uniq$11([...withSeparator([line, ...wrapped(line)]).flatMap((spelling) => test(spelling)), ...withSeparator(wrapped(line.toLowerCase())).flatMap((spelling) => testNormalized(spelling).map((pattern) => originalOf.get(pattern) ?? pattern))]);
89807
+ return (line) => uniq$11([...withSeparator([line, ...wrapped(line)]).flatMap((spelling) => test(spelling)), ...withSeparator([line.toLowerCase(), ...wrapped(line.toLowerCase())]).flatMap((spelling) => testNormalized(spelling).map((pattern) => originalOf.get(pattern) ?? pattern))]);
88777
89808
  }
88778
89809
  function uniq$11(values) {
88779
89810
  return [...new Set(values)];
@@ -92544,7 +93575,14 @@ function convertJunieToRulesyncPermissions({ allowlist }) {
92544
93575
  * restriction is restated at the end of every other key that holds a looser
92545
93576
  * rule it overlaps, where it is matched after that rule. A `*` catch-all
92546
93577
  * (`{"*": {"*": "ask"}}` followed by per-tool allows) is the documented way to
92547
- * set an OpenCode default, so it is left where it is.
93578
+ * set an OpenCode default, so it is not restated in the later keys.
93579
+ *
93580
+ * The `*` key's own patterns are reordered allow, then ask, then deny, so the
93581
+ * strictest matching one wins there too. This disables an allow carve-out
93582
+ * under a broader ask or deny in that key (`{"*": "deny", "src/**": "allow"}`
93583
+ * denies `src/**` as well), so a warning is logged whenever the order changes,
93584
+ * unless `<target>.permission["*"]` (`allToolsOverridden`) replaces the key
93585
+ * with an exact order anyway.
92548
93586
  *
92549
93587
  * A restated rule must never land after an overlapping stricter one, or it
92550
93588
  * would loosen what that rule says. The tail of a key is therefore written
@@ -92553,15 +93591,23 @@ function convertJunieToRulesyncPermissions({ allowlist }) {
92553
93591
  * then the restated `*` denies. A key whose own catch-all is a deny covers
92554
93592
  * every input of a restated ask already, so such an ask is restated as a deny.
92555
93593
  */
92556
- function restateAllToolsRestrictionsLast(sharedPermission) {
93594
+ function restateAllToolsRestrictionsLast({ sharedPermission, toolTarget, allToolsOverridden = false, logger }) {
92557
93595
  const allToolsRules = Object.hasOwn(sharedPermission, "*") ? sharedPermission["*"] : void 0;
92558
93596
  const restrictions = Object.entries(allToolsRules ?? {}).filter(([pattern, action]) => action !== "allow" && pattern !== "*" && !isPrototypePollutionKey(pattern));
92559
- if (restrictions.length === 0) return sharedPermission;
93597
+ if (restrictions.length === 0 && !allToolsRules) return sharedPermission;
92560
93598
  const result = {};
92561
- for (const [key, rules] of Object.entries(sharedPermission)) result[key] = key === "*" ? rules : restateInKey({
92562
- rules,
92563
- restrictions
92564
- });
93599
+ for (const [key, rules] of Object.entries(sharedPermission)) {
93600
+ if (key !== "*") {
93601
+ result[key] = restateInKey({
93602
+ rules,
93603
+ restrictions
93604
+ });
93605
+ continue;
93606
+ }
93607
+ const sorted = sortRulesByActionPriority(rules);
93608
+ if (!allToolsOverridden && !(0, node_util.isDeepStrictEqual)(Object.keys(sorted), Object.keys(rules))) logger?.warn(`The all-tools "*" permission patterns were reordered allow, ask, deny because ${toolTarget} applies the last matching pattern and the stricter rule must win, which may disable a looser carve-out under a broader ask or deny pattern (e.g. "*": "deny", "src/**": "allow"). Set ${toolTarget}.permission["*"] to control the exact order.`);
93609
+ result[key] = sorted;
93610
+ }
92565
93611
  return result;
92566
93612
  }
92567
93613
  function globsOverlap(left, right) {
@@ -92813,7 +93859,12 @@ var KiloPermissions = class KiloPermissions extends ToolPermissions {
92813
93859
  const rulesyncJson = rulesyncPermissions.getJson();
92814
93860
  const kiloOverride = rulesyncJson.kilo;
92815
93861
  const incomingPermission = {
92816
- ...restateAllToolsRestrictionsLast(honorAllToolsOnBash(rulesyncJson.permission)),
93862
+ ...restateAllToolsRestrictionsLast({
93863
+ sharedPermission: honorAllToolsOnBash(rulesyncJson.permission),
93864
+ toolTarget: "kilo",
93865
+ allToolsOverridden: Object.hasOwn(kiloOverride?.permission ?? {}, "*"),
93866
+ logger
93867
+ }),
92817
93868
  ...kiloOverride?.permission
92818
93869
  };
92819
93870
  if (!global && Object.hasOwn(incomingPermission, KILO_MARKDOWN_SOURCE_KEY)) {
@@ -94425,7 +95476,7 @@ function mergePatternRules(base, incoming) {
94425
95476
  action,
94426
95477
  existing: Object.hasOwn(merged, pattern) ? merged[pattern] : void 0
94427
95478
  })) merged[pattern] = action;
94428
- return Object.fromEntries(Object.entries(merged).toSorted(([, a], [, b]) => PERMISSION_ACTION_PRIORITY[a] - PERMISSION_ACTION_PRIORITY[b]));
95479
+ return sortRulesByActionPriority(merged);
94429
95480
  }
94430
95481
  function toCanonicalPermissionKey(opencodeKey) {
94431
95482
  return lookupOwn({
@@ -94486,7 +95537,7 @@ function fromOpencodeV2PermissionRules(rules) {
94486
95537
  * written under the key OpenCode actually reads. A folded `write` is merged
94487
95538
  * with any canonical `edit` rules rather than replacing them.
94488
95539
  */
94489
- function toOpencodeSharedPermission({ permission, toolTarget, logger }) {
95540
+ function toOpencodeSharedPermission({ permission, toolTarget, allToolsOverridden, logger }) {
94490
95541
  const sharedPermission = {};
94491
95542
  for (const [category, value] of Object.entries(honorAllToolsOnBash(permission))) {
94492
95543
  if (OPENCODE_UNSUPPORTED_PERMISSION_CATEGORIES.has(category)) {
@@ -94507,7 +95558,12 @@ function toOpencodeSharedPermission({ permission, toolTarget, logger }) {
94507
95558
  sharedPermission[key] = merged;
94508
95559
  } else sharedPermission[key] = value;
94509
95560
  }
94510
- return restateAllToolsRestrictionsLast(sharedPermission);
95561
+ return restateAllToolsRestrictionsLast({
95562
+ sharedPermission,
95563
+ toolTarget,
95564
+ allToolsOverridden,
95565
+ logger
95566
+ });
94511
95567
  }
94512
95568
  const OpencodePermissionsConfigSchema = zod_mini.z.looseObject({
94513
95569
  permission: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.enum([
@@ -94611,6 +95667,7 @@ var OpencodePermissions = class extends ToolPermissions {
94611
95667
  const sharedPermission = toOpencodeSharedPermission({
94612
95668
  permission: rulesyncJson.permission ?? {},
94613
95669
  toolTarget: this.layout.toolTarget,
95670
+ allToolsOverridden: Object.hasOwn(overridePermission, "*"),
94614
95671
  logger
94615
95672
  });
94616
95673
  const isV2 = this.layout.configVersion === "v2";
@@ -100212,28 +101269,31 @@ function parseTraePermissionConfig({ fileContent, relativePath }) {
100212
101269
  const moduleLogger = fallbackLogger;
100213
101270
  /**
100214
101271
  * Vibe's builtin tool names are the snake_case of each tool class
100215
- * (`BaseTool.get_name()`): `Edit` → `edit`, `WebFetch` → `web_fetch`,
100216
- * `WebSearch` → `web_search`, alongside `read_file`, `write_file` and `bash`.
101272
+ * (`BaseTool.get_name()`): `Edit` → `edit`, alongside `read_file`,
101273
+ * `write_file` and `bash`.
100217
101274
  * `edit` and `write_file` are distinct tools — `write_file` has been
100218
101275
  * create-only since v2.14.0 — so the canonical `edit` and `write` categories
100219
101276
  * must not collapse onto one name.
100220
101277
  *
100221
- * `grep` and `agent` have no table here: since v3.0.0 every session runs on
100222
- * the Unified Harness, which reads `[tools.*]` only for its Rust builtins
100223
- * (`RUST_BUILTIN_TOOL_SOURCES`). There is no grep tool any more — searching
100224
- * goes through the shell — and subagents are spawned by the built-in
100225
- * `agents.spawn` tool, which the `enable_subagents` switch governs instead of
100226
- * a `[tools.task]` table. See {@link VIBE_RETIRED_TOOL_TABLES}.
101278
+ * `grep`, `agent`, `webfetch` and `websearch` have no table here: since
101279
+ * v3.0.0 every session runs on the Unified Harness, which reads `[tools.*]`
101280
+ * only for its Rust builtins (`RUST_BUILTIN_TOOL_SOURCES`). There is no grep
101281
+ * tool any more — searching goes through the shell — and subagents are
101282
+ * spawned by the built-in `agents.spawn` tool, which the `enable_subagents`
101283
+ * switch governs instead of a `[tools.task]` table. `web_fetch` and
101284
+ * `web_search` are in Vibe's `RETIRED_TOOL_NAMES`: pages are fetched and the
101285
+ * web searched by the `connector_web_search_open_url` /
101286
+ * `connector_web_search_web_search` connector tools. See
101287
+ * {@link VIBE_RETIRED_TOOL_TABLES}.
100227
101288
  * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.2/vibe/app_server/_unified_permissions.py
100228
101289
  * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.2/vibe/app_server/_ignored_tool_settings.py
101290
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/config/_setting_keys.py
100229
101291
  */
100230
101292
  const CANONICAL_TO_VIBE_TOOL_NAMES = {
100231
101293
  bash: "bash",
100232
101294
  read: "read_file",
100233
101295
  edit: "edit",
100234
- write: "write_file",
100235
- webfetch: "web_fetch",
100236
- websearch: "web_search"
101296
+ write: "write_file"
100237
101297
  };
100238
101298
  /**
100239
101299
  * The tables earlier rulesync versions wrote for canonical categories that
@@ -100241,15 +101301,38 @@ const CANONICAL_TO_VIBE_TOOL_NAMES = {
100241
101301
  * effect"), `[tools.task]` for the subagent tool v3.0.0 renamed to
100242
101302
  * `agents.*`, and `[tools.external_directory]` — Vibe has no such tool, and
100243
101303
  * its unused-settings check skips unknown tool names as custom/MCP tools, so
100244
- * that deny was silently inert. A regenerate that configures the category removes them — and
100245
- * the matching `disabled_tools` entry — instead of leaving an inert table.
101304
+ * that deny was silently inert. `[tools.web_fetch]` / `[tools.web_search]`
101305
+ * are inert for the same reason: Vibe 3.x retired both tools, and v3.1.3 warns
101306
+ * about a tool filter naming them. A regenerate that configures the category
101307
+ * removes them — and the matching `disabled_tools` entry — instead of leaving
101308
+ * an inert table.
100246
101309
  * Import still reads them (see {@link VIBE_TO_CANONICAL_TOOL_NAMES}), so a
100247
101310
  * Vibe 2.x config is lifted into the canonical categories rather than lost.
100248
101311
  */
100249
101312
  const VIBE_RETIRED_TOOL_TABLES = {
100250
101313
  grep: "grep",
100251
101314
  agent: "task",
100252
- external_directory: "external_directory"
101315
+ external_directory: "external_directory",
101316
+ webfetch: "web_fetch",
101317
+ websearch: "web_search"
101318
+ };
101319
+ /**
101320
+ * The connector tools that replaced Vibe's retired web builtins, by canonical
101321
+ * category, so the skip warning can say where to write the rule instead.
101322
+ * rulesync does not write them itself: whether their `allowlist` / `denylist`
101323
+ * keys carry the old tools' semantics is not documented upstream.
101324
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/config/_setting_keys.py
101325
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/plugins/builtins/vibe/skills/vibe/SKILL.md
101326
+ */
101327
+ const VIBE_WEB_CONNECTOR_TOOLS = {
101328
+ webfetch: {
101329
+ retired: "web_fetch",
101330
+ connector: "connector_web_search_open_url"
101331
+ },
101332
+ websearch: {
101333
+ retired: "web_search",
101334
+ connector: "connector_web_search_web_search"
101335
+ }
100253
101336
  };
100254
101337
  /** The canonical category Vibe's `enable_subagents` switch expresses. */
100255
101338
  const VIBE_SUBAGENT_CATEGORY = "agent";
@@ -100625,7 +101708,7 @@ function retireLegacyToolTables({ permission, tools, disabledTools, logger }) {
100625
101708
  }
100626
101709
  if (disabledTools.delete(legacyToolName)) removed.push(`disabled_tools entry '${legacyToolName}'`);
100627
101710
  }
100628
- if (removed.length > 0) logger?.warn(`Removed ${removed.join(", ")} from the Vibe config: Vibe 3.x does not read [tools.grep], the former 'task' subagent tool or an 'external_directory' tool (the 'external_directory' category is written to outside_workdir instead), so those entries had no effect.`);
101711
+ if (removed.length > 0) logger?.warn(`Removed ${removed.join(", ")} from the Vibe config: Vibe 3.x does not read [tools.grep], the former 'task' subagent tool, an 'external_directory' tool (the 'external_directory' category is written to outside_workdir instead) or the retired 'web_fetch' / 'web_search' tools, so those entries had no effect.`);
100629
101712
  }
100630
101713
  /**
100631
101714
  * Report the rules of a category that has no Vibe tool table. `grep` gets its
@@ -100641,6 +101724,14 @@ function warnOnUnmappedCategory({ category, rules, logger }) {
100641
101724
  logger?.warn(`Vibe has no grep tool (searching goes through the shell, so 'rg' and 'grep' follow [tools.bash]); skipping ${ruleCount} 'grep' rule(s). Author a 'bash' rule such as "grep *" or "rg *" to restrict searching on Vibe.`);
100642
101725
  return;
100643
101726
  }
101727
+ const webTool = lookupOwn({
101728
+ record: VIBE_WEB_CONNECTOR_TOOLS,
101729
+ key: category
101730
+ });
101731
+ if (webTool !== void 0) {
101732
+ logger?.warn(`Vibe 3.x retired its '${webTool.retired}' tool (web access goes through the '${webTool.connector}' connector tool); skipping ${ruleCount} '${category}' rule(s) instead of emitting an inert [tools.${webTool.retired}] table. Author a '${webTool.connector}' rule (a '*' deny adds it to disabled_tools) to restrict it on Vibe.`);
101733
+ return;
101734
+ }
100644
101735
  logger?.warn(`Vibe has no tool table for the '${category}' category; skipping ${ruleCount} rule(s) instead of emitting an inert [tools.${category}] table.`);
100645
101736
  }
100646
101737
  /**
@@ -100851,7 +101942,7 @@ function retireWithheldAllows({ source, permission, tools, resolveNames }) {
100851
101942
  fromAllToolsCategory: false
100852
101943
  }));
100853
101944
  const globShadowed = createShadowingRestrictionsTest(restrictions);
100854
- const shadowed = (pattern) => category === "webfetch" ? restrictions.some((restriction) => urlPatternsOverlap(restriction.pattern, pattern)) : globShadowed(pattern).length > 0;
101945
+ const shadowed = (pattern) => globShadowed(pattern).length > 0;
100855
101946
  const retires = (pattern) => withheld.has(pattern) || restrictions.length > 0 && honored[pattern] !== "allow" && shadowed(pattern);
100856
101947
  for (const vibeToolName of resolveNames(category) ?? []) {
100857
101948
  if (!Object.hasOwn(tools, vibeToolName)) continue;