rulesync 43.9.2 → 43.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -827,7 +827,8 @@ const skillsProcessorToolTargetTuple = [
827
827
  "zed",
828
828
  "zoocode",
829
829
  "dsh",
830
- "lettacode"
830
+ "lettacode",
831
+ "openclaw"
831
832
  ];
832
833
  const hooksProcessorToolTargetTuple = [
833
834
  "amp",
@@ -5183,7 +5184,8 @@ const HookDefinitionSchema = z.looseObject({
5183
5184
  asyncRewake: z.optional(z.boolean()),
5184
5185
  rewakeMessage: z.optional(safeString),
5185
5186
  rewakeSummary: z.optional(safeString),
5186
- continueOnBlock: z.optional(z.boolean())
5187
+ continueOnBlock: z.optional(z.boolean()),
5188
+ strictJsonOutput: z.optional(z.boolean())
5187
5189
  });
5188
5190
  /**
5189
5191
  * All canonical hook event names.
@@ -6824,41 +6826,55 @@ const JUNIE_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_JUNIE_EVENT_NAM
6824
6826
  /**
6825
6827
  * Map canonical camelCase event names to Mistral Vibe snake_case.
6826
6828
  *
6827
- * Vibe documents three hook events. The canonical `stop` and `subagentStop`
6828
- * events both map to Vibe's `post_agent` (fires after every assistant turn
6829
- * ending without pending tool calls); the adapter tells them apart with the
6830
- * hook's `match` on the agent name (`main` for the main agent).
6829
+ * The canonical `stop` and `subagentStop` events both map to Vibe's
6830
+ * `post_agent` (fires after every assistant turn ending without pending tool
6831
+ * calls); the adapter tells them apart with the hook's `match` on the agent
6832
+ * name (`main` for the main agent). v3.1.1 added `pre_agent`, `notification`,
6833
+ * `session_start` and `session_end`, and v3.1.3 added `pre_llm` and
6834
+ * `post_llm`.
6831
6835
  *
6832
- * These are the v2.21.0 names; the pre-2.21.0 spellings (`before_tool`,
6836
+ * These are the v2.21.0+ names; the pre-2.21.0 spellings (`before_tool`,
6833
6837
  * `after_tool`, `post_agent_turn`) are rejected by Vibe's strict `HookType`
6834
6838
  * enum.
6835
- * @see https://github.com/mistralai/mistral-vibe/blob/main/README.md
6839
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/hooks/models.py
6836
6840
  */
6837
6841
  const CANONICAL_TO_VIBE_EVENT_NAMES = {
6838
6842
  preToolUse: "pre_tool",
6839
6843
  postToolUse: "post_tool",
6840
6844
  stop: "post_agent",
6841
- subagentStop: "post_agent"
6845
+ subagentStop: "post_agent",
6846
+ beforeSubmitPrompt: "pre_agent",
6847
+ notification: "notification",
6848
+ sessionStart: "session_start",
6849
+ sessionEnd: "session_end",
6850
+ preModelInvocation: "pre_llm",
6851
+ postModelInvocation: "post_llm"
6842
6852
  };
6843
6853
  /**
6844
6854
  * Hook events supported by Mistral Vibe (mistral-vibe).
6845
6855
  *
6846
- * Vibe exposes three hook events in `.vibe/hooks.toml`: `pre_tool` ←
6847
- * `preToolUse`, `post_tool` ← `postToolUse`, and `post_agent` ← `stop` /
6848
- * `subagentStop`. `post_agent` fires after every assistant turn that ends
6849
- * without pending tool calls, for the main agent and (since v3.0.2) for every
6850
- * subagent. v3.0.3 lets a `post_agent` hook take a `match` on the agent that
6851
- * finished its turn: the reserved alias `main` selects the main agent, so
6852
- * canonical `stop` becomes `post_agent` with `match = "main"`, and a canonical
6853
- * `subagentStop` with a matcher becomes `post_agent` with that agent name as
6854
- * `match`. Only the tool events (`pre_tool`/`post_tool`) carry the `strict`
6855
- * flag. Only `type: "command"` hooks are relevant.
6856
- *
6857
- * v2.21.0 graduated hooks from experimental and renamed all three types
6858
- * (`before_tool` → `pre_tool`, `after_tool` → `post_tool`, `post_agent_turn` →
6859
- * `post_agent`). `HookType` is a strict enum, so an entry using an old name is
6860
- * rejected outright and reported as a `HookConfigIssue`.
6861
- * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.3/README.md
6856
+ * Vibe reads hooks from `.vibe/hooks.toml`: `pre_tool` ← `preToolUse`,
6857
+ * `post_tool` ← `postToolUse`, `post_agent` ← `stop` / `subagentStop`,
6858
+ * `pre_agent` ← `beforeSubmitPrompt`, `notification` ← `notification`,
6859
+ * `session_start` ← `sessionStart`, `session_end` ← `sessionEnd`, `pre_llm` ←
6860
+ * `preModelInvocation` and `post_llm` ← `postModelInvocation`.
6861
+ *
6862
+ * `post_agent`, `pre_agent`, `pre_llm` and `post_llm` take a `match` on the
6863
+ * agent whose turn it is: the reserved alias `main` selects the main agent, so
6864
+ * canonical `stop` and `beforeSubmitPrompt` are written with `match = "main"`.
6865
+ * `session_start` matches the source (`startup` / `resume` / `clear` /
6866
+ * `fork`), `session_end` the reason (`exit` / `clear` / `other`) and
6867
+ * `notification` the notification type (`approval_requested` /
6868
+ * `question_asked` / `turn_completed` / `turn_failed`). The `strict` flag is
6869
+ * valid on `pre_tool`, `post_tool`, `pre_agent`, `pre_llm` and `post_llm`
6870
+ * (`STRICT_HOOK_TYPES`). Only `type: "command"` hooks are relevant.
6871
+ *
6872
+ * v2.21.0 graduated hooks from experimental and renamed all three original
6873
+ * types (`before_tool` → `pre_tool`, `after_tool` → `post_tool`,
6874
+ * `post_agent_turn` → `post_agent`). `HookType` is a strict enum, so an entry
6875
+ * using an old name is rejected outright and reported as a `HookConfigIssue`.
6876
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/hooks/models.py
6877
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/plugins/builtins/vibe/skills/vibe/SKILL.md
6862
6878
  */
6863
6879
  const VIBE_HOOK_EVENTS = eventsOf(CANONICAL_TO_VIBE_EVENT_NAMES);
6864
6880
  /**
@@ -8428,6 +8444,31 @@ const ClaudecodePermissionsOverrideSchema = z.looseObject({
8428
8444
  sandbox: z.optional(z.looseObject({}))
8429
8445
  });
8430
8446
  /**
8447
+ * Tool-scoped override block for Command Code. The `permissions` object of
8448
+ * `.commandcode/settings.json` carries three documented non-list fields with
8449
+ * no canonical permission category: `defaultMode` (the session-start mode:
8450
+ * `default`, `accept-edits`, `plan`, `yolo` or `dont-ask`, plus the aliases
8451
+ * Command Code accepts such as `bypassPermissions` or `acceptEdits`),
8452
+ * `additionalDirectories` (extra directories treated as inside the workspace)
8453
+ * and `disableBypass` (`"disable"` or `true` makes `yolo` impossible to enter). Only
8454
+ * these three are written; the managed `allow`/`ask`/`deny` lists stay driven
8455
+ * by the shared `permission` block, and any other key placed here is ignored
8456
+ * with a warning. Values that widen trust are written with a warning.
8457
+ *
8458
+ * @example
8459
+ * { "permissions": { "defaultMode": "plan", "disableBypass": true } }
8460
+ * @see https://commandcode.ai/docs/permissions
8461
+ */
8462
+ const CommandcodePermissionsFieldsSchema = z.looseObject({
8463
+ defaultMode: z.optional(z.string()),
8464
+ additionalDirectories: z.optional(z.array(z.string())),
8465
+ disableBypass: z.optional(z.union([z.literal("disable"), z.boolean()]))
8466
+ });
8467
+ const CommandcodePermissionsOverrideSchema = z.looseObject({
8468
+ permission: z.optional(ToolScopedPermissionSchema),
8469
+ permissions: z.optional(CommandcodePermissionsFieldsSchema)
8470
+ });
8471
+ /**
8431
8472
  * Tool-scoped override block for Mistral Vibe. Vibe's per-tool `BaseToolConfig`
8432
8473
  * carries a `sensitive_patterns` list — patterns that escalate to ASK even when
8433
8474
  * the tool's base permission is ALWAYS (allow). The canonical model can only set
@@ -9703,7 +9744,7 @@ const PermissionsConfigSchema = z.looseObject({
9703
9744
  continue: z.optional(CanonicalPermissionsOverrideSchema),
9704
9745
  copilot: z.optional(CopilotPermissionsOverrideSchema),
9705
9746
  codebuddy: z.optional(CodebuddyPermissionsOverrideSchema),
9706
- commandcode: z.optional(CanonicalPermissionsOverrideSchema),
9747
+ commandcode: z.optional(CommandcodePermissionsOverrideSchema),
9707
9748
  lettacode: z.optional(CanonicalPermissionsOverrideSchema),
9708
9749
  crush: z.optional(CanonicalPermissionsOverrideSchema),
9709
9750
  goose: z.optional(CanonicalPermissionsOverrideSchema),
@@ -11544,6 +11585,15 @@ const RulesyncSkillFrontmatterSchema = z.looseObject({
11544
11585
  "disable-model-invocation": z.optional(z.boolean()),
11545
11586
  "user-invocable": z.optional(z.boolean())
11546
11587
  })),
11588
+ openclaw: z.optional(z.looseObject({
11589
+ homepage: z.optional(z.string()),
11590
+ "user-invocable": z.optional(z.boolean()),
11591
+ "disable-model-invocation": z.optional(z.boolean()),
11592
+ "command-dispatch": z.optional(z.string()),
11593
+ "command-tool": z.optional(z.string()),
11594
+ "command-arg-mode": z.optional(z.string()),
11595
+ metadata: z.optional(z.looseObject({}))
11596
+ })),
11547
11597
  reasonix: z.optional(z.looseObject({
11548
11598
  invocation: z.optional(z.string()),
11549
11599
  "disable-model-invocation": z.optional(z.boolean()),
@@ -11623,6 +11673,13 @@ const RulesyncSkillFrontmatterSchema = z.looseObject({
11623
11673
  "when-to-use": z.optional(z.string()),
11624
11674
  paths: z.optional(z.union([z.string(), z.array(z.string())]))
11625
11675
  })),
11676
+ firebender: z.optional(z.looseObject({
11677
+ version: z.optional(z.unknown()),
11678
+ autoTrigger: z.optional(z.boolean()),
11679
+ "disable-model-invocation": z.optional(z.boolean()),
11680
+ projectTypes: z.optional(z.union([z.string(), z.array(z.string())])),
11681
+ icon: z.optional(z.string())
11682
+ })),
11626
11683
  zcode: z.optional(z.looseObject({
11627
11684
  when_to_use: z.optional(z.string()),
11628
11685
  license: z.optional(z.string()),
@@ -11912,9 +11969,9 @@ async function getLocalSkillDirNames(sourceTree) {
11912
11969
  * The rulesync skill frontmatter exposes a root-level `disable-model-invocation`
11913
11970
  * default that applies to every tool supporting the flag (claudecode, codebuddy, copilot,
11914
11971
  * copilotcli, crush, cursor, zed, pi, omp, qwencode, vibe, grokcli, factorydroid, dsh, reasonix,
11915
- * commandcode, lettacode, opencode, opencodev1, mimocode, xum). Each tool's own section may override that
11916
- * default with a per-target value. A defined section value (including `false`)
11917
- * always wins over the root default.
11972
+ * commandcode, lettacode, opencode, opencodev1, mimocode, xum, firebender). Each tool's own section
11973
+ * may override that default with a per-target value. A defined section value
11974
+ * (including `false`) always wins over the root default.
11918
11975
  *
11919
11976
  * `devin` also consumes the root-level value — it maps `true` onto a user-only
11920
11977
  * `triggers` list (see `devin-skill.ts`) — but has no section key of the same
@@ -17489,7 +17546,7 @@ const COMMANDCODE_SKILLS_DIR_PATH = join(COMMANDCODE_DIR, "skills");
17489
17546
  * (Command Code would send it as prompt text; a rulesync command carries its
17490
17547
  * own frontmatter) and only the body is kept.
17491
17548
  *
17492
- * @see https://commandcode.ai/docs/custom-slash-commands
17549
+ * @see https://commandcode.ai/docs/reference/slash-commands#custom-slash-commands
17493
17550
  */
17494
17551
  var CommandcodeCommand = class CommandcodeCommand extends ToolCommand {
17495
17552
  static getSettablePaths(_options = {}) {
@@ -20998,12 +21055,25 @@ function raiseOpencodeAgentToV2(fields) {
20998
21055
  }
20999
21056
  const OPENCODE_FILE_TEMPLATE_PATTERN = /^\s*\{file:(.+?)\}\s*$/;
21000
21057
  /**
21058
+ * Resolves the path of a `{file:...}` reference the way OpenCode does: relative
21059
+ * to the config file's directory, absolute as written, or from the home
21060
+ * directory when it starts with `~/`.
21061
+ *
21062
+ * @see https://opencode.ai/docs/config/#files
21063
+ */
21064
+ function resolveOpencodeFileTemplatePath({ referencedPath, configDir }) {
21065
+ if (referencedPath.startsWith("~/")) return join(getHomeDirectory(), referencedPath.slice(2));
21066
+ if (isAbsolute(referencedPath)) return referencedPath;
21067
+ return join(configDir, referencedPath);
21068
+ }
21069
+ /**
21001
21070
  * Resolves an OpenCode `{file:./path}` string reference into the referenced
21002
21071
  * file's contents. OpenCode resolves these paths relative to the config file's
21003
21072
  * location, so `configDir` must be the directory holding `opencode.json`. When
21004
21073
  * the value is not a whole-value file reference it is returned unchanged; when
21005
21074
  * the referenced file cannot be read the literal value is preserved (so the
21006
- * reference is not silently lost).
21075
+ * reference is not silently lost). As in OpenCode, an absolute path is used as
21076
+ * written and a path starting with `~/` is taken from the home directory.
21007
21077
  *
21008
21078
  * When `containmentRoot` is given (project scope), a reference whose real
21009
21079
  * location — every `..` segment and symbolic link resolved — lies outside it is
@@ -21021,7 +21091,10 @@ async function resolveOpencodeFileTemplate({ value, configDir, containmentRoot,
21021
21091
  if (!match) return value;
21022
21092
  const referencedPath = match[1]?.trim().replace(/^\.\//, "");
21023
21093
  if (!referencedPath) return value;
21024
- const targetPath = join(configDir, referencedPath);
21094
+ const targetPath = resolveOpencodeFileTemplatePath({
21095
+ referencedPath,
21096
+ configDir
21097
+ });
21025
21098
  if (containmentRoot === void 0) return await readFileContentOrNull(targetPath) ?? value;
21026
21099
  const relativePath = await resolvedRelativePath({
21027
21100
  rootPath: containmentRoot,
@@ -26437,18 +26510,86 @@ var FactorydroidSkill = class FactorydroidSkill extends ToolSkill {
26437
26510
  };
26438
26511
  // src/features/skills/firebender-skill.ts
26439
26512
  /**
26513
+ * The Agent Skills standard keys the `agentsskills` section carries. On import
26514
+ * they go back there, exactly as for the `agentsskills` target, and every other
26515
+ * key besides `name` / `description` goes into the `firebender` section.
26516
+ */
26517
+ const AGENT_SKILLS_STANDARD_KEYS$1 = /* @__PURE__ */ new Set([
26518
+ "name",
26519
+ "description",
26520
+ "license",
26521
+ "compatibility",
26522
+ "metadata",
26523
+ "allowed-tools"
26524
+ ]);
26525
+ /**
26440
26526
  * Firebender skills follow the Agent Skills layout (`<name>/SKILL.md` with the
26441
26527
  * required `name` and `description` frontmatter, plus optional supporting
26442
26528
  * files), so this target reuses {@link AgentsSkillsSkill} with Firebender's
26443
26529
  * recommended locations: `.firebender/skills/` (project) and
26444
26530
  * `~/.firebender/skills/` (user).
26445
26531
  *
26532
+ * On top of the standard fields, Firebender reads `version`, `autoTrigger`,
26533
+ * `disable-model-invocation` (the inverse of `autoTrigger`, which wins when
26534
+ * both are set), `projectTypes` and `icon`. Those come from the `firebender`
26535
+ * section of the rulesync skill and are written verbatim;
26536
+ * `disable-model-invocation` falls back to the root-level rulesync value.
26537
+ *
26446
26538
  * @see https://docs.firebender.com/api-reference/skills
26447
26539
  */
26448
- var FirebenderSkill = class extends AgentsSkillsSkill {
26540
+ var FirebenderSkill = class FirebenderSkill extends AgentsSkillsSkill {
26449
26541
  static getSettablePaths(_options = {}) {
26450
26542
  return { relativeDirPath: FIREBENDER_SKILLS_DIR_PATH };
26451
26543
  }
26544
+ toRulesyncSkill() {
26545
+ const base = super.toRulesyncSkill();
26546
+ const firebenderSection = Object.fromEntries(Object.entries(this.getFrontmatter()).filter(([key]) => !AGENT_SKILLS_STANDARD_KEYS$1.has(key)));
26547
+ if (Object.keys(firebenderSection).length === 0) return base;
26548
+ const rulesyncFrontmatter = {
26549
+ ...base.getFrontmatter(),
26550
+ firebender: firebenderSection
26551
+ };
26552
+ return this.toRulesyncSkillWith(rulesyncFrontmatter);
26553
+ }
26554
+ static fromRulesyncSkill({ outputRoot = process.cwd(), rulesyncSkill, validate = true, global = false, logger }) {
26555
+ const settablePaths = FirebenderSkill.getSettablePaths({ global });
26556
+ const rulesyncFrontmatter = rulesyncSkill.getFrontmatter();
26557
+ const dirName = rulesyncSkill.getDirName();
26558
+ const firebenderSection = {};
26559
+ const ignoredKeys = [];
26560
+ for (const [key, value] of Object.entries(rulesyncFrontmatter.firebender ?? {})) if (AGENT_SKILLS_STANDARD_KEYS$1.has(key)) ignoredKeys.push(key);
26561
+ else firebenderSection[key] = value;
26562
+ if (ignoredKeys.length > 0) warnWithFallback(logger, `${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.`);
26563
+ const disableModelInvocation = resolveDisableModelInvocation({
26564
+ rootFrontmatter: rulesyncFrontmatter,
26565
+ section: rulesyncFrontmatter.firebender
26566
+ });
26567
+ const frontmatter = {
26568
+ name: rulesyncFrontmatter.name,
26569
+ description: rulesyncFrontmatter.description,
26570
+ ...toSpecConformantAgentSkillFields(resolveAgentsSkillsSection(rulesyncFrontmatter)),
26571
+ ...firebenderSection,
26572
+ ...disableModelInvocation !== void 0 && { "disable-model-invocation": disableModelInvocation }
26573
+ };
26574
+ AgentsSkillsSkill.reportSpecViolations({
26575
+ outputRoot,
26576
+ relativeDirPath: settablePaths.relativeDirPath,
26577
+ dirName,
26578
+ frontmatter,
26579
+ sourceAllowedTools: rulesyncFrontmatter.agentsskills?.["allowed-tools"],
26580
+ logger
26581
+ });
26582
+ return new FirebenderSkill({
26583
+ outputRoot,
26584
+ relativeDirPath: settablePaths.relativeDirPath,
26585
+ dirName,
26586
+ frontmatter,
26587
+ body: rulesyncSkill.getBody(),
26588
+ otherFiles: rulesyncSkill.getOtherFiles(),
26589
+ validate,
26590
+ global
26591
+ });
26592
+ }
26452
26593
  static toolTarget = "firebender";
26453
26594
  };
26454
26595
  // src/features/skills/gitlabduo-skill.ts
@@ -26675,39 +26816,22 @@ var GrokcliSkill = class GrokcliSkill extends ToolSkill {
26675
26816
  return new GrokcliSkill(this.forDeletionParams(params));
26676
26817
  }
26677
26818
  };
26678
- // src/features/skills/junie-skill.ts
26679
- const JunieSkillFrontmatterSchema = z.looseObject({
26680
- name: z.string(),
26681
- description: z.string()
26682
- });
26819
+ // src/utils/markdown-paragraph.ts
26683
26820
  /** An ATX markdown heading line (`#` … `######`). */
26684
26821
  const HEADING_LINE = /^#{1,6}(\s|$)/;
26685
26822
  /**
26686
- * Junie's own fallback for a `SKILL.md` with no `description`: "If
26687
- * `description` is not provided in the frontmatter, Junie CLI extracts the
26688
- * first paragraph of the body content as the description." Headings do not
26689
- * count as that paragraph — "If the body is also empty or contains only
26690
- * headings, the skill will fail to load."
26823
+ * The first non-heading paragraph of a Markdown body, collapsed onto one line.
26691
26824
  *
26692
- * This is import-only. The canonical `RulesyncSkillFrontmatter` requires a
26693
- * description, so without the fallback a skill Junie itself loads fine aborts
26694
- * the whole import; generation keeps emitting an explicit description, which
26695
- * the same docs recommend.
26696
- *
26697
- * Heading lines are therefore skipped rather than taken: a body opening with
26698
- * `# Skill Name` would otherwise import that title as the description and —
26699
- * because the next generate writes it out explicitly — replace Junie's own
26700
- * correct fallback with the wrong value everywhere, canonical config included.
26701
- *
26702
- * A paragraph runs to the first blank line or heading, and is collapsed onto
26703
- * one line because it becomes a YAML frontmatter value. A fenced code block is
26704
- * not treated specially: it is ordinary content, so a body whose first
26705
- * paragraph is a fence yields the fence text. Returns an empty string when the
26706
- * body holds no such paragraph, which the caller turns into a skipped skill.
26707
- *
26708
- * @see https://junie.jetbrains.com/docs/agent-skills.html
26825
+ * JetBrains Junie falls back to this paragraph as the description of a skill
26826
+ * or subagent whose frontmatter omits one. Heading lines are skipped rather
26827
+ * than taken, so a body opening with `# Title` does not yield the title. A
26828
+ * paragraph runs to the first blank line or heading, and is collapsed onto one
26829
+ * line because callers store it as a YAML frontmatter value. A fenced code
26830
+ * block is not treated specially: it is ordinary content, so a body whose
26831
+ * first paragraph is a fence yields the fence text. Returns an empty string
26832
+ * when the body holds no such paragraph.
26709
26833
  */
26710
- function deriveDescriptionFromBody(body) {
26834
+ function firstNonHeadingParagraph(body) {
26711
26835
  const paragraph = [];
26712
26836
  for (const rawLine of body.split(/\r?\n/)) {
26713
26837
  const line = rawLine.trim();
@@ -26721,6 +26845,11 @@ function deriveDescriptionFromBody(body) {
26721
26845
  }
26722
26846
  return paragraph.join(" ").trim();
26723
26847
  }
26848
+ // src/features/skills/junie-skill.ts
26849
+ const JunieSkillFrontmatterSchema = z.looseObject({
26850
+ name: z.string(),
26851
+ description: z.string()
26852
+ });
26724
26853
  /**
26725
26854
  * Represents a JetBrains Junie skill directory.
26726
26855
  * Skills are stored under the .junie/skills directory with SKILL.md files.
@@ -26791,7 +26920,7 @@ var JunieSkill = class JunieSkill extends ToolSkill {
26791
26920
  });
26792
26921
  let frontmatter = loaded.frontmatter;
26793
26922
  if (isRecord(frontmatter) && frontmatter.description === void 0) {
26794
- const derived = deriveDescriptionFromBody(loaded.body);
26923
+ const derived = firstNonHeadingParagraph(loaded.body);
26795
26924
  if (derived === "") throw new Error(`Cannot import ${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.`);
26796
26925
  frontmatter = {
26797
26926
  ...frontmatter,
@@ -27825,6 +27954,125 @@ var PiSkill = class extends ToolSkill {
27825
27954
  var OmpSkill = class extends PiSkill {
27826
27955
  static layout = OMP_LAYOUT;
27827
27956
  };
27957
+ // src/constants/openclaw-paths.ts
27958
+ const OPENCLAW_WORKSPACE_DIR_PATH = join(".openclaw", "workspace");
27959
+ const OPENCLAW_RULE_FILE_NAME = "AGENTS.md";
27960
+ const OPENCLAW_CONFIG_DIR_PATH = ".openclaw";
27961
+ const OPENCLAW_CONFIG_FILE_NAME = "openclaw.json";
27962
+ const OPENCLAW_MCP_SERVERS_KEY = "servers";
27963
+ const OPENCLAW_PROJECT_SKILLS_DIR_PATH = join(".agents", "skills");
27964
+ const OPENCLAW_GLOBAL_SKILLS_DIR_PATH = join(OPENCLAW_CONFIG_DIR_PATH, "skills");
27965
+ // src/features/skills/openclaw-skill.ts
27966
+ const OpenclawSkillFrontmatterSchema = z.looseObject({
27967
+ name: z.string(),
27968
+ description: z.string(),
27969
+ homepage: z.optional(z.string()),
27970
+ "user-invocable": z.optional(z.boolean()),
27971
+ "disable-model-invocation": z.optional(z.boolean()),
27972
+ "command-dispatch": z.optional(z.string()),
27973
+ "command-tool": z.optional(z.string()),
27974
+ "command-arg-mode": z.optional(z.string()),
27975
+ metadata: z.optional(z.looseObject({}))
27976
+ });
27977
+ /**
27978
+ * Represents an OpenClaw skill directory.
27979
+ *
27980
+ * Project mode writes the execution folder's `.agents/skills/<name>/SKILL.md`,
27981
+ * which OpenClaw loads when a session runs from that folder (the same mechanism
27982
+ * that loads the folder's `AGENTS.md`). Global mode writes the managed/local
27983
+ * `~/.openclaw/skills/<name>/SKILL.md` root, visible to every agent sharing the
27984
+ * default state directory. The execution folder's `skills/` and the personal
27985
+ * `~/.agents/skills` roots are left alone (see `openclaw-paths.ts`).
27986
+ *
27987
+ * Every key beyond `name`/`description` is carried in the `openclaw` section of
27988
+ * the rulesync skill; the two invocation flags and `metadata` fall back to the
27989
+ * shared root-level defaults when the section omits them.
27990
+ *
27991
+ * @see https://docs.openclaw.ai/tools/skills
27992
+ */
27993
+ var OpenclawSkill = class OpenclawSkill extends ToolSkill {
27994
+ constructor({ outputRoot = process.cwd(), relativeDirPath = OPENCLAW_PROJECT_SKILLS_DIR_PATH, dirName, frontmatter, body, otherFiles = [], validate = true, global = false }) {
27995
+ super({
27996
+ outputRoot,
27997
+ relativeDirPath,
27998
+ dirName,
27999
+ mainFile: {
28000
+ name: SKILL_FILE_NAME,
28001
+ body,
28002
+ frontmatter: { ...frontmatter }
28003
+ },
28004
+ otherFiles,
28005
+ global
28006
+ });
28007
+ if (validate) {
28008
+ const result = this.validate();
28009
+ if (!result.success) throw result.error;
28010
+ }
28011
+ }
28012
+ static getSettablePaths({ global = false } = {}) {
28013
+ return { relativeDirPath: global ? OPENCLAW_GLOBAL_SKILLS_DIR_PATH : OPENCLAW_PROJECT_SKILLS_DIR_PATH };
28014
+ }
28015
+ getFrontmatter() {
28016
+ return OpenclawSkillFrontmatterSchema.parse(this.requireMainFileFrontmatter());
28017
+ }
28018
+ validate() {
28019
+ return this.validateMainFileFrontmatter(OpenclawSkillFrontmatterSchema);
28020
+ }
28021
+ toRulesyncSkill() {
28022
+ const { name, description, ...section } = this.getFrontmatter();
28023
+ const rulesyncFrontmatter = {
28024
+ name,
28025
+ description,
28026
+ targets: ["*"],
28027
+ ...Object.keys(section).length > 0 && { openclaw: section }
28028
+ };
28029
+ return this.toRulesyncSkillWith(rulesyncFrontmatter);
28030
+ }
28031
+ static fromRulesyncSkill({ outputRoot = process.cwd(), rulesyncSkill, validate = true, global = false }) {
28032
+ const rulesyncFrontmatter = rulesyncSkill.getFrontmatter();
28033
+ const { name: _sectionName, description: _sectionDescription, ...section } = rulesyncFrontmatter.openclaw ?? {};
28034
+ const disableModelInvocation = resolveDisableModelInvocation({
28035
+ rootFrontmatter: rulesyncFrontmatter,
28036
+ section
28037
+ });
28038
+ const userInvocable = resolveUserInvocable({
28039
+ rootFrontmatter: rulesyncFrontmatter,
28040
+ section
28041
+ });
28042
+ const metadata = resolveMetadata({
28043
+ rootFrontmatter: rulesyncFrontmatter,
28044
+ section
28045
+ });
28046
+ const frontmatter = {
28047
+ ...section,
28048
+ name: rulesyncFrontmatter.name,
28049
+ description: rulesyncFrontmatter.description,
28050
+ ...metadata !== void 0 && { metadata },
28051
+ ...disableModelInvocation !== void 0 && { "disable-model-invocation": disableModelInvocation },
28052
+ ...userInvocable !== void 0 && { "user-invocable": userInvocable }
28053
+ };
28054
+ return new OpenclawSkill({
28055
+ outputRoot,
28056
+ relativeDirPath: OpenclawSkill.getSettablePaths({ global }).relativeDirPath,
28057
+ dirName: rulesyncSkill.getDirName(),
28058
+ frontmatter,
28059
+ body: rulesyncSkill.getBody(),
28060
+ otherFiles: rulesyncSkill.getOtherFiles(),
28061
+ validate,
28062
+ global
28063
+ });
28064
+ }
28065
+ static toolTarget = "openclaw";
28066
+ static async fromDir(params) {
28067
+ return new OpenclawSkill(await this.loadStandardSkillParams({
28068
+ params,
28069
+ schema: OpenclawSkillFrontmatterSchema
28070
+ }));
28071
+ }
28072
+ static forDeletion(params) {
28073
+ return new OpenclawSkill(this.forDeletionParams(params));
28074
+ }
28075
+ };
27828
28076
  // src/features/skills/opencodev1-skill.ts
27829
28077
  /**
27830
28078
  * Skill generator for **OpenCode V1** (OpenCode 1.x). Skills live in the same
@@ -29888,6 +30136,14 @@ const toolSkillFactories = /* @__PURE__ */ new Map([
29888
30136
  supportsSimulated: false,
29889
30137
  supportsGlobal: true
29890
30138
  }
30139
+ }],
30140
+ ["openclaw", {
30141
+ class: OpenclawSkill,
30142
+ meta: {
30143
+ supportsProject: true,
30144
+ supportsSimulated: false,
30145
+ supportsGlobal: true
30146
+ }
29891
30147
  }]
29892
30148
  ]);
29893
30149
  const defaultGetFactory$5 = (target) => {
@@ -32381,7 +32637,7 @@ function warnAboutReservedAgentName({ name, relativeFilePath, logger }) {
32381
32637
  * `.commandcode/agents/` (project) or `~/.commandcode/agents/` (user); the
32382
32638
  * body is the agent's system prompt.
32383
32639
  *
32384
- * @see https://commandcode.ai/docs/custom-agents
32640
+ * @see https://commandcode.ai/docs/agents
32385
32641
  */
32386
32642
  var CommandcodeSubagent = class extends FrontmatterMarkdownToolSubagent {
32387
32643
  static getSettablePaths(_options = {}) {
@@ -34135,7 +34391,7 @@ var HermesagentSubagent = class HermesagentSubagent extends ToolSubagent {
34135
34391
  */
34136
34392
  const JunieSubagentFrontmatterSchema = z.looseObject({
34137
34393
  name: z.optional(z.string()),
34138
- description: z.string(),
34394
+ description: z.optional(z.string()),
34139
34395
  tools: z.optional(z.union([z.string(), z.array(z.string())])),
34140
34396
  disallowedTools: z.optional(z.union([z.string(), z.array(z.string())])),
34141
34397
  mcpServers: z.optional(z.union([z.string(), z.array(z.string())])),
@@ -34146,6 +34402,34 @@ const JunieSubagentFrontmatterSchema = z.looseObject({
34146
34402
  skills: z.optional(z.union([z.string(), z.array(z.string())])),
34147
34403
  allowPromptArgument: z.optional(z.boolean())
34148
34404
  });
34405
+ /** Junie truncates a body-derived subagent description to this many characters. */
34406
+ const JUNIE_DERIVED_DESCRIPTION_MAX_LENGTH = 1024;
34407
+ /**
34408
+ * Junie's fallback when a subagent's frontmatter has no `description`: the
34409
+ * first non-heading paragraph of the body, truncated to 1,024 characters.
34410
+ * Returns `undefined` when the body has no such paragraph.
34411
+ *
34412
+ * @see https://junie.jetbrains.com/docs/junie-cli-subagents.html
34413
+ */
34414
+ function deriveDescriptionFromBody(body) {
34415
+ const paragraph = firstNonHeadingParagraph(body);
34416
+ if (paragraph === "") return void 0;
34417
+ return truncateText({
34418
+ text: paragraph,
34419
+ maxLength: JUNIE_DERIVED_DESCRIPTION_MAX_LENGTH,
34420
+ suffix: ""
34421
+ });
34422
+ }
34423
+ function isMissingDescription(value) {
34424
+ return value === void 0 || value === null || typeof value === "string" && value.trim() === "";
34425
+ }
34426
+ /**
34427
+ * Junie's fallback subagent name: the file name without its `.agent.md` or
34428
+ * `.md` extension.
34429
+ */
34430
+ function nameFromFileName(relativeFilePath) {
34431
+ return relativeFilePath.replace(/(\.agent)?\.md$/, "");
34432
+ }
34149
34433
  var JunieSubagent = class JunieSubagent extends ToolSubagent {
34150
34434
  frontmatter;
34151
34435
  body;
@@ -34177,8 +34461,8 @@ var JunieSubagent = class JunieSubagent extends ToolSubagent {
34177
34461
  outputRoot: ".",
34178
34462
  frontmatter: {
34179
34463
  targets: ["*"],
34180
- name: name ?? this.getRelativeFilePath().replace(/\.md$/, ""),
34181
- description,
34464
+ name: name ?? nameFromFileName(this.getRelativeFilePath()),
34465
+ ...description !== void 0 && { description },
34182
34466
  ...Object.keys(junieSection).length > 0 && { junie: junieSection }
34183
34467
  },
34184
34468
  body: this.body,
@@ -34237,7 +34521,16 @@ var JunieSubagent = class JunieSubagent extends ToolSubagent {
34237
34521
  const dirPath = relativeDirPath ?? this.getSettablePaths({ global }).relativeDirPath;
34238
34522
  const filePath = join(outputRoot, dirPath, relativeFilePath);
34239
34523
  const fileContent = await readFileContent(filePath);
34240
- const { frontmatter, body: content } = parseFrontmatter(fileContent, filePath);
34524
+ const { frontmatter: parsedFrontmatter, body: content } = parseFrontmatter(fileContent, filePath);
34525
+ let frontmatter = parsedFrontmatter;
34526
+ if (isRecord(frontmatter) && isMissingDescription(frontmatter.description)) {
34527
+ const { description: _missing, ...rest } = frontmatter;
34528
+ const derived = deriveDescriptionFromBody(content);
34529
+ frontmatter = derived === void 0 ? rest : {
34530
+ ...rest,
34531
+ description: derived
34532
+ };
34533
+ }
34241
34534
  const result = JunieSubagentFrontmatterSchema.safeParse(frontmatter);
34242
34535
  if (!result.success) throw new Error(`Invalid frontmatter in ${filePath}: ${formatError(result.error)}`);
34243
34536
  return new JunieSubagent({
@@ -34935,11 +35228,19 @@ const LettacodeSubagentFrontmatterSchema = z.looseObject({
34935
35228
  */
34936
35229
  const LETTACODE_AGENT_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
34937
35230
  /**
34938
- * Names Letta Code keeps for its external-agent launchers: a custom subagent
34939
- * by one of these names is skipped when agents are loaded
34940
- * (`RESERVED_EXTERNAL_SUBAGENT_NAMES` in `src/agent/subagents/index.ts`).
35231
+ * Names a custom subagent cannot take: Letta Code skips it when agents are
35232
+ * loaded. These are the external-agent launcher names
35233
+ * (`RESERVED_EXTERNAL_SUBAGENT_NAMES` in `src/agent/subagents/index.ts`)
35234
+ * plus `memory`, which the same loader also skips (as of letta-code v0.34.66).
34941
35235
  */
34942
- const LETTACODE_RESERVED_AGENT_NAMES = /* @__PURE__ */ new Set(["claude-code", "codex"]);
35236
+ const LETTACODE_RESERVED_AGENT_NAMES = /* @__PURE__ */ new Set([
35237
+ "letta",
35238
+ "claude-code",
35239
+ "codex",
35240
+ "opencode",
35241
+ "cursor",
35242
+ "memory"
35243
+ ]);
34943
35244
  /**
34944
35245
  * The subagent is still generated as authored — the name is the user's to
34945
35246
  * change, and a rename here would make it diverge from the other targets —
@@ -41462,18 +41763,20 @@ var AugmentcodePluginRule = class extends AugmentcodeRule {
41462
41763
  return { nonRoot: { relativeDirPath: AUGMENTCODE_PLUGIN_RULES_DIR } };
41463
41764
  }
41464
41765
  /**
41465
- * Auggie 1.x (still a prerelease on npm at the time of writing; the stable
41466
- * line is 0.36.0) no longer loads `rules/` from plugins: "Rules shipped in
41467
- * plugins (`rules/` in a plugin)" is listed among the removed features, while
41468
- * commands, agents, skills, hooks and MCP servers still load. The rule files
41469
- * are still written, because the stable 0.x CLI reads them, but under 1.x the
41470
- * bundle silently loses them, so say so.
41766
+ * Auggie 1.x (the stable line on npm `latest` since 1.2.0; 0.x is kept only
41767
+ * on the `v0-release` tag with auto-update turned off) no longer loads
41768
+ * `rules/` from plugins: "Rules shipped in plugins (`rules/` in a plugin)" is
41769
+ * listed among the removed features, while commands, agents, skills, hooks
41770
+ * and MCP servers still load. The rule files are still written for users
41771
+ * pinned to 0.x, which reads them, but under 1.x the bundle silently loses
41772
+ * them, so say so.
41471
41773
  * @see https://docs.augmentcode.com/cli/whats-new
41774
+ * @see https://www.augmentcode.com/changelog
41472
41775
  * @see https://docs.augmentcode.com/cli/v0/plugins
41473
41776
  */
41474
41777
  static async getGenerationWarnings({ toolRules }) {
41475
41778
  if (toolRules.length === 0) return [];
41476
- return [`augmentcode-plugin: plugin rules (rules/*.md) are loaded by Auggie 0.x only; Auggie 1.x no longer reads rules/ from plugins, so these ${toolRules.length} rule file(s) have no effect there. Ship instructions that must reach Auggie 1.x users as a skill, or have them generate the augmentcode target in their project.`];
41779
+ return [`augmentcode-plugin: plugin rules (rules/*.md) are loaded by Auggie 0.x only; Auggie 1.x no longer reads rules/ from plugins, so these ${toolRules.length} rule file(s) reach only users pinned to Auggie 0.x (1.x is the stable CLI since 1.2.0). Ship instructions that must reach Auggie 1.x users as a skill, or have them generate the augmentcode target in their project.`];
41477
41780
  }
41478
41781
  };
41479
41782
  // src/features/rules/bob-rule.ts
@@ -46059,12 +46362,6 @@ var OmpRule = class OmpRule extends ToolRule {
46059
46362
  }
46060
46363
  static toolTarget = "omp";
46061
46364
  };
46062
- // src/constants/openclaw-paths.ts
46063
- const OPENCLAW_WORKSPACE_DIR_PATH = join(".openclaw", "workspace");
46064
- const OPENCLAW_RULE_FILE_NAME = "AGENTS.md";
46065
- const OPENCLAW_CONFIG_DIR_PATH = ".openclaw";
46066
- const OPENCLAW_CONFIG_FILE_NAME = "openclaw.json";
46067
- const OPENCLAW_MCP_SERVERS_KEY = "servers";
46068
46365
  // src/features/rules/openclaw-rule.ts
46069
46366
  /**
46070
46367
  * Rule generator for OpenClaw, the always-on assistant gateway.
@@ -54594,12 +54891,23 @@ function toolMatcherEntryToCanonical({ rawEntry, eventName, converterConfig, war
54594
54891
  * tool-native keys through verbatim — so documented native triggers (e.g.
54595
54892
  * kiro-ide's `PostFileSave`) survive an import → generate round-trip instead
54596
54893
  * of failing canonical validation.
54894
+ *
54895
+ * An event key named `__proto__`, `constructor` or `prototype` is dropped with
54896
+ * a warning: no tool documents such an event, and carrying it into
54897
+ * `.rulesync/hooks.jsonc` would make the next `generate` fail the
54898
+ * prototype-pollution key validation.
54597
54899
  */
54598
- function buildImportedHooksConfig({ hooks, overrideKey, version = 1, extraOverride }) {
54900
+ function buildImportedHooksConfig({ hooks, overrideKey, version = 1, extraOverride, logger }) {
54599
54901
  const canonical = {};
54600
54902
  const native = {};
54601
- for (const [event, defs] of Object.entries(hooks)) if (isHookEvent(event)) canonical[event] = defs;
54602
- else native[event] = defs;
54903
+ for (const [event, defs] of Object.entries(hooks)) {
54904
+ if (isPrototypePollutionKey(event)) {
54905
+ logger?.warn(`Skipping imported ${overrideKey} hooks event ${quoteValueForWarning(event)}: reserved key names cannot be used as hook events.`);
54906
+ continue;
54907
+ }
54908
+ if (isHookEvent(event)) canonical[event] = defs;
54909
+ else native[event] = defs;
54910
+ }
54603
54911
  const override = { ...extraOverride };
54604
54912
  if (Object.keys(native).length > 0) override.hooks = native;
54605
54913
  const config = {
@@ -54849,6 +55157,7 @@ var AntigravityHooks = class extends ToolHooks {
54849
55157
  });
54850
55158
  const overrideKey = this.constructor.getOverrideKey();
54851
55159
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
55160
+ logger,
54852
55161
  hooks,
54853
55162
  overrideKey
54854
55163
  }), null, 2) });
@@ -55233,6 +55542,7 @@ var AugmentcodeHooks = class AugmentcodeHooks extends ToolHooks {
55233
55542
  converterConfig: AUGMENTCODE_CONVERTER_CONFIG
55234
55543
  });
55235
55544
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
55545
+ logger,
55236
55546
  hooks,
55237
55547
  overrideKey: "augmentcode"
55238
55548
  }), null, 2) });
@@ -55309,6 +55619,7 @@ var AugmentcodePluginHooks = class AugmentcodePluginHooks extends ToolHooks {
55309
55619
  converterConfig: AUGMENTCODE_PLUGIN_CONVERTER_CONFIG
55310
55620
  });
55311
55621
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
55622
+ logger,
55312
55623
  hooks,
55313
55624
  overrideKey: "augmentcode"
55314
55625
  }), null, 2) });
@@ -55870,6 +56181,7 @@ var SettingsJsonHooks = class extends ToolHooks {
55870
56181
  converterConfig: ctor.getConverterConfig()
55871
56182
  });
55872
56183
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
56184
+ logger,
55873
56185
  hooks,
55874
56186
  overrideKey: spec.overrideKey
55875
56187
  }), null, 2) });
@@ -56663,13 +56975,14 @@ var CodewhaleHooks = class CodewhaleHooks extends ToolHooks {
56663
56975
  global
56664
56976
  });
56665
56977
  }
56666
- toRulesyncHooks() {
56978
+ toRulesyncHooks({ logger } = {}) {
56667
56979
  const parsed = this.parseFileContentOrThrow({
56668
56980
  displayName: "Codewhale",
56669
56981
  parse: (fileContent) => parseCodewhaleToml(fileContent)
56670
56982
  });
56671
56983
  const rawHooks = this.global ? isPlainObject(parsed.hooks) ? parsed.hooks.hooks : void 0 : parsed.hooks;
56672
56984
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
56985
+ logger,
56673
56986
  hooks: codewhaleHooksToCanonical(rawHooks),
56674
56987
  overrideKey: "codewhale"
56675
56988
  }), null, 2) });
@@ -56907,6 +57220,7 @@ var CodexcliHooks = class CodexcliHooks extends ToolHooks {
56907
57220
  logger
56908
57221
  });
56909
57222
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
57223
+ logger,
56910
57224
  hooks,
56911
57225
  overrideKey: "codexcli"
56912
57226
  }), null, 2) });
@@ -57003,6 +57317,7 @@ var CommandcodeHooks = class CommandcodeHooks extends ToolHooks {
57003
57317
  converterConfig: COMMANDCODE_CONVERTER_CONFIG
57004
57318
  });
57005
57319
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
57320
+ logger,
57006
57321
  hooks,
57007
57322
  overrideKey: "commandcode"
57008
57323
  }), null, 2) });
@@ -57302,6 +57617,7 @@ var CopilotHooks = class CopilotHooks extends ToolHooks {
57302
57617
  parse: (fileContent) => JSON.parse(fileContent)
57303
57618
  }).hooks, options?.logger);
57304
57619
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
57620
+ logger: options?.logger,
57305
57621
  hooks,
57306
57622
  overrideKey: "copilot"
57307
57623
  }), null, 2) });
@@ -57754,6 +58070,7 @@ var CopilotcliHooks = class CopilotcliHooks extends ToolHooks {
57754
58070
  parse: (fileContent) => JSON.parse(fileContent)
57755
58071
  }).hooks, options?.logger);
57756
58072
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
58073
+ logger: options?.logger,
57757
58074
  hooks,
57758
58075
  overrideKey: "copilotcli",
57759
58076
  ...this.disableAllHooks !== void 0 && { extraOverride: { disableAllHooks: this.disableAllHooks } }
@@ -57991,6 +58308,15 @@ function normalizeCrushEventName(event) {
57991
58308
  /** Crush tool events, by normalized spelling, on which a `matcher` is valid. */
57992
58309
  const NORMALIZED_CRUSH_TOOL_EVENTS = new Set(CRUSH_TOOL_EVENTS.map((event) => normalizeCrushEventName(event)));
57993
58310
  /**
58311
+ * Every event Crush fires, by normalized spelling: the twelve with a canonical
58312
+ * counterpart plus `PermissionResult`, which is a tool event. Crush refuses to
58313
+ * load the whole config when a `hooks` key names any other event
58314
+ * ("hook <key>: unknown event").
58315
+ * @see https://github.com/charmbracelet/crush/blob/v0.102.0/internal/hooks/events.go
58316
+ * @see https://github.com/charmbracelet/crush/blob/v0.102.0/internal/config/hooks.go
58317
+ */
58318
+ const NORMALIZED_KNOWN_CRUSH_EVENTS = new Set([...Object.values(CANONICAL_TO_CRUSH_EVENT_NAMES), ...CRUSH_TOOL_EVENTS].map((event) => normalizeCrushEventName(event)));
58319
+ /**
57994
58320
  * Resolve a `crush.hooks` override key to the canonical event it names, or
57995
58321
  * null when it names no canonical event. The key may be spelled the canonical
57996
58322
  * way (`stop`) or in any spelling Crush accepts for the event (`TurnEnd`,
@@ -58019,11 +58345,13 @@ function resolveOverrideCanonicalEvent(key) {
58019
58345
  * spelling it uses: the override replaces the shared entries of that event
58020
58346
  * (as for every other tool's override), and override keys that name the same
58021
58347
  * event are concatenated in order, the way Crush itself merges them. A key
58022
- * that names no canonical event — such as `PermissionResult`, or one an
58023
- * import filed there — is written verbatim so it round-trips; keys of that
58024
- * kind that Crush reads as the same event are concatenated under the first
58025
- * spelling. A `matcher` is only written on a tool event: Crush rejects the
58026
- * whole config when one appears anywhere else.
58348
+ * that names a Crush event with no canonical counterpart (`PermissionResult`)
58349
+ * is written verbatim so it round-trips; keys of that kind that Crush reads as
58350
+ * the same event are concatenated under the first spelling. A key that names
58351
+ * no Crush event at all (such as the Claude Code spelling `Stop`) is skipped
58352
+ * with a warning, since Crush would refuse to load the whole config. A
58353
+ * `matcher` is only written on a tool event: Crush rejects the whole config
58354
+ * when one appears anywhere else.
58027
58355
  */
58028
58356
  function canonicalToCrushHooks({ config, toolOverride, logger }) {
58029
58357
  const shared = /* @__PURE__ */ new Map();
@@ -58046,6 +58374,10 @@ function canonicalToCrushHooks({ config, toolOverride, logger }) {
58046
58374
  }) ?? key;
58047
58375
  else {
58048
58376
  const normalized = normalizeCrushEventName(key);
58377
+ if (!NORMALIZED_KNOWN_CRUSH_EVENTS.has(normalized)) {
58378
+ logger?.warn(`crush.hooks event ${quoteValueForWarning(key)} is not a Crush hook event, so it was skipped — Crush refuses to load a config with an unknown hook event.`);
58379
+ continue;
58380
+ }
58049
58381
  crushEvent = verbatimSpellings.get(normalized) ?? key;
58050
58382
  verbatimSpellings.set(normalized, crushEvent);
58051
58383
  }
@@ -58199,9 +58531,10 @@ var CrushHooks = class CrushHooks extends ToolHooks {
58199
58531
  global
58200
58532
  });
58201
58533
  }
58202
- toRulesyncHooks() {
58534
+ toRulesyncHooks({ logger } = {}) {
58203
58535
  const hooks = crushHooksToCanonical(this.json[CRUSH_HOOKS_KEY]);
58204
58536
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
58537
+ logger,
58205
58538
  hooks,
58206
58539
  overrideKey: "crush"
58207
58540
  }), null, 2) });
@@ -58298,7 +58631,7 @@ var CursorHooks = class CursorHooks extends ToolHooks {
58298
58631
  static supportsPreserveUnowned() {
58299
58632
  return true;
58300
58633
  }
58301
- toRulesyncHooks() {
58634
+ toRulesyncHooks({ logger } = {}) {
58302
58635
  const content = this.getFileContent();
58303
58636
  const parsed = JSON.parse(content);
58304
58637
  const cursorHooks = parsed.hooks ?? {};
@@ -58312,6 +58645,7 @@ var CursorHooks = class CursorHooks extends ToolHooks {
58312
58645
  }
58313
58646
  const version = parsed.version ?? 1;
58314
58647
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
58648
+ logger,
58315
58649
  hooks: canonicalHooks,
58316
58650
  overrideKey: "cursor",
58317
58651
  version
@@ -58329,6 +58663,22 @@ var CursorHooks = class CursorHooks extends ToolHooks {
58329
58663
  };
58330
58664
  // src/features/hooks/deepagents-hooks.ts
58331
58665
  /**
58666
+ * deepagents-code 0.2.11+ spells the canonical `failClosed` as a per-handler
58667
+ * `onError: "continue" | "deny"`. Only `"deny"` changes behavior: a failed,
58668
+ * timed-out or invalid-output `PreToolUse` handler then denies the tool call.
58669
+ * `"continue"` is the default, so `false` is omitted; upstream ignores the
58670
+ * field on every other event, so a `true` there is dropped with a warning.
58671
+ * Older dcode versions ignore the field and keep failing open.
58672
+ * https://github.com/langchain-ai/deepagents/blob/main/libs/code/HOOKS.md
58673
+ */
58674
+ const DEEPAGENTS_KEYWORD_FIELDS = [{
58675
+ canonical: "failClosed",
58676
+ tool: "onError",
58677
+ trueValue: "deny",
58678
+ falseValue: "continue",
58679
+ events: /* @__PURE__ */ new Set(["preToolUse"])
58680
+ }];
58681
+ /**
58332
58682
  * Convert the canonical hooks config to the deepagents Hooks v2 document.
58333
58683
  *
58334
58684
  * ```json
@@ -58338,7 +58688,8 @@ var CursorHooks = class CursorHooks extends ToolHooks {
58338
58688
  * Definitions sharing an event and matcher land in one group, preserving their
58339
58689
  * authored order — upstream runs a group's handlers in sequence.
58340
58690
  */
58341
- function canonicalToDeepagentsHooks(config) {
58691
+ function canonicalToDeepagentsHooks(config, logger) {
58692
+ const warn = warnOnce(logger);
58342
58693
  const supported = new Set(DEEPAGENTS_HOOK_EVENTS);
58343
58694
  const effectiveHooks = {
58344
58695
  ...config.hooks,
@@ -58361,6 +58712,13 @@ function canonicalToDeepagentsHooks(config) {
58361
58712
  };
58362
58713
  if (def.timeout !== void 0 && def.timeout !== null && def.timeout > 0) handler.timeout = def.timeout;
58363
58714
  if (def.statusMessage !== void 0 && def.statusMessage !== null) handler.statusMessage = def.statusMessage;
58715
+ Object.assign(handler, emitKeywordFields({
58716
+ def,
58717
+ hookType: "command",
58718
+ eventName: canonicalEvent,
58719
+ fields: DEEPAGENTS_KEYWORD_FIELDS,
58720
+ warn
58721
+ }));
58364
58722
  const matcher = def.matcher !== void 0 && def.matcher !== null && def.matcher !== "" ? def.matcher : void 0;
58365
58723
  const groups = hooks[deepagentsEvent] ??= [];
58366
58724
  const group = groups.find((candidate) => candidate.matcher === matcher);
@@ -58376,7 +58734,8 @@ function canonicalToDeepagentsHooks(config) {
58376
58734
  /**
58377
58735
  * Convert the Hooks v2 document back to the canonical hooks record.
58378
58736
  */
58379
- function deepagentsToCanonicalHooks(hooks) {
58737
+ function deepagentsToCanonicalHooks(hooks, logger) {
58738
+ const warn = warnOnce(logger);
58380
58739
  const canonical = {};
58381
58740
  for (const [deepagentsEvent, groups] of Object.entries(hooks)) {
58382
58741
  const canonicalEvent = lookupOwn({
@@ -58395,6 +58754,19 @@ function deepagentsToCanonicalHooks(hooks) {
58395
58754
  if (typeof group.matcher === "string" && group.matcher !== "") def.matcher = group.matcher;
58396
58755
  if (typeof handler.timeout === "number") def.timeout = handler.timeout;
58397
58756
  if (typeof handler.statusMessage === "string") def.statusMessage = handler.statusMessage;
58757
+ let keywordSource = handler;
58758
+ if (canonicalEvent === "preToolUse" && handler.onError !== void 0 && handler.onError !== "deny" && handler.onError !== "continue") {
58759
+ 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.`);
58760
+ const { onError: _dropped, ...rest } = handler;
58761
+ keywordSource = rest;
58762
+ }
58763
+ Object.assign(def, importKeywordFields({
58764
+ h: keywordSource,
58765
+ hookType: "command",
58766
+ eventName: canonicalEvent,
58767
+ fields: DEEPAGENTS_KEYWORD_FIELDS,
58768
+ warn
58769
+ }));
58398
58770
  (canonical[canonicalEvent] ??= []).push(def);
58399
58771
  }
58400
58772
  }
@@ -58453,8 +58825,8 @@ var DeepagentsHooks = class DeepagentsHooks extends ToolHooks {
58453
58825
  global
58454
58826
  });
58455
58827
  }
58456
- static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false }) {
58457
- const hooks = canonicalToDeepagentsHooks(rulesyncHooks.getJson());
58828
+ static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false, logger }) {
58829
+ const hooks = canonicalToDeepagentsHooks(rulesyncHooks.getJson(), logger);
58458
58830
  const fileContent = JSON.stringify({ hooks }, null, 2);
58459
58831
  const paths = DeepagentsHooks.getSettablePaths({ global });
58460
58832
  return new DeepagentsHooks({
@@ -58465,19 +58837,20 @@ var DeepagentsHooks = class DeepagentsHooks extends ToolHooks {
58465
58837
  validate
58466
58838
  });
58467
58839
  }
58468
- toRulesyncHooks() {
58840
+ toRulesyncHooks({ logger } = {}) {
58469
58841
  const parsed = this.parseFileContentOrThrow({
58470
58842
  displayName: "deepagents",
58471
58843
  parse: (fileContent) => JSON.parse(fileContent)
58472
58844
  });
58473
58845
  const rawHooks = isRecord(parsed) ? parsed.hooks : void 0;
58474
- const hooks = Array.isArray(rawHooks) ? deepagentsLegacyToCanonicalHooks(rawHooks) : isRecord(rawHooks) ? deepagentsToCanonicalHooks(rawHooks) : {};
58846
+ const hooks = Array.isArray(rawHooks) ? deepagentsLegacyToCanonicalHooks(rawHooks) : isRecord(rawHooks) ? deepagentsToCanonicalHooks(rawHooks, logger) : {};
58475
58847
  return this.toRulesyncHooksDefault({
58476
58848
  outputRoot: getDeepagentsRulesyncOutputRoot({
58477
58849
  nativeOutputRoot: this.outputRoot,
58478
58850
  global: this.global
58479
58851
  }),
58480
58852
  fileContent: JSON.stringify(buildImportedHooksConfig({
58853
+ logger,
58481
58854
  hooks,
58482
58855
  overrideKey: "deepagents"
58483
58856
  }), null, 2)
@@ -58583,6 +58956,7 @@ var DevinHooks = class extends ToolHooks {
58583
58956
  logger
58584
58957
  });
58585
58958
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
58959
+ logger,
58586
58960
  hooks,
58587
58961
  overrideKey: "devin"
58588
58962
  }), null, 2) });
@@ -58808,6 +59182,7 @@ var FactorydroidHooks = class FactorydroidHooks extends ToolHooks {
58808
59182
  logger
58809
59183
  });
58810
59184
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59185
+ logger,
58811
59186
  hooks,
58812
59187
  overrideKey: "factorydroid"
58813
59188
  }), null, 2) });
@@ -58892,9 +59267,10 @@ var FirebenderHooks = class FirebenderHooks extends ToolHooks {
58892
59267
  static supportsPreserveUnowned() {
58893
59268
  return true;
58894
59269
  }
58895
- toRulesyncHooks() {
59270
+ toRulesyncHooks({ logger } = {}) {
58896
59271
  const parsed = JSON.parse(this.getFileContent());
58897
59272
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59273
+ logger,
58898
59274
  hooks: parsed.hooks ?? {},
58899
59275
  overrideKey: "firebender",
58900
59276
  version: parsed.version ?? 1
@@ -58962,6 +59338,7 @@ var GitlabduoHooks = class GitlabduoHooks extends ToolHooks {
58962
59338
  logger
58963
59339
  });
58964
59340
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59341
+ logger,
58965
59342
  hooks,
58966
59343
  overrideKey: "gitlabduo"
58967
59344
  }), null, 2) });
@@ -59031,6 +59408,7 @@ var GooseHooks = class GooseHooks extends ToolHooks {
59031
59408
  logger
59032
59409
  });
59033
59410
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59411
+ logger,
59034
59412
  hooks,
59035
59413
  overrideKey: "goose"
59036
59414
  }), null, 2) });
@@ -59113,6 +59491,7 @@ var GrokcliHooks = class GrokcliHooks extends ToolHooks {
59113
59491
  logger
59114
59492
  });
59115
59493
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59494
+ logger,
59116
59495
  hooks,
59117
59496
  overrideKey: "grokcli"
59118
59497
  }), null, 2) });
@@ -59406,7 +59785,7 @@ var HermesagentHooks = class HermesagentHooks extends ToolHooks {
59406
59785
  }) }
59407
59786
  });
59408
59787
  }
59409
- toRulesyncHooks() {
59788
+ toRulesyncHooks({ logger } = {}) {
59410
59789
  const hooks = hermesHooksToCanonical(parseSharedConfig({
59411
59790
  format: "yaml",
59412
59791
  fileContent: this.getFileContent()
@@ -59417,6 +59796,7 @@ var HermesagentHooks = class HermesagentHooks extends ToolHooks {
59417
59796
  global: this.global
59418
59797
  }),
59419
59798
  fileContent: JSON.stringify(buildImportedHooksConfig({
59799
+ logger,
59420
59800
  hooks,
59421
59801
  overrideKey: "hermesagent"
59422
59802
  }), null, 2)
@@ -59446,13 +59826,20 @@ const JUNIE_CONVERTER_CONFIG = {
59446
59826
  projectDirVar: "",
59447
59827
  supportedHookTypes: /* @__PURE__ */ new Set(["command"]),
59448
59828
  noMatcherEvents: /* @__PURE__ */ new Set(["beforeSubmitPrompt", "stop"]),
59449
- booleanPassthroughFields: [{
59450
- canonical: "failClosed",
59451
- tool: "blockOnError"
59452
- }, {
59453
- canonical: "async",
59454
- tool: "async"
59455
- }]
59829
+ booleanPassthroughFields: [
59830
+ {
59831
+ canonical: "failClosed",
59832
+ tool: "blockOnError"
59833
+ },
59834
+ {
59835
+ canonical: "async",
59836
+ tool: "async"
59837
+ },
59838
+ {
59839
+ canonical: "strictJsonOutput",
59840
+ tool: "strictJsonOutput"
59841
+ }
59842
+ ]
59456
59843
  };
59457
59844
  var JunieHooks = class JunieHooks extends ToolHooks {
59458
59845
  isDeletable() {
@@ -59504,6 +59891,7 @@ var JunieHooks = class JunieHooks extends ToolHooks {
59504
59891
  logger
59505
59892
  });
59506
59893
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
59894
+ logger,
59507
59895
  hooks,
59508
59896
  overrideKey: "junie"
59509
59897
  }), null, 2) });
@@ -59642,33 +60030,255 @@ const SHELL_EVENT_TOOL_GATES = {
59642
60030
  }
59643
60031
  };
59644
60032
  /**
59645
- * Canonical events whose command receives a Claude Code-style JSON payload on
59646
- * stdin and whose result can deny the call, mapped to the `hook_event_name`
59647
- * the payload carries. Only `preToolUse` (`tool.execute.before`) takes part:
59648
- * it is the one named hook where throwing aborts the call — OpenCode rejects
59649
- * the tool call and returns the error message to the model (the `.env`
59650
- * protection example in the plugins doc).
59651
- *
59652
- * The payload mirrors Claude Code's `PreToolUse` input: `hook_event_name`,
59653
- * `session_id` (`input.sessionID`), `tool_use_id` (`input.callID`),
59654
- * `tool_name` (the raw OpenCode tool name — `bash`, `edit`, `<server>_<tool>`
59655
- * for MCP — the same subject a `matcher` is tested against), `tool_input`
59656
- * (`output.args`) and `cwd` (the plugin context's `directory`, falling back to
59657
- * `process.cwd()`). It is serialized lazily, on the first handler whose
59658
- * matcher matches, so a tool call no hook applies to pays nothing for it.
59659
- *
59660
- * Bun Shell has no stdin option on a command and rejects redirections on a
59661
- * subshell, so the payload is piped in by the shell's builtin `echo`
59662
- * (`echo ${payload} | <command>`); Bun escapes the interpolated value, so the
59663
- * payload never reaches the shell as syntax. The pipe feeds the first
59664
- * pipeline of the command — a compound `a && b` or `a; b` gives the payload
59665
- * to `a` only, so multi-step guards belong in a script.
60033
+ * Canonical events whose command receives Claude Code's JSON input for the
60034
+ * event on stdin (every other command gets an empty stdin), with the fields
60035
+ * besides `hook_event_name` and `cwd`. `tool_name` is the raw OpenCode tool
60036
+ * name, the subject a `matcher` is tested against. A payload is serialized
60037
+ * lazily, once per invocation, by the first handler that runs.
59666
60038
  *
59667
60039
  * @see https://opencode.ai/docs/plugins/
59668
60040
  * @see https://bun.sh/docs/runtime/shell
59669
60041
  * @see https://code.claude.com/docs/en/hooks
59670
60042
  */
59671
- const STDIN_PAYLOAD_EVENTS = { preToolUse: "PreToolUse" };
60043
+ const STDIN_PAYLOADS = {
60044
+ preToolUse: {
60045
+ name: "PreToolUse",
60046
+ fields: [
60047
+ "session_id: input.sessionID",
60048
+ "tool_use_id: input.callID",
60049
+ "tool_name: input.tool",
60050
+ "tool_input: output?.args"
60051
+ ]
60052
+ },
60053
+ postToolUse: {
60054
+ name: "PostToolUse",
60055
+ fields: [
60056
+ "session_id: input.sessionID",
60057
+ "tool_use_id: input.callID",
60058
+ "tool_name: input.tool",
60059
+ "tool_input: input.args",
60060
+ "tool_response: output"
60061
+ ]
60062
+ },
60063
+ stop: {
60064
+ name: "Stop",
60065
+ fields: ["session_id: event.properties?.sessionID"]
60066
+ }
60067
+ };
60068
+ /**
60069
+ * V1 hooks that run before the action they belong to — every named hook but
60070
+ * `tool.execute.after`: like the Bun Shell call earlier versions emitted, a
60071
+ * failing command throws there, which aborts the action. Everywhere else a
60072
+ * failure is only logged.
60073
+ */
60074
+ const BLOCKING_HOOKS = new Set(Object.keys(NAMED_HOOK_MATCHER_SUBJECTS).filter((hook) => hook !== "tool.execute.after"));
60075
+ /**
60076
+ * Helpers of every plugin with a handler. Bun Shell cannot give a command a
60077
+ * stdin of its own, and one that inherits OpenCode's (the TTY, or the pipe of
60078
+ * `opencode serve --stdio`) blocks forever once any part of it reads stdin. So
60079
+ * `__rulesyncRunCommand` runs the command in the host's own Bun-compiled binary
60080
+ * as the Bun CLI (`BUN_BE_BUN=1`, without the project's `.env`): `exec` runs it
60081
+ * with the same Bun Shell, parsing the text the template literal of earlier
60082
+ * versions held, with the payload as stdin. The script clears `BUN_BE_BUN` for
60083
+ * the programs the command starts: Bun Shell has no `unset`, so it exports an
60084
+ * empty value, which Bun treats as unset (only a non-empty value other than
60085
+ * `0` makes a Bun-compiled binary act as the Bun CLI). A host without the Bun
60086
+ * CLI fails the probe and falls back to Bun Shell, piping the payload into the
60087
+ * first command only (a probe still running after 10 s is killed; it, a
60088
+ * failing one or one that prints anything but `rulesync` means no Bun CLI for
60089
+ * 5 minutes). Ordinary commands write to the host's stdout and stderr, as Bun
60090
+ * Shell echoed them; a `preToolUse` command's are read, 1 MiB each kept (more
60091
+ * stdout denies; on the Bun Shell fallback the whole output is buffered before
60092
+ * that check). Output
60093
+ * pipes a background process keeps open are read for 1 s after the command
60094
+ * exits; what arrived by then is kept, and the reads are then cancelled, as
60095
+ * they are at a timeout. The OpenCode 1.x-style `event` hooks (`inProcess`)
60096
+ * take the Bun Shell path too: starting the child takes about
60097
+ * 250 ms, and OpenCode 1.x's one-shot `opencode run` exits right after
60098
+ * `session.idle`, before a `stop` command run that way could start.
60099
+ * A command that outlives its timeout (counted from its start) resolves to
60100
+ * `null` and is killed. On POSIX its process tree, read from procfs or else
60101
+ * `ps`, gets SIGTERM and, 2 s later, SIGKILL for each of those processes still
60102
+ * alive (same start time, wherever it was reparented) and what it started
60103
+ * since; the command's own process is signalled through its Bun handle only,
60104
+ * so a PID reused after it exited is never signalled. The command keeps
60105
+ * OpenCode's process group, so it keeps the terminal
60106
+ * and Ctrl-C, but a process that left the tree before the timeout (orphaned or
60107
+ * `setsid`) escapes, and without procfs and `ps` only
60108
+ * the command's own process is killed (logged). The pending SIGKILL keeps the
60109
+ * host alive for those 2 s. On Windows, `taskkill /T /F` ends the tree as
60110
+ * linked by parent PID at that moment, then the child is ended through its
60111
+ * handle; a process whose parent had already exited is not reached. Bun Shell
60112
+ * (the fallback) cannot kill: it stops waiting, and the command keeps running.
60113
+ * On a failure, `__rulesyncRunHook` throws in a blocking hook or logs it
60114
+ * otherwise.
60115
+ *
60116
+ * @see https://bun.sh/docs/bundler/executables
60117
+ */
60118
+ function buildRunHelperLinesFor(cwdExpression) {
60119
+ 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 })`;
60120
+ return [
60121
+ "const __rulesyncRead = (stream, limit = 1048576) => {",
60122
+ " const chunks = [];",
60123
+ " let size = 0;",
60124
+ " const reader = stream.getReader();",
60125
+ " let reading = true;",
60126
+ " const done = (async () => {",
60127
+ " for (let read; reading && !(read = await reader.read()).done; ) {",
60128
+ " if (reading && (size += read.value.length) <= limit) chunks.push(read.value);",
60129
+ " }",
60130
+ " })().catch(() => {});",
60131
+ " const stop = () => {",
60132
+ " if (reading) (reading = false), reader.cancel().catch(() => {});",
60133
+ " };",
60134
+ " return { done, stop, text: () => Buffer.concat(chunks).toString(), overflow: () => size > limit };",
60135
+ "};",
60136
+ "let __rulesyncCanExec;",
60137
+ "let __rulesyncRetryAt = 0;",
60138
+ "// pid -> [ppid, start time], from procfs or else ps; a reused PID gets a new start time.",
60139
+ "const __rulesyncProcesses = () => {",
60140
+ " const processes = new Map();",
60141
+ " try {",
60142
+ " const fs = require(\"node:fs\");",
60143
+ " for (const pid of fs.readdirSync(\"/proc\").filter((name) => /^\\d+$/.test(name))) {",
60144
+ " try {",
60145
+ " const stat = fs.readFileSync(\"/proc/\" + pid + \"/stat\", \"utf8\");",
60146
+ " const fields = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \");",
60147
+ " processes.set(pid, [fields[1], fields[19]]);",
60148
+ " } catch {}",
60149
+ " }",
60150
+ " if (processes.size > 0) return processes;",
60151
+ " } catch {}",
60152
+ " try {",
60153
+ " // The C locale keeps `lstart` in one format; it is compared as text, never parsed.",
60154
+ " const env = { ...process.env, LC_ALL: \"C\", LANG: \"C\" };",
60155
+ " const ps = Bun.spawnSync([\"ps\", \"-A\", \"-o\", \"pid=,ppid=,lstart=\"], { env, timeout: 5000 });",
60156
+ " if (ps.exitCode === 0) {",
60157
+ " for (const line of ps.stdout.toString().trim().split(\"\\n\")) {",
60158
+ " const [pid, ppid, ...started] = line.trim().split(/\\s+/);",
60159
+ " processes.set(pid, [ppid, started.join(\" \")]);",
60160
+ " }",
60161
+ " return processes;",
60162
+ " }",
60163
+ " } catch {}",
60164
+ " console.error(\"[rulesync-hooks] neither /proc nor ps is available: only the hook process is killed\");",
60165
+ "};",
60166
+ "const __rulesyncTree = (roots, processes) => {",
60167
+ " const tree = [...roots];",
60168
+ " for (let size = -1; size !== tree.length; ) {",
60169
+ " size = tree.length;",
60170
+ " for (const [pid, [ppid]] of processes ?? []) if (tree.includes(ppid) && !tree.includes(pid)) tree.push(pid);",
60171
+ " }",
60172
+ " return tree;",
60173
+ "};",
60174
+ "// The child itself is signalled only through its handle, a no-op once Bun has reaped it, so a",
60175
+ "// reused PID is never signalled; its descendants only while it is running (not reaped, its PID",
60176
+ "// cannot be reused), and in the SIGKILL round only with both snapshots: the first snapshot's",
60177
+ "// descendants that are the same processes (same start time), and what they and the child,",
60178
+ "// if it ran across the second snapshot, have started since.",
60179
+ "const __rulesyncKillTree = (proc) => {",
60180
+ " const kill = (pids, signal) => pids.forEach((pid) => { try { process.kill(Number(pid), signal); } catch {} });",
60181
+ " const running = () => proc.exitCode === null && proc.signalCode === null;",
60182
+ " const root = String(proc.pid);",
60183
+ " const before = running() ? __rulesyncProcesses() : undefined;",
60184
+ " const first = before && running() ? __rulesyncTree([root], before).slice(1) : [];",
60185
+ " proc.kill(\"SIGTERM\");",
60186
+ " kill(first, \"SIGTERM\");",
60187
+ " setTimeout(() => {",
60188
+ " const alive = running();",
60189
+ " const now = before && __rulesyncProcesses();",
60190
+ " if (!now) return proc.kill(\"SIGKILL\");",
60191
+ " // Every first-snapshot descendant that is still the same process, wherever it was",
60192
+ " // reparented (to PID 1 or a subreaper), and the child if it survived SIGTERM, with what",
60193
+ " // they have started since. The child is killed first, so it starts nothing more.",
60194
+ " const same = first.filter((pid) => now.get(pid)?.[1] === before.get(pid)?.[1]);",
60195
+ " const own = alive && running() && now.get(root)?.[1] === before.get(root)?.[1];",
60196
+ " proc.kill(\"SIGKILL\");",
60197
+ " kill(__rulesyncTree(own ? [root, ...same] : same, now).filter((pid) => pid !== root), \"SIGKILL\");",
60198
+ " }, 2000);",
60199
+ "};",
60200
+ "// `proc.kill()` is TerminateProcess on the child alone. A libuv program (node) that dies takes",
60201
+ "// the children it spawned along through its job object, but not ones started through another",
60202
+ "// program (cmd.exe) or detached. taskkill /T ends the tree as linked by parent PID at that",
60203
+ "// moment; System32's copy, so a taskkill earlier on PATH is never run.",
60204
+ "const __rulesyncKillWindowsTree = (proc) => {",
60205
+ " if (proc.exitCode === null && proc.signalCode === null) {",
60206
+ " const taskkill = (process.env.SystemRoot ?? \"C:\\\\Windows\") + \"\\\\System32\\\\taskkill.exe\";",
60207
+ " try {",
60208
+ " Bun.spawnSync([taskkill, \"/T\", \"/F\", \"/PID\", String(proc.pid)], { stdout: \"ignore\", stderr: \"ignore\", windowsHide: true, timeout: 5000 });",
60209
+ " } catch {}",
60210
+ " }",
60211
+ " proc.kill();",
60212
+ "};",
60213
+ "const __rulesyncRunCommand = async ({ command, input, seconds, inProcess = false, echo = false }) => {",
60214
+ " // A probe that printed `rulesync` is kept; one past its deadline, failing or printing",
60215
+ " // anything else means no Bun CLI for 5 minutes; one that threw is dropped, so the next",
60216
+ " // command probes again.",
60217
+ " if (!inProcess && (__rulesyncCanExec === undefined || (__rulesyncRetryAt && Date.now() >= __rulesyncRetryAt))) {",
60218
+ " __rulesyncRetryAt = 0;",
60219
+ " const probing = (__rulesyncCanExec = (async () => {",
60220
+ ` const probe = ${spawn("\"echo rulesync\"", "\"ignore\"", "\"pipe\"", "\"ignore\"")};`,
60221
+ " const output = __rulesyncRead(probe.stdout, 1024);",
60222
+ " let timer;",
60223
+ " // Settles on its own, even if the probe ignores the kill or a process holds its stdout.",
60224
+ " const deadline = new Promise((resolve) => (timer = setTimeout(resolve, 10000, null)));",
60225
+ " const exited = Promise.all([probe.exited, output.done]).then(([code]) => code);",
60226
+ " const exitCode = await Promise.race([exited, deadline]).finally(() => clearTimeout(timer));",
60227
+ " if (exitCode === null) probe.kill(\"SIGKILL\"), output.stop();",
60228
+ " const found = exitCode === 0 && output.text().trim() === \"rulesync\";",
60229
+ " if (!found) __rulesyncRetryAt = Date.now() + 300000;",
60230
+ " return found;",
60231
+ " })().catch(() => {",
60232
+ " if (__rulesyncCanExec === probing) __rulesyncCanExec = undefined;",
60233
+ " return false;",
60234
+ " }));",
60235
+ " }",
60236
+ " let timer;",
60237
+ " const timeout = () => new Promise((resolve) => (timer = setTimeout(resolve, seconds * 1000, null)));",
60238
+ " if (inProcess || !(await __rulesyncCanExec)) {",
60239
+ ` const run = Bun.$\`echo \${input} | \${{ raw: command }}\`.cwd(${cwdExpression}).nothrow();`,
60240
+ " const result = await Promise.race([echo ? run : run.quiet(), timeout()]).finally(() => clearTimeout(timer));",
60241
+ " if (!result || echo) return result && { exitCode: result.exitCode };",
60242
+ " const { exitCode, stdout, stderr } = result;",
60243
+ " return { exitCode, stdout: stdout.toString(), stderr: stderr.toString(), overflow: stdout.length > 1048576 };",
60244
+ " }",
60245
+ " // An ordinary command writes to the host's stdout and stderr; a preToolUse one is read.",
60246
+ " const output = echo ? \"inherit\" : \"pipe\";",
60247
+ ` const proc = ${spawn("\"export BUN_BE_BUN=\\n\" + command", "new TextEncoder().encode(input + \"\\n\")", "output")};`,
60248
+ " const [stdout, stderr] = echo ? [] : [__rulesyncRead(proc.stdout), __rulesyncRead(proc.stderr)];",
60249
+ " const exitCode = await Promise.race([proc.exited, timeout()]).finally(() => clearTimeout(timer));",
60250
+ " if (exitCode === null) {",
60251
+ " stdout?.stop(), stderr?.stop();",
60252
+ " if (process.platform === \"win32\") __rulesyncKillWindowsTree(proc);",
60253
+ " else __rulesyncKillTree(proc);",
60254
+ " return null;",
60255
+ " }",
60256
+ " if (echo) return { exitCode };",
60257
+ " await Promise.race([Promise.all([stdout.done, stderr.done]), Bun.sleep(1000)]);",
60258
+ " stdout.stop(), stderr.stop();",
60259
+ " return { exitCode, stdout: stdout.text(), stderr: stderr.text(), overflow: stdout.overflow() };",
60260
+ "};",
60261
+ "const __rulesyncRunHook = async ({ label, command, input, blocking, seconds, inProcess = false }) => {",
60262
+ " let result;",
60263
+ " try {",
60264
+ " result = await __rulesyncRunCommand({ command, input, seconds, inProcess, echo: true });",
60265
+ " } catch (error) {",
60266
+ " if (blocking) throw error;",
60267
+ " console.error(\"[rulesync-hooks] \" + label + \" hook failed:\", error);",
60268
+ " return;",
60269
+ " }",
60270
+ " if (result === null) {",
60271
+ " const message = \"[rulesync-hooks] \" + label + \" hook timed out after \" + seconds + \"s\";",
60272
+ " if (blocking) throw new Error(message);",
60273
+ " return console.error(message);",
60274
+ " }",
60275
+ " if (result.exitCode === 0) return;",
60276
+ " const message = \"[rulesync-hooks] \" + label + \" hook exited with code \" + result.exitCode;",
60277
+ " if (blocking) throw new Error(message);",
60278
+ " console.error(message);",
60279
+ "};"
60280
+ ];
60281
+ }
59672
60282
  /**
59673
60283
  * Name of the helper the generated plugin defines when a `preToolUse` handler
59674
60284
  * is present. It interprets the command's result like Claude Code does for a
@@ -59678,7 +60288,10 @@ const STDIN_PAYLOAD_EVENTS = { preToolUse: "PreToolUse" };
59678
60288
  * - exit code 0 with JSON stdout whose `hookSpecificOutput.permissionDecision`
59679
60289
  * is `"deny"` → deny, with `permissionDecisionReason` as the reason;
59680
60290
  * - exit code 0 otherwise → allow;
59681
- * - any other non-zero exit → deny too, with stderr or the exit code.
60291
+ * - any other non-zero exit → deny too, with stderr or the exit code;
60292
+ * - more than 1 MiB of stdout → deny, without parsing it;
60293
+ * - a command past its timeout → deny, like a non-zero exit, unless the hook
60294
+ * sets `failClosed: false`, which allows the call and logs the timeout.
59682
60295
  *
59683
60296
  * Every reason goes through the `sanitizeBlockReason` helper shared with the
59684
60297
  * Pi extension (`hook-block-reason.ts`): control and format characters are
@@ -59694,7 +60307,12 @@ const PRE_TOOL_USE_RESULT_HELPER = "__rulesyncEnforcePreToolUseResult";
59694
60307
  const PRE_TOOL_USE_RESULT_HELPER_LINES = [
59695
60308
  ...buildBlockReasonSanitizerLines({ typed: false }),
59696
60309
  "",
59697
- `const ${PRE_TOOL_USE_RESULT_HELPER} = (result) => {`,
60310
+ `const ${PRE_TOOL_USE_RESULT_HELPER} = (result, failClosed) => {`,
60311
+ " if (result === null) {",
60312
+ " if (failClosed !== false) throw new Error(\"preToolUse hook timed out.\");",
60313
+ " return console.error(\"[rulesync-hooks] preToolUse hook timed out\");",
60314
+ " }",
60315
+ " if (result.overflow) throw new Error(\"preToolUse hook wrote more than 1 MiB to stdout.\");",
59698
60316
  " const stderr = result.stderr.toString();",
59699
60317
  " if (result.exitCode === 0) {",
59700
60318
  " let parsed;",
@@ -59728,15 +60346,70 @@ function escapeForTemplateLiteral(command) {
59728
60346
  function validateAndSanitizeMatcher(matcher) {
59729
60347
  return sanitizeMatcherRegex(matcher).replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
59730
60348
  }
59731
- /** The per-canonical-event gates and payload flag every handler of it carries. */
60349
+ /**
60350
+ * A hook's `timeout` in seconds, Claude Code's default of 600 when it sets none,
60351
+ * capped at what `setTimeout` can wait (larger values fire at once), and its
60352
+ * `failClosed` as written: unset is not `false`.
60353
+ */
60354
+ function hookTimingOf(def) {
60355
+ const timeout = def.timeout !== void 0 && def.timeout > 0 ? def.timeout : 600;
60356
+ return {
60357
+ timeout: Math.min(timeout, 2147483),
60358
+ failClosed: def.failClosed
60359
+ };
60360
+ }
60361
+ const FAIL_CLOSED_TOOL_LABELS = {
60362
+ kilo: "Kilo Code",
60363
+ mimocode: "MiMo Code",
60364
+ opencode: "OpenCode",
60365
+ opencodev1: "OpenCode V1"
60366
+ };
60367
+ /**
60368
+ * Canonical events other than `preToolUse` whose hook runs before its action in
60369
+ * every OpenCode-style plugin (V1 and V2): a failing or timed-out command always
60370
+ * aborts the action there. A test checks it against `BLOCKING_HOOKS` and the V2
60371
+ * generator's `isBlockingOpencodeV2Target`.
60372
+ */
60373
+ const ALWAYS_BLOCKING_EVENTS = /* @__PURE__ */ new Set([
60374
+ "beforeShellExecution",
60375
+ "beforeSubmitPrompt",
60376
+ "preModelInvocation",
60377
+ "userPromptExpansion",
60378
+ "preCompact"
60379
+ ]);
60380
+ /**
60381
+ * Warn about each `failClosed` the generated plugin ignores where it changes
60382
+ * the outcome: the plugin only reads it on `preToolUse`, to decide what a
60383
+ * timed-out command does. Elsewhere a hook that runs before its action always
60384
+ * fails on a timeout, so a `false` there is ignored (a `true` already holds),
60385
+ * and any other hook only logs it, so a `true` there is ignored (a `false`
60386
+ * already holds, like the other targets treat an omitted `false`).
60387
+ */
60388
+ function warnIgnoredFailClosed({ config, supportedEvents, toolConfigKey, logger }) {
60389
+ const configHooks = {
60390
+ ...config.hooks,
60391
+ ...config[toolConfigKey]?.hooks
60392
+ };
60393
+ const plugin = `the generated ${FAIL_CLOSED_TOOL_LABELS[toolConfigKey]} plugin`;
60394
+ for (const [event, definitions] of Object.entries(configHooks)) {
60395
+ if (event === "preToolUse" || !supportedEvents.includes(event)) continue;
60396
+ const blocking = ALWAYS_BLOCKING_EVENTS.has(event);
60397
+ for (const def of definitions) {
60398
+ if (def.failClosed !== !blocking) continue;
60399
+ 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`);
60400
+ }
60401
+ }
60402
+ }
60403
+ /** The per-canonical-event gates and payload every handler of it carries. */
59732
60404
  function handlerExtrasFor(canonicalEvent) {
59733
60405
  const shellGate = SHELL_EVENT_TOOL_GATES[canonicalEvent];
59734
60406
  const propertyGate = GENERIC_EVENT_PROPERTY_GATES[canonicalEvent];
59735
- const stdinEvent = shellGate ? void 0 : STDIN_PAYLOAD_EVENTS[canonicalEvent];
60407
+ const payload = shellGate ? void 0 : STDIN_PAYLOADS[canonicalEvent];
59736
60408
  return {
60409
+ event: canonicalEvent,
59737
60410
  ...shellGate ? { toolGate: shellGate.tool } : {},
59738
60411
  ...propertyGate ? { propertyGate } : {},
59739
- ...stdinEvent ? { stdinEvent } : {}
60412
+ ...payload ? { payload } : {}
59740
60413
  };
59741
60414
  }
59742
60415
  /**
@@ -59749,7 +60422,8 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
59749
60422
  const extras = handlerExtrasFor(canonicalEvent);
59750
60423
  const toolEvent = shellGate?.toolEvent ?? eventMap[canonicalEvent];
59751
60424
  if (!toolEvent) continue;
59752
- const matcherSupported = !shellGate && Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent) && NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] !== null;
60425
+ const isNamedHook = Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent);
60426
+ const matcherSupported = !shellGate && isNamedHook && NAMED_HOOK_MATCHER_SUBJECTS[toolEvent] !== null;
59753
60427
  const handlers = [];
59754
60428
  for (const def of definitions) {
59755
60429
  if ((def.type ?? "command") !== "command") continue;
@@ -59758,11 +60432,14 @@ function collectOpencodeStyleHandlers({ effectiveHooks, eventMap, namedEventHand
59758
60432
  handlers.push({
59759
60433
  command: def.command,
59760
60434
  matcher: def.matcher ? def.matcher : void 0,
60435
+ blocking: BLOCKING_HOOKS.has(toolEvent),
60436
+ ...hookTimingOf(def),
60437
+ inProcess: !isNamedHook,
59761
60438
  ...extras
59762
60439
  });
59763
60440
  }
59764
60441
  if (handlers.length > 0) {
59765
- const grouped = Object.hasOwn(NAMED_HOOK_MATCHER_SUBJECTS, toolEvent) ? namedEventHandlers : genericEventHandlers;
60442
+ const grouped = isNamedHook ? namedEventHandlers : genericEventHandlers;
59766
60443
  const existing = grouped[toolEvent];
59767
60444
  if (existing) existing.push(...handlers);
59768
60445
  else grouped[toolEvent] = handlers;
@@ -59778,13 +60455,17 @@ function buildGenericEventBodyLines(genericEventHandlers) {
59778
60455
  for (const [eventName, handlers] of Object.entries(genericEventHandlers)) {
59779
60456
  bodyLines.push(` ${isFirst ? "if" : "else if"} (event.type === "${eventName}") {`);
59780
60457
  isFirst = false;
60458
+ for (const line of buildPayloadClosureLines({
60459
+ handlers,
60460
+ cwdExpression: V1_CWD_EXPRESSION
60461
+ })) bodyLines.push(` ${line}`);
59781
60462
  for (const handler of handlers) {
59782
- const escapedCommand = escapeForTemplateLiteral(handler.command);
60463
+ const runStatement = buildRunStatement(handler);
59783
60464
  if (handler.propertyGate) {
59784
60465
  bodyLines.push(` if (${handler.propertyGate}) {`);
59785
- bodyLines.push(` await $\`${escapedCommand}\`;`);
60466
+ bodyLines.push(` ${runStatement}`);
59786
60467
  bodyLines.push(" }");
59787
- } else bodyLines.push(` await $\`${escapedCommand}\`;`);
60468
+ } else bodyLines.push(` ${runStatement}`);
59788
60469
  }
59789
60470
  bodyLines.push(" }");
59790
60471
  }
@@ -59794,39 +60475,61 @@ function buildGenericEventBodyLines(genericEventHandlers) {
59794
60475
  function stdinPayloadVariable(stdinEvent) {
59795
60476
  return `__rulesync${stdinEvent}Input`;
59796
60477
  }
60478
+ /** The `cwd` a V1 payload reports: the session directory, else the process's. */
60479
+ const V1_CWD_EXPRESSION = "directory ?? process.cwd()";
60480
+ /** Lazily serialized closures for the payloads the handlers use (internal tables only). */
60481
+ function buildPayloadClosureLines({ handlers, cwdExpression }) {
60482
+ const payloads = /* @__PURE__ */ new Map();
60483
+ for (const handler of handlers) if (handler.payload) payloads.set(handler.payload.name, handler.payload);
60484
+ const lines = [];
60485
+ for (const payload of payloads.values()) {
60486
+ const variable = stdinPayloadVariable(payload.name);
60487
+ lines.push(`let ${variable}Cache;`, `const ${variable} = () =>`);
60488
+ lines.push(` (${variable}Cache ??= JSON.stringify({`);
60489
+ lines.push(` hook_event_name: "${payload.name}",`);
60490
+ lines.push(...payload.fields.map((field) => ` ${field},`));
60491
+ lines.push(` cwd: ${cwdExpression},`, " }));");
60492
+ }
60493
+ return lines;
60494
+ }
59797
60495
  /**
59798
- * The statement that runs a handler's command. A handler with a stdin payload
59799
- * pipes the payload in and hands the result to the deny-aware helper; every
59800
- * other handler keeps Bun Shell's default mode, where a non-zero exit throws.
60496
+ * The statement that runs a handler's command with its stdin payload, or an
60497
+ * empty stdin. The command keeps the escaping it had in the template literal
60498
+ * earlier versions emitted, so `bun exec` parses the same text.
59801
60499
  */
59802
60500
  function buildRunStatement(handler) {
59803
- const escapedCommand = escapeForTemplateLiteral(handler.command);
59804
- if (handler.stdinEvent) {
59805
- const payload = stdinPayloadVariable(handler.stdinEvent);
59806
- return `${PRE_TOOL_USE_RESULT_HELPER}(await $\`echo \${${payload}()} | ${escapedCommand}\`.nothrow().quiet());`;
59807
- }
59808
- return `await $\`${escapedCommand}\`;`;
60501
+ const command = JSON.stringify(escapeForTemplateLiteral(handler.command));
60502
+ const input = handler.payload ? `${stdinPayloadVariable(handler.payload.name)}()` : "\"\"";
60503
+ if (handler.payload?.name === "PreToolUse") {
60504
+ const failClosed = handler.failClosed === void 0 ? "" : `, ${handler.failClosed}`;
60505
+ return `${PRE_TOOL_USE_RESULT_HELPER}(await __rulesyncRunCommand({ command: ${command}, input: ${input}, seconds: ${handler.timeout} })${failClosed});`;
60506
+ }
60507
+ return `await __rulesyncRunHook({ ${[
60508
+ `label: ${JSON.stringify(handler.event)}`,
60509
+ `command: ${command}`,
60510
+ `input: ${input}`,
60511
+ `blocking: ${handler.blocking}`,
60512
+ `seconds: ${handler.timeout}`,
60513
+ ...handler.inProcess ? ["inProcess: true"] : []
60514
+ ].join(", ")} });`;
60515
+ }
60516
+ /** The helpers a plugin body defines before its handlers, run in `cwdExpression`. */
60517
+ function buildRunHelperLines({ handlers, cwdExpression }) {
60518
+ if (handlers.length === 0) return [];
60519
+ const usesPreToolUse = handlers.some((handler) => handler.payload?.name === "PreToolUse");
60520
+ return [...buildRunHelperLinesFor(cwdExpression), ...usesPreToolUse ? ["", ...PRE_TOOL_USE_RESULT_HELPER_LINES] : []];
59809
60521
  }
59810
60522
  /** Emit the named (`tool.execute.*`) handler blocks. */
59811
60523
  function buildNamedEventBodyLines(namedEventHandlers) {
59812
60524
  const bodyLines = [];
59813
60525
  for (const [eventName, handlers] of Object.entries(namedEventHandlers)) {
59814
60526
  const matcherSubject = NAMED_HOOK_MATCHER_SUBJECTS[eventName] ?? null;
59815
- const stdinEvents = [...new Set(handlers.flatMap((handler) => handler.stdinEvent ? [handler.stdinEvent] : []))];
59816
- bodyLines.push(` "${eventName}": async (${stdinEvents.length > 0 ? "input, output" : "input"}) => {`);
59817
- for (const stdinEvent of stdinEvents) {
59818
- const payload = stdinPayloadVariable(stdinEvent);
59819
- bodyLines.push(` let ${payload}Cache;`);
59820
- bodyLines.push(` const ${payload} = () =>`);
59821
- bodyLines.push(` (${payload}Cache ??= JSON.stringify({`);
59822
- bodyLines.push(` hook_event_name: "${stdinEvent}",`);
59823
- bodyLines.push(" session_id: input.sessionID,");
59824
- bodyLines.push(" tool_use_id: input.callID,");
59825
- bodyLines.push(" tool_name: input.tool,");
59826
- bodyLines.push(" tool_input: output?.args,");
59827
- bodyLines.push(" cwd: directory ?? process.cwd(),");
59828
- bodyLines.push(" }));");
59829
- }
60527
+ const payloadLines = buildPayloadClosureLines({
60528
+ handlers,
60529
+ cwdExpression: V1_CWD_EXPRESSION
60530
+ });
60531
+ bodyLines.push(` "${eventName}": async (${payloadLines.length > 0 ? "input, output" : "input"}) => {`);
60532
+ bodyLines.push(...payloadLines.map((line) => ` ${line}`));
59830
60533
  for (const handler of handlers) {
59831
60534
  const runStatement = buildRunStatement(handler);
59832
60535
  if (handler.toolGate) {
@@ -59849,7 +60552,7 @@ function buildNamedEventBodyLines(namedEventHandlers) {
59849
60552
  }
59850
60553
  /** Wrap the handler body lines in the requested export shape. */
59851
60554
  function wrapInExportShape({ preambleLines, bodyLines, exportStyle }) {
59852
- const pluginContextPattern = preambleLines.length > 0 ? "{ $, directory }" : "{ $ }";
60555
+ const pluginContextPattern = preambleLines.length > 0 ? "{ directory }" : "{ $ }";
59853
60556
  const lines = [];
59854
60557
  if (exportStyle === "default") {
59855
60558
  lines.push("export default {");
@@ -59890,7 +60593,10 @@ function generateOpencodeStylePluginCode(config, supportedEvents, toolConfigKey,
59890
60593
  });
59891
60594
  const bodyLines = [...buildGenericEventBodyLines(genericEventHandlers), ...buildNamedEventBodyLines(namedEventHandlers)];
59892
60595
  return wrapInExportShape({
59893
- preambleLines: Object.values(namedEventHandlers).some((handlers) => handlers.some((handler) => handler.stdinEvent !== void 0)) ? PRE_TOOL_USE_RESULT_HELPER_LINES : [],
60596
+ preambleLines: buildRunHelperLines({
60597
+ handlers: [...Object.values(namedEventHandlers), ...Object.values(genericEventHandlers)].flat(),
60598
+ cwdExpression: V1_CWD_EXPRESSION
60599
+ }),
59894
60600
  bodyLines,
59895
60601
  exportStyle
59896
60602
  }).join("\n");
@@ -59924,8 +60630,15 @@ var KiloHooks = class KiloHooks extends ToolHooks {
59924
60630
  validate
59925
60631
  });
59926
60632
  }
59927
- static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false }) {
59928
- const fileContent = generateOpencodeStylePluginCode(rulesyncHooks.getJson(), KILO_HOOK_EVENTS, "kilo", CANONICAL_TO_KILO_EVENT_NAMES, "default");
60633
+ static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false, logger }) {
60634
+ const config = rulesyncHooks.getJson();
60635
+ warnIgnoredFailClosed({
60636
+ config,
60637
+ supportedEvents: KILO_HOOK_EVENTS,
60638
+ toolConfigKey: "kilo",
60639
+ logger
60640
+ });
60641
+ const fileContent = generateOpencodeStylePluginCode(config, KILO_HOOK_EVENTS, "kilo", CANONICAL_TO_KILO_EVENT_NAMES, "default");
59929
60642
  const paths = KiloHooks.getSettablePaths({ global });
59930
60643
  return new KiloHooks({
59931
60644
  outputRoot,
@@ -60133,7 +60846,7 @@ var KimiCodeHooks = class KimiCodeHooks extends ToolHooks {
60133
60846
  global: true
60134
60847
  });
60135
60848
  }
60136
- toRulesyncHooks() {
60849
+ toRulesyncHooks({ logger } = {}) {
60137
60850
  const config = parseSharedConfig({
60138
60851
  format: "toml",
60139
60852
  fileContent: this.getFileContent()
@@ -60146,6 +60859,7 @@ var KimiCodeHooks = class KimiCodeHooks extends ToolHooks {
60146
60859
  relativeDirPath: RULESYNC_RELATIVE_DIR_PATH,
60147
60860
  relativeFilePath: RULESYNC_HOOKS_FILE_NAME,
60148
60861
  fileContent: JSON.stringify(buildImportedHooksConfig({
60862
+ logger,
60149
60863
  hooks: kimiCodeHooksToCanonical(config.hooks),
60150
60864
  overrideKey: "kimi-code"
60151
60865
  }), null, 2)
@@ -60370,12 +61084,13 @@ var KiroIdeHooks = class extends ToolHooks {
60370
61084
  validate
60371
61085
  });
60372
61086
  }
60373
- toRulesyncHooks() {
61087
+ toRulesyncHooks({ logger } = {}) {
60374
61088
  const hooks = kiroIdeHooksToCanonical(this.parseFileContentOrThrow({
60375
61089
  displayName: "Kiro IDE",
60376
61090
  parse: (fileContent) => KiroIdeHooksFileSchema.parse(JSON.parse(fileContent))
60377
61091
  }).hooks ?? []);
60378
61092
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
61093
+ logger,
60379
61094
  hooks,
60380
61095
  overrideKey: KIRO_HOOKS_OVERRIDE_KEY
60381
61096
  }), null, 2) });
@@ -60560,12 +61275,13 @@ var KiroHooks = class KiroHooks extends ToolHooks {
60560
61275
  validate
60561
61276
  });
60562
61277
  }
60563
- toRulesyncHooks() {
61278
+ toRulesyncHooks({ logger } = {}) {
60564
61279
  const hooks = kiroHooksToCanonical(this.parseFileContentOrThrow({
60565
61280
  displayName: "Kiro",
60566
61281
  parse: (fileContent) => JSON.parse(fileContent)
60567
61282
  }).hooks);
60568
61283
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
61284
+ logger,
60569
61285
  hooks,
60570
61286
  overrideKey: "kiro"
60571
61287
  }), null, 2) });
@@ -60719,6 +61435,7 @@ var LettacodeHooks = class LettacodeHooks extends ToolHooks {
60719
61435
  converterConfig: LETTACODE_CONVERTER_CONFIG
60720
61436
  });
60721
61437
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
61438
+ logger,
60722
61439
  hooks,
60723
61440
  overrideKey: "lettacode"
60724
61441
  }), null, 2) });
@@ -60737,10 +61454,7 @@ var LettacodeHooks = class LettacodeHooks extends ToolHooks {
60737
61454
  * option; the per-type checks inside the loop stay, so an older 2.x that
60738
61455
  * ignores it still runs each command only for its own event).
60739
61456
  *
60740
- * Commands run through a private Bun Shell instance (`new Bun.$.Shell()`, the
60741
- * plugin runs inside the Bun-built OpenCode binary) whose working directory is
60742
- * the plugin location's directory, so the global `Bun.$` defaults other
60743
- * plugins see are left alone.
61457
+ * Commands run in the plugin location's directory (see `buildRunHelperLines`).
60744
61458
  *
60745
61459
  * @see https://opencode.ai/v2/docs/build/plugins/
60746
61460
  */
@@ -60763,13 +61477,33 @@ const OPENCODE_V2_HANDLER_GATES = {
60763
61477
  permissionDenied: "event.data?.reply === \"reject\""
60764
61478
  };
60765
61479
  /**
60766
- * Canonical events whose command receives a Claude Code-style `PreToolUse`
60767
- * JSON payload on stdin and whose result can deny the call. Throwing from an
60768
- * `execute.before` hook fails the tool call with the error message, which the
60769
- * model sees — the same contract the V1 plugin implements, interpreted by the
60770
- * shared `PRE_TOOL_USE_RESULT_HELPER`.
61480
+ * The V2 counterparts of the V1 stdin payloads (`STDIN_PAYLOADS`), plus
61481
+ * Claude Code's `PostToolUseFailure` input for a failed call.
60771
61482
  */
60772
- const OPENCODE_V2_STDIN_PAYLOAD_EVENTS = { preToolUse: "PreToolUse" };
61483
+ const TOOL_CALL_FIELDS = [
61484
+ "session_id: event.sessionID",
61485
+ "tool_use_id: event.id",
61486
+ "tool_name: event.tool",
61487
+ "tool_input: event.input"
61488
+ ];
61489
+ const OPENCODE_V2_STDIN_PAYLOADS = {
61490
+ preToolUse: {
61491
+ name: "PreToolUse",
61492
+ fields: TOOL_CALL_FIELDS
61493
+ },
61494
+ postToolUse: {
61495
+ name: "PostToolUse",
61496
+ fields: [...TOOL_CALL_FIELDS, "tool_response: event.result"]
61497
+ },
61498
+ postToolUseFailure: {
61499
+ name: "PostToolUseFailure",
61500
+ fields: [...TOOL_CALL_FIELDS, "error: event.error?.message ?? event.error"]
61501
+ },
61502
+ stop: {
61503
+ name: "Stop",
61504
+ fields: ["session_id: event.data?.sessionID"]
61505
+ }
61506
+ };
60773
61507
  /**
60774
61508
  * Helper the generated plugin defines when a handler has a matcher. A matcher
60775
61509
  * is tested against the V2 tool name and, for a tool OpenCode 2.x renamed,
@@ -60806,28 +61540,21 @@ function buildHookRegistrationLines(hookPoint, handlers) {
60806
61540
  const lines = [];
60807
61541
  lines.push("__rulesyncRegistrations.push(");
60808
61542
  lines.push(` await ctx.${domain}.hook("${name}", async (event) => {`);
60809
- const stdinEvents = [...new Set(handlers.flatMap((handler) => handler.stdinEvent ? [handler.stdinEvent] : []))];
60810
- for (const stdinEvent of stdinEvents) {
60811
- const payload = stdinPayloadVariable(stdinEvent);
60812
- lines.push(` let ${payload}Cache;`);
60813
- lines.push(` const ${payload} = () =>`);
60814
- lines.push(` (${payload}Cache ??= JSON.stringify({`);
60815
- lines.push(` hook_event_name: "${stdinEvent}",`);
60816
- lines.push(" session_id: event.sessionID,");
60817
- lines.push(" tool_use_id: event.id,");
60818
- lines.push(" tool_name: event.tool,");
60819
- lines.push(" tool_input: event.input,");
60820
- lines.push(" cwd: directory,");
60821
- lines.push(" }));");
60822
- }
61543
+ lines.push(...buildPayloadClosureLines({
61544
+ handlers,
61545
+ cwdExpression: "directory"
61546
+ }).map((line) => ` ${line}`));
60823
61547
  for (const handler of handlers) lines.push(...wrapInConditions(handler, buildRunStatement(handler), " "));
60824
61548
  lines.push(" }),");
60825
61549
  lines.push(");");
60826
61550
  return lines;
60827
61551
  }
60828
61552
  /**
60829
- * Emit the event-stream loop. Each command is isolated in its own try/catch so
60830
- * a failing hook neither skips its siblings nor ends the subscription. The
61553
+ * Emit the event-stream loop. Event handlers are non-blocking, so
61554
+ * `__rulesyncRunHook` logs a failing command instead of throwing, and it
61555
+ * neither skips its siblings nor ends the subscription. Each handler also runs
61556
+ * in its own try/catch, so a throw while evaluating its gate or building its
61557
+ * payload, outside `__rulesyncRunHook`, is logged the same way. The
60831
61558
  * subscription passes `types` so the server delivers only the handled events.
60832
61559
  */
60833
61560
  function buildEventLoopLines(eventHandlers) {
@@ -60843,11 +61570,16 @@ function buildEventLoopLines(eventHandlers) {
60843
61570
  for (const [eventType, handlers] of eventHandlers) {
60844
61571
  lines.push(` ${isFirst ? "if" : "} else if"} (event.type === "${eventType}") {`);
60845
61572
  isFirst = false;
61573
+ lines.push(...buildPayloadClosureLines({
61574
+ handlers,
61575
+ cwdExpression: "directory"
61576
+ }).map((line) => ` ${line}`));
60846
61577
  for (const handler of handlers) {
60847
61578
  lines.push(" try {");
60848
61579
  lines.push(...wrapInConditions(handler, buildRunStatement(handler), " "));
60849
61580
  lines.push(" } catch (error) {");
60850
- lines.push(` console.error("[rulesync-hooks] ${eventType} hook failed:", error);`);
61581
+ const message = JSON.stringify(`[rulesync-hooks] ${handler.event} hook failed:`);
61582
+ lines.push(` console.error(${message}, error);`);
60851
61583
  lines.push(" }");
60852
61584
  }
60853
61585
  }
@@ -60856,10 +61588,17 @@ function buildEventLoopLines(eventHandlers) {
60856
61588
  lines.push("})().catch(() => {});");
60857
61589
  return lines;
60858
61590
  }
61591
+ /**
61592
+ * Every hook point but `execute.after` runs before its action, which a throw
61593
+ * aborts; the event stream only observes.
61594
+ */
61595
+ function isBlockingOpencodeV2Target(target) {
61596
+ return !target.startsWith("event:") && target !== "tool:execute.after";
61597
+ }
60859
61598
  /** Build the handlers of one canonical event's command definitions. */
60860
61599
  function buildHandlersFor({ canonicalEvent, definitions, target }) {
60861
61600
  const gate = OPENCODE_V2_HANDLER_GATES[canonicalEvent];
60862
- const stdinEvent = OPENCODE_V2_STDIN_PAYLOAD_EVENTS[canonicalEvent];
61601
+ const payload = OPENCODE_V2_STDIN_PAYLOADS[canonicalEvent];
60863
61602
  const matcherSupported = !(canonicalEvent === "beforeShellExecution" || canonicalEvent === "afterShellExecution") && OPENCODE_V2_MATCHABLE_HOOKS.has(target);
60864
61603
  const handlers = [];
60865
61604
  for (const def of definitions) {
@@ -60868,9 +61607,12 @@ function buildHandlersFor({ canonicalEvent, definitions, target }) {
60868
61607
  if (def.matcher && !matcherSupported) continue;
60869
61608
  handlers.push({
60870
61609
  command: def.command,
61610
+ event: canonicalEvent,
61611
+ blocking: isBlockingOpencodeV2Target(target),
61612
+ ...hookTimingOf(def),
60871
61613
  ...def.matcher ? { matcher: def.matcher } : {},
60872
61614
  ...gate ? { gate } : {},
60873
- ...stdinEvent ? { stdinEvent } : {}
61615
+ ...payload ? { payload } : {}
60874
61616
  });
60875
61617
  }
60876
61618
  return handlers;
@@ -60878,13 +61620,14 @@ function buildHandlersFor({ canonicalEvent, definitions, target }) {
60878
61620
  /** Emit the statements of the `setup` function body. */
60879
61621
  function buildSetupBodyLines({ hookHandlers, eventHandlers }) {
60880
61622
  if (hookHandlers.size === 0 && eventHandlers.size === 0) return [];
60881
- const usesStdinPayload = [...hookHandlers.values()].some((handlers) => handlers.some((handler) => handler.stdinEvent !== void 0));
60882
61623
  const body = [
60883
61624
  "const directory = ctx.location?.directory ?? process.cwd();",
60884
- "const $ = new Bun.$.Shell();",
60885
- "$.cwd(directory);"
61625
+ "",
61626
+ ...buildRunHelperLines({
61627
+ handlers: [...hookHandlers.values(), ...eventHandlers.values()].flat(),
61628
+ cwdExpression: "directory"
61629
+ })
60886
61630
  ];
60887
- if (usesStdinPayload) body.push("", ...PRE_TOOL_USE_RESULT_HELPER_LINES);
60888
61631
  if ([...hookHandlers.values()].some((handlers) => handlers.some((handler) => handler.matcher !== void 0))) body.push("", ...TOOL_MATCHER_HELPER_LINES);
60889
61632
  const cleanup = [];
60890
61633
  if (hookHandlers.size > 0) {
@@ -60957,8 +61700,14 @@ var OpencodeHooks = class extends ToolHooks {
60957
61700
  validate
60958
61701
  });
60959
61702
  }
60960
- static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false }) {
61703
+ static fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false, logger }) {
60961
61704
  const config = rulesyncHooks.getJson();
61705
+ warnIgnoredFailClosed({
61706
+ config,
61707
+ supportedEvents: this.layout.configVersion === "v2" ? OPENCODE_V2_HOOK_EVENTS : OPENCODE_HOOK_EVENTS,
61708
+ toolConfigKey: this.layout.toolTarget,
61709
+ logger
61710
+ });
60962
61711
  const fileContent = this.layout.configVersion === "v2" ? generateOpencodeV2PluginCode({
60963
61712
  config,
60964
61713
  supportedEvents: OPENCODE_V2_HOOK_EVENTS,
@@ -61711,9 +62460,10 @@ var PoolHooks = class PoolHooks extends ToolHooks {
61711
62460
  global
61712
62461
  });
61713
62462
  }
61714
- toRulesyncHooks() {
62463
+ toRulesyncHooks({ logger } = {}) {
61715
62464
  const hooks = poolHooksToCanonical(this.settings[POOL_HOOKS_KEY]);
61716
62465
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
62466
+ logger,
61717
62467
  hooks,
61718
62468
  overrideKey: "pool"
61719
62469
  }), null, 2) });
@@ -62110,12 +62860,13 @@ var QwencodeHooks = class QwencodeHooks extends ToolHooks {
62110
62860
  static supportsPreserveUnowned() {
62111
62861
  return true;
62112
62862
  }
62113
- toRulesyncHooks() {
62863
+ toRulesyncHooks({ logger } = {}) {
62114
62864
  const settings = this.parseFileContentOrThrow({
62115
62865
  displayName: "Qwen Code",
62116
62866
  parse: (fileContent) => JSON.parse(fileContent)
62117
62867
  });
62118
62868
  const canonical = buildImportedHooksConfig({
62869
+ logger,
62119
62870
  hooks: qwencodeHooksToCanonical(settings.hooks),
62120
62871
  overrideKey: "qwencode",
62121
62872
  ...typeof settings.disableAllHooks === "boolean" && { extraOverride: { disableAllHooks: settings.disableAllHooks } }
@@ -62320,12 +63071,13 @@ var ReasonixHooks = class ReasonixHooks extends ToolHooks {
62320
63071
  validate
62321
63072
  });
62322
63073
  }
62323
- toRulesyncHooks() {
63074
+ toRulesyncHooks({ logger } = {}) {
62324
63075
  const hooks = reasonixHooksToCanonical(this.parseFileContentOrThrow({
62325
63076
  displayName: "Reasonix",
62326
63077
  parse: (fileContent) => JSON.parse(fileContent)
62327
63078
  }).hooks);
62328
63079
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
63080
+ logger,
62329
63081
  hooks,
62330
63082
  overrideKey: "reasonix"
62331
63083
  }), null, 2) });
@@ -62550,13 +63302,14 @@ var TabnineHooks = class TabnineHooks extends ToolHooks {
62550
63302
  validate
62551
63303
  });
62552
63304
  }
62553
- toRulesyncHooks() {
63305
+ toRulesyncHooks({ logger } = {}) {
62554
63306
  const configPath = join(this.getRelativeDirPath(), this.getRelativeFilePath());
62555
63307
  const hooks = tabnineHooksToCanonical(this.parseFileContentOrThrow({
62556
63308
  displayName: "Tabnine CLI",
62557
63309
  parse: (fileContent) => parseTabnineSettings(fileContent, configPath)
62558
63310
  }).hooks);
62559
63311
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
63312
+ logger,
62560
63313
  hooks,
62561
63314
  overrideKey: "tabnine"
62562
63315
  }), null, 2) });
@@ -62621,13 +63374,31 @@ var TraeHooks = class extends SettingsJsonHooks {
62621
63374
  const VIBE_DIR = ".vibe";
62622
63375
  const VIBE_HOOKS_FILE_NAME = "hooks.toml";
62623
63376
  /**
62624
- * Vibe scopes the tool-name `match` glob and the `strict` flag to tool hooks
62625
- * (`pre_tool` / `post_tool`). `post_agent` takes a `match` too since v3.0.3,
62626
- * but on the name of the agent that finished its turn, not a tool name (see
62627
- * {@link VIBE_MAIN_AGENT_MATCH}).
62628
- * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.3/README.md
63377
+ * Vibe scopes the tool-name `match` glob to tool hooks (`pre_tool` /
63378
+ * `post_tool`). The other events take a `match` too, on something other than a
63379
+ * tool name: the agent whose turn it is on `post_agent` / `pre_agent` /
63380
+ * `pre_llm` / `post_llm`, and the source, reason or notification type on
63381
+ * `session_start` / `session_end` / `notification`.
63382
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/plugins/builtins/vibe/skills/vibe/SKILL.md
62629
63383
  */
62630
63384
  const VIBE_TOOL_EVENTS = /* @__PURE__ */ new Set(["pre_tool", "post_tool"]);
63385
+ /**
63386
+ * The events where a failing hook may block, and so the only ones that accept
63387
+ * `strict`. Vibe's `HookConfig` validator rejects a `strict` entry of any
63388
+ * other type.
63389
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/hooks/models.py
63390
+ */
63391
+ const VIBE_STRICT_EVENTS = /* @__PURE__ */ new Set([
63392
+ "pre_tool",
63393
+ "post_tool",
63394
+ "pre_agent",
63395
+ "pre_llm",
63396
+ "post_llm"
63397
+ ]);
63398
+ /** The canonical matcher for a `pre_agent` hook that runs for every agent. */
63399
+ const VIBE_ANY_AGENT_MATCHER = "*";
63400
+ /** The Vibe event canonical `beforeSubmitPrompt` becomes. */
63401
+ const VIBE_PRE_AGENT_EVENT = "pre_agent";
62631
63402
  /** The Vibe event both canonical `stop` and `subagentStop` become. */
62632
63403
  const VIBE_POST_AGENT_EVENT = "post_agent";
62633
63404
  /**
@@ -62675,11 +63446,69 @@ function fromVibeHookMatch(match) {
62675
63446
  return match.toLowerCase() === VIBE_SHELL_HOOK_MATCH ? "Bash" : match;
62676
63447
  }
62677
63448
  /**
63449
+ * The `match` for an event whose matcher is not a tool name, or `undefined`
63450
+ * when the canonical matcher selects everything.
63451
+ */
63452
+ function toVibeOptionalMatch(matcher) {
63453
+ if (typeof matcher !== "string" || matcher === "" || matcher === "*") return;
63454
+ return matcher;
63455
+ }
63456
+ /**
63457
+ * The `match` of the Vibe entry a canonical hook becomes: a string, `undefined`
63458
+ * to leave the key out, or null to skip the hook.
63459
+ */
63460
+ function toVibeEntryMatch({ event, vibeEvent, matcher, logger }) {
63461
+ if (VIBE_TOOL_EVENTS.has(vibeEvent)) return toVibeHookMatch(matcher);
63462
+ if (event === "subagentStop") return toVibeSubagentMatch({
63463
+ matcher,
63464
+ logger
63465
+ });
63466
+ if (vibeEvent === VIBE_POST_AGENT_EVENT) return VIBE_MAIN_AGENT_MATCH;
63467
+ if (vibeEvent === VIBE_PRE_AGENT_EVENT) {
63468
+ if (typeof matcher !== "string" || matcher === "") return VIBE_MAIN_AGENT_MATCH;
63469
+ return toVibeOptionalMatch(matcher);
63470
+ }
63471
+ return toVibeOptionalMatch(matcher);
63472
+ }
63473
+ /**
63474
+ * The canonical event and matcher a Vibe entry's `type` and `match` become.
63475
+ */
63476
+ function fromVibeEntryMatch({ vibeEvent, canonicalEvent, match }) {
63477
+ if (VIBE_TOOL_EVENTS.has(vibeEvent)) return {
63478
+ canonicalEvent,
63479
+ matcher: fromVibeHookMatch(match)
63480
+ };
63481
+ const optionalMatch = toVibeOptionalMatch(match);
63482
+ const isMainAgent = optionalMatch === void 0 || optionalMatch.toLowerCase() === VIBE_MAIN_AGENT_MATCH;
63483
+ if (vibeEvent === VIBE_POST_AGENT_EVENT) return isMainAgent ? {
63484
+ canonicalEvent,
63485
+ matcher: void 0
63486
+ } : {
63487
+ canonicalEvent: "subagentStop",
63488
+ matcher: optionalMatch
63489
+ };
63490
+ if (vibeEvent === VIBE_PRE_AGENT_EVENT) {
63491
+ if (optionalMatch === void 0) return {
63492
+ canonicalEvent,
63493
+ matcher: VIBE_ANY_AGENT_MATCHER
63494
+ };
63495
+ return {
63496
+ canonicalEvent,
63497
+ matcher: isMainAgent ? void 0 : optionalMatch
63498
+ };
63499
+ }
63500
+ return {
63501
+ canonicalEvent,
63502
+ matcher: optionalMatch
63503
+ };
63504
+ }
63505
+ /**
62678
63506
  * Build the flat `[[hooks]]` array for `.vibe/hooks.toml` from a canonical
62679
63507
  * hooks config. Vibe uses a flat array where each entry carries its own event
62680
- * `type`, `match` glob/regex (a tool name for tool hooks, an agent name
62681
- * for `post_agent`), and `command`. Only `type: "command"`
62682
- * canonical hooks are emitted: a Vibe hook is a shell command line. (v2.25.1
63508
+ * `type`, `match` glob/regex (a tool name for tool hooks, an agent name for
63509
+ * `post_agent` / `pre_agent` / `pre_llm` / `post_llm`, a source, reason or
63510
+ * notification type for the session and notification hooks), and `command`.
63511
+ * Only `type: "command"` canonical hooks are emitted: a Vibe hook is a shell command line. (v2.25.1
62683
63512
  * to v2.25.4 briefly exec'd it without a shell under the unified harness and
62684
63513
  * skipped any command containing a backslash; v2.25.5 restored shell
62685
63514
  * execution — "Hook commands using pipes, `&&`, redirects, globs or `$VAR`
@@ -62704,27 +63533,23 @@ function canonicalToVibeHooks({ config, toolOverride, logger }) {
62704
63533
  for (const def of defs) {
62705
63534
  if ((def.type ?? "command") !== "command") continue;
62706
63535
  if (typeof def.command !== "string") continue;
62707
- const isToolEvent = VIBE_TOOL_EVENTS.has(vibeEvent);
62708
- let match;
62709
- if (isToolEvent) match = toVibeHookMatch(def.matcher);
62710
- else if (event === "subagentStop") {
62711
- const subagentMatch = toVibeSubagentMatch({
62712
- matcher: def.matcher,
62713
- logger
62714
- });
62715
- if (subagentMatch === null) continue;
62716
- match = subagentMatch;
62717
- } else match = VIBE_MAIN_AGENT_MATCH;
63536
+ const match = toVibeEntryMatch({
63537
+ event,
63538
+ vibeEvent,
63539
+ matcher: def.matcher,
63540
+ logger
63541
+ });
63542
+ if (match === null) continue;
62718
63543
  const index = nextIndexByVibeEvent.get(vibeEvent) ?? 0;
62719
63544
  const entry = {
62720
63545
  name: typeof def.name === "string" ? def.name : `${vibeEvent}-${index}`,
62721
63546
  type: vibeEvent,
62722
- match,
63547
+ ...match !== void 0 && { match },
62723
63548
  command: def.command
62724
63549
  };
62725
63550
  if (typeof def.timeout === "number") entry.timeout = def.timeout;
62726
63551
  const strict = def.strict;
62727
- if (isToolEvent && typeof strict === "boolean") entry.strict = strict;
63552
+ if (VIBE_STRICT_EVENTS.has(vibeEvent) && typeof strict === "boolean") entry.strict = strict;
62728
63553
  if (typeof def.description === "string") entry.description = def.description;
62729
63554
  hooks.push(entry);
62730
63555
  nextIndexByVibeEvent.set(vibeEvent, index + 1);
@@ -62739,22 +63564,22 @@ function vibeEntryToCanonicalDef(raw) {
62739
63564
  const vibeEvent = typeof entry.type === "string" ? entry.type : void 0;
62740
63565
  if (vibeEvent === void 0) return null;
62741
63566
  if (isPrototypePollutionKey(vibeEvent)) return null;
62742
- let canonicalEvent = lookupOwn({
63567
+ const mappedEvent = lookupOwn({
62743
63568
  record: VIBE_TO_CANONICAL_EVENT_NAMES,
62744
63569
  key: vibeEvent
62745
63570
  }) ?? vibeEvent;
62746
63571
  const def = { type: "command" };
62747
63572
  if (typeof entry.command === "string") def.command = entry.command;
62748
- if (vibeEvent === VIBE_POST_AGENT_EVENT) {
62749
- const agentMatch = typeof entry.match === "string" ? entry.match : "";
62750
- if (agentMatch !== "" && agentMatch !== "*" && agentMatch.toLowerCase() !== VIBE_MAIN_AGENT_MATCH) {
62751
- canonicalEvent = "subagentStop";
62752
- def.matcher = agentMatch;
62753
- }
62754
- } else {
62755
- const matcher = fromVibeHookMatch(entry.match);
62756
- if (matcher !== void 0) def.matcher = matcher;
62757
- }
63573
+ const resolved = fromVibeEntryMatch({
63574
+ vibeEvent: lookupOwn({
63575
+ record: CANONICAL_TO_VIBE_EVENT_NAMES,
63576
+ key: mappedEvent
63577
+ }) ?? vibeEvent,
63578
+ canonicalEvent: mappedEvent,
63579
+ match: entry.match
63580
+ });
63581
+ const canonicalEvent = resolved.canonicalEvent;
63582
+ if (resolved.matcher !== void 0) def.matcher = resolved.matcher;
62758
63583
  if (typeof entry.timeout === "number") def.timeout = entry.timeout;
62759
63584
  if (typeof entry.name === "string") def.name = entry.name;
62760
63585
  if (typeof entry.description === "string") def.description = entry.description;
@@ -62788,22 +63613,55 @@ function vibeHooksToCanonical(parsed) {
62788
63613
  /** Vibe reads a `match` with a `re:` prefix or glob metacharacters as a pattern. */
62789
63614
  const VIBE_PATTERN_MATCH = /^re:|[*?[]/;
62790
63615
  /**
62791
- * Move the imported `subagentStop` hooks into the `vibe` override when any of
62792
- * them matches agents by a regex or glob rather than by a literal name. Such a
62793
- * pattern can also select the main agent (a main session answers to its mode
62794
- * name, e.g. `accept-edits`), and other tools would read it as their own
62795
- * matcher syntax, so it is kept Vibe-only. The override replaces the shared
63616
+ * The canonical events whose imported hooks are kept Vibe-only once any of
63617
+ * them carries a matcher, with the reason for the warning. Their matcher
63618
+ * selects Vibe agents, which other tools either drop (Claude Code, with a
63619
+ * warning) or read as their own matcher syntax, so a hook scoped to one agent
63620
+ * — or, for `pre_agent`, to every agent including subagents — would fire
63621
+ * everywhere there. A `subagentStop` hook needs a matcher anyway, so only a
63622
+ * pattern (which may also select the main agent) moves it.
63623
+ */
63624
+ const VIBE_ONLY_AGENT_SCOPED_EVENTS = [
63625
+ {
63626
+ event: "subagentStop",
63627
+ vibeEvent: "post_agent",
63628
+ isVibeOnly: (matcher) => VIBE_PATTERN_MATCH.test(matcher)
63629
+ },
63630
+ {
63631
+ event: "beforeSubmitPrompt",
63632
+ vibeEvent: "pre_agent",
63633
+ isVibeOnly: () => true
63634
+ },
63635
+ {
63636
+ event: "preModelInvocation",
63637
+ vibeEvent: "pre_llm",
63638
+ isVibeOnly: () => true
63639
+ },
63640
+ {
63641
+ event: "postModelInvocation",
63642
+ vibeEvent: "post_llm",
63643
+ isVibeOnly: () => true
63644
+ }
63645
+ ];
63646
+ /**
63647
+ * Move the imported hooks of an agent-matched event into the `vibe` override
63648
+ * when any of them is scoped in a way other tools cannot express (see
63649
+ * {@link VIBE_ONLY_AGENT_SCOPED_EVENTS}). The override replaces the shared
62796
63650
  * list for its event, so the whole list moves to keep every entry on Vibe.
62797
63651
  */
62798
- function takeVibeOnlySubagentStop({ hooks, logger }) {
62799
- const defs = lookupOwn({
62800
- record: hooks,
62801
- key: "subagentStop"
62802
- });
62803
- if (defs === void 0 || !defs.some((def) => typeof def.matcher === "string" && VIBE_PATTERN_MATCH.test(def.matcher))) return;
62804
- delete hooks.subagentStop;
62805
- 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.");
62806
- return defs;
63652
+ function takeVibeOnlyAgentScopedHooks({ hooks, logger }) {
63653
+ const taken = {};
63654
+ for (const { event, vibeEvent, isVibeOnly } of VIBE_ONLY_AGENT_SCOPED_EVENTS) {
63655
+ const defs = lookupOwn({
63656
+ record: hooks,
63657
+ key: event
63658
+ });
63659
+ if (defs === void 0 || !defs.some((def) => typeof def.matcher === "string" && isVibeOnly(def.matcher))) continue;
63660
+ delete hooks[event];
63661
+ taken[event] = defs;
63662
+ 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.`);
63663
+ }
63664
+ return taken;
62807
63665
  }
62808
63666
  function parseVibeToml(fileContent) {
62809
63667
  const parsed = smolToml.parse(fileContent || smolToml.stringify({}));
@@ -62855,21 +63713,22 @@ var VibeHooks = class extends ToolHooks {
62855
63713
  displayName: "Vibe",
62856
63714
  parse: (fileContent) => parseVibeToml(fileContent)
62857
63715
  }));
62858
- const vibeOnlySubagentStop = takeVibeOnlySubagentStop({
63716
+ const vibeOnly = takeVibeOnlyAgentScopedHooks({
62859
63717
  hooks,
62860
63718
  logger: options.logger
62861
63719
  });
62862
63720
  const config = buildImportedHooksConfig({
63721
+ logger: options.logger,
62863
63722
  hooks,
62864
63723
  overrideKey: "vibe"
62865
63724
  });
62866
- if (vibeOnlySubagentStop !== void 0) {
63725
+ if (Object.keys(vibeOnly).length > 0) {
62867
63726
  const override = config.vibe ?? {};
62868
63727
  config.vibe = {
62869
63728
  ...override,
62870
63729
  hooks: {
62871
63730
  ...override.hooks,
62872
- subagentStop: vibeOnlySubagentStop
63731
+ ...vibeOnly
62873
63732
  }
62874
63733
  };
62875
63734
  }
@@ -63077,6 +63936,7 @@ var ZcodeHooks = class ZcodeHooks extends ToolHooks {
63077
63936
  logger
63078
63937
  });
63079
63938
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
63939
+ logger,
63080
63940
  hooks,
63081
63941
  overrideKey: "zcode"
63082
63942
  }), null, 2) });
@@ -63161,6 +64021,7 @@ var ZcodePluginHooks = class ZcodePluginHooks extends ToolHooks {
63161
64021
  logger
63162
64022
  });
63163
64023
  return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
64024
+ logger,
63164
64025
  hooks,
63165
64026
  overrideKey: "zcode"
63166
64027
  }), null, 2) });
@@ -78726,6 +79587,15 @@ const PERMISSION_ACTION_PRIORITY = {
78726
79587
  deny: 2
78727
79588
  };
78728
79589
  /**
79590
+ * A pattern map reordered allow, then ask, then deny, keeping the authored
79591
+ * order within each action. A tool that applies the last matching pattern
79592
+ * then lets the strictest matching rule win. `Object.fromEntries` defines own
79593
+ * properties, so even a `__proto__` pattern survives.
79594
+ */
79595
+ function sortRulesByActionPriority(rules) {
79596
+ return Object.fromEntries(Object.entries(rules).toSorted(([, a], [, b]) => PERMISSION_ACTION_PRIORITY[a] - PERMISSION_ACTION_PRIORITY[b]));
79597
+ }
79598
+ /**
78729
79599
  * Whether `action` should replace `existing` when two canonical rules collapse
78730
79600
  * onto one entry: an empty slot always takes it, otherwise only a strictly
78731
79601
  * stricter action (deny > ask > allow) does.
@@ -80396,7 +81266,13 @@ function splitUrlPattern(withoutScheme) {
80396
81266
  * (so an allowed `example.com` overlaps a restricted `*.pdf`), and an overlap
80397
81267
  * from any of them counts. A host ending in a DNS root dot (`example.com.`)
80398
81268
  * is also compared with one and with all trailing dots removed, in addition
80399
- * to its original reading, so this only ever adds overlaps. A pattern holding
81269
+ * to its original reading, so this only ever adds overlaps. The allow is also
81270
+ * compared without its userinfo, query and fragment
81271
+ * (`https://user@example.com/x?y=1#z` as `example.com/x`), which name no other
81272
+ * host or path, again in addition to its original reading. Only a `?` or `#`
81273
+ * in the path counts as a query or fragment start there, so a `?` glob in the
81274
+ * host is left alone (one in the path is read as a query start for this extra
81275
+ * reading, which can only add overlaps). A pattern holding
80400
81276
  * whitespace names no URL. Callers pass the restriction as `left` and the
80401
81277
  * allow as `right`.
80402
81278
  */
@@ -80419,12 +81295,7 @@ function urlPatternsOverlap(left, right) {
80419
81295
  */
80420
81296
  function wholeStringsOverlap(left, right) {
80421
81297
  const normalizedLeft = normalizeUrlPattern(left);
80422
- const normalizedRight = normalizeUrlPattern(right);
80423
- return [
80424
- [left, right],
80425
- [normalizedLeft, normalizedRight],
80426
- ...normalizedLeft.includes("/") ? [] : [[normalizedLeft, withAnyPath(normalizedRight)]]
80427
- ].some(([restriction = "", allow = ""]) => createShadowingRestrictionsTest([{
81298
+ return [[left, right], ...allowReadings(normalizeUrlPattern(right)).flatMap((normalizedRight) => [[normalizedLeft, normalizedRight], ...normalizedLeft.includes("/") ? [] : [[normalizedLeft, withAnyPath(normalizedRight)]]])].some(([restriction = "", allow = ""]) => createShadowingRestrictionsTest([{
80428
81299
  pattern: restriction,
80429
81300
  fromAllToolsCategory: false
80430
81301
  }])(allow).length > 0);
@@ -80433,8 +81304,25 @@ function wholeStringsOverlap(left, right) {
80433
81304
  function withAnyPath(withoutScheme) {
80434
81305
  return stripUrlSchemeKeepingPathCase(withoutScheme).includes("/") ? withoutScheme : `${withoutScheme}/*`;
80435
81306
  }
81307
+ /**
81308
+ * A scheme-less allow pattern as written, plus (when they differ) the same
81309
+ * pattern without the userinfo before its host and the query and fragment
81310
+ * after its path, so `user:pass@example.com/x?y=1` is also read as
81311
+ * `example.com/x`. A `?` is a single-character glob in Rulesync patterns, so
81312
+ * only a `?` or `#` in the path (after the first `/`) is read as a query or
81313
+ * fragment start; the host keeps it (`git?ub.com` is not cut to `git`). The
81314
+ * original reading stays first, so a caller that ORs the readings only ever
81315
+ * gains overlaps.
81316
+ */
81317
+ function allowReadings(withoutScheme) {
81318
+ const slash = withoutScheme.indexOf("/");
81319
+ const hostPort = slash === -1 ? withoutScheme : withoutScheme.slice(0, slash);
81320
+ const path = slash === -1 ? "" : withoutScheme.slice(slash).replace(/[?#].*$/s, "");
81321
+ const stripped = `${hostPort.slice(hostPort.lastIndexOf("@") + 1)}${path}`;
81322
+ return stripped === withoutScheme || stripped === "" ? [withoutScheme] : [withoutScheme, stripped];
81323
+ }
80436
81324
  function urlPartsOverlap(left, right) {
80437
- const readings = (pattern) => [.../* @__PURE__ */ new Set([stripUrlSchemeKeepingPathCase(pattern), stripUrlSchemeLoosely(pattern)])].map(splitUrlPattern).flatMap((parts) => parts.host.endsWith(".") ? [
81325
+ 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(".") ? [
80438
81326
  parts,
80439
81327
  {
80440
81328
  ...parts,
@@ -80445,7 +81333,8 @@ function urlPartsOverlap(left, right) {
80445
81333
  host: parts.host.replace(/\.+$/, "")
80446
81334
  }
80447
81335
  ] : [parts]);
80448
- return readings(left).some((a) => readings(right).some((b) => urlPartsPairOverlap(a, b)));
81336
+ const allowParts = readings(right, { asAllow: true });
81337
+ return readings(left).some((a) => allowParts.some((b) => urlPartsPairOverlap(a, b)));
80449
81338
  }
80450
81339
  function urlPartsPairOverlap(a, b) {
80451
81340
  const hosts = (host) => [host, `*.${host}`];
@@ -81949,8 +82838,11 @@ var AugmentcodePermissions = class AugmentcodePermissions extends ToolPermission
81949
82838
  * does nothing.
81950
82839
  *
81951
82840
  * Only Auggie 0.x reads `recommendedMarketplaces`: the 1.x plugin settings
81952
- * reference lists `enabledPlugins` alone. The key is still written because the
81953
- * stable CLI is 0.x, and the write warning says it is 0.x-only.
82841
+ * reference lists `enabledPlugins` alone, and the 1.x settings loader never
82842
+ * reads the key. 1.x is the stable CLI since 1.2.0, so the key now reaches only
82843
+ * users pinned to 0.x (npm `v0-release` with auto-update off). It is still
82844
+ * written for them, and the write warning says so.
82845
+ * @see https://www.augmentcode.com/changelog
81954
82846
  *
81955
82847
  * Both make Auggie load code the repository did not ship — a recommended
81956
82848
  * marketplace is one prompt away from being cloned, and an enabled plugin can
@@ -81971,7 +82863,7 @@ function buildPluginConsumptionPatch({ override, existing, global, logger }) {
81971
82863
  else {
81972
82864
  patch.recommendedMarketplaces = recommendedMarketplaces;
81973
82865
  const existingMarketplaces = existingKeys.recommendedMarketplaces;
81974
- if (recommendedMarketplaces.length > 0 && !isDeepStrictEqual(recommendedMarketplaces, existingMarketplaces)) logger?.warn(`Writing AugmentCode \`recommendedMarketplaces\` (${recommendedMarketplaces.map(quoteValueForWarning).join(", ")}): Auggie 0.x prompts everyone who opens this workspace to install these plugin marketplaces (Auggie 1.x no longer reads this key).`);
82866
+ if (recommendedMarketplaces.length > 0 && !isDeepStrictEqual(recommendedMarketplaces, existingMarketplaces)) logger?.warn(`Writing AugmentCode \`recommendedMarketplaces\` (${recommendedMarketplaces.map(quoteValueForWarning).join(", ")}): Auggie 0.x prompts everyone who opens this workspace to install these plugin marketplaces (Auggie 1.x no longer reads this key, so only users pinned to Auggie 0.x see the prompt).`);
81975
82867
  warnAboutRemovedPluginIds({
81976
82868
  key: "recommendedMarketplaces",
81977
82869
  removed: (existingMarketplaces ?? []).filter((marketplace) => !recommendedMarketplaces.includes(marketplace)),
@@ -87514,6 +88406,173 @@ function parseCommandcodeRuleLists(permissions) {
87514
88406
  return permission;
87515
88407
  }
87516
88408
  /**
88409
+ * The non-list `permissions` fields rulesync authors through the
88410
+ * `commandcode.permissions` override and imports back. Every other key of the
88411
+ * file's `permissions` object is kept as it is, never written from the source.
88412
+ */
88413
+ const COMMANDCODE_PERMISSIONS_FIELD_KEYS = [
88414
+ "defaultMode",
88415
+ "additionalDirectories",
88416
+ "disableBypass"
88417
+ ];
88418
+ const ACCEPT_EDITS_REASON = "workspace edits and safe filesystem shell commands then run without a prompt";
88419
+ const YOLO_REASON = "every session then starts in permission bypass, where only deny and ask rules still stop a tool";
88420
+ /**
88421
+ * The `permissions.defaultMode` values (aliases included) that start a session
88422
+ * with fewer prompts than `default`. `plan` and `dont-ask` are absent: `plan`
88423
+ * is read-only, and `dont-ask` is a fail-closed allowlist that denies whatever
88424
+ * policy does not already allow, so neither widens anything.
88425
+ *
88426
+ * @see https://commandcode.ai/docs/permissions
88427
+ */
88428
+ const COMMANDCODE_WIDENING_DEFAULT_MODES = {
88429
+ "accept-edits": ACCEPT_EDITS_REASON,
88430
+ "auto-accept": ACCEPT_EDITS_REASON,
88431
+ acceptEdits: ACCEPT_EDITS_REASON,
88432
+ yolo: YOLO_REASON,
88433
+ bypass: YOLO_REASON,
88434
+ bypassPermissions: YOLO_REASON
88435
+ };
88436
+ /**
88437
+ * How many prompts each documented `defaultMode` (aliases included) removes:
88438
+ * `plan` and `dont-ask` (fail-closed) < `default` < `accept-edits` < `yolo`.
88439
+ * Used to notice an override that replaces a stricter mode already in the file.
88440
+ */
88441
+ const COMMANDCODE_DEFAULT_MODE_LOOSENESS = {
88442
+ plan: 0,
88443
+ "dont-ask": 0,
88444
+ dontAsk: 0,
88445
+ default: 1,
88446
+ manual: 1,
88447
+ standard: 1,
88448
+ "accept-edits": 2,
88449
+ "auto-accept": 2,
88450
+ acceptEdits: 2,
88451
+ yolo: 3,
88452
+ bypass: 3,
88453
+ bypassPermissions: 3
88454
+ };
88455
+ /**
88456
+ * Command Code resolves settings project-local > project > user-global, and a
88457
+ * scalar from the more specific file overwrites the others (only the rule
88458
+ * lists and `additionalDirectories` union across files). A project-scope
88459
+ * `defaultMode` or `disableBypass` therefore replaces whatever the user set in
88460
+ * `~/.commandcode/settings.json`.
88461
+ *
88462
+ * @see https://commandcode.ai/docs/settings
88463
+ */
88464
+ 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";
88465
+ /**
88466
+ * The widening entry for a `commandcode.permissions.defaultMode`, or `null`
88467
+ * when it does not widen. A mode that removes prompts always widens; at
88468
+ * project scope so does any mode looser than the strictest ones (`plan`,
88469
+ * `dont-ask`), because it overrides the user-global mode; and so does a mode
88470
+ * looser than the one already in the file. An undocumented mode is warned
88471
+ * about on its own.
88472
+ */
88473
+ function defaultModeWideningEntry({ defaultMode, replaced, global, logger }) {
88474
+ const label = `permissions.defaultMode: "${defaultMode}"`;
88475
+ const projectNote = global ? [] : [PROJECT_SCALAR_OVERRIDES_GLOBAL];
88476
+ const reason = lookupOwn({
88477
+ record: COMMANDCODE_WIDENING_DEFAULT_MODES,
88478
+ key: defaultMode
88479
+ });
88480
+ if (reason !== void 0) return `${label} (${[reason, ...projectNote].join("; ")})`;
88481
+ const looseness = lookupOwn({
88482
+ record: COMMANDCODE_DEFAULT_MODE_LOOSENESS,
88483
+ key: defaultMode
88484
+ });
88485
+ if (looseness === void 0) {
88486
+ 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.`);
88487
+ return null;
88488
+ }
88489
+ const replacedLooseness = typeof replaced === "string" ? lookupOwn({
88490
+ record: COMMANDCODE_DEFAULT_MODE_LOOSENESS,
88491
+ key: replaced
88492
+ }) : void 0;
88493
+ const notes = replacedLooseness !== void 0 && looseness > replacedLooseness ? [`replaces the stricter "${String(replaced)}" already in the file`] : [];
88494
+ if (looseness > 0) notes.push(...projectNote);
88495
+ return notes.length > 0 ? `${label} (${notes.join("; ")})` : null;
88496
+ }
88497
+ /**
88498
+ * Name, in one warning, every `commandcode.permissions` value that widens what
88499
+ * Command Code trusts. At project scope the scalars also override the
88500
+ * user-global file, which the warning says explicitly.
88501
+ */
88502
+ function warnWideningCommandcodeFields({ fields, existingPermissions, global, logger }) {
88503
+ const widening = [];
88504
+ const { defaultMode, additionalDirectories, disableBypass } = fields;
88505
+ if (typeof defaultMode === "string") {
88506
+ const entry = defaultModeWideningEntry({
88507
+ defaultMode,
88508
+ replaced: existingPermissions.defaultMode,
88509
+ global,
88510
+ logger
88511
+ });
88512
+ if (entry !== null) widening.push(entry);
88513
+ }
88514
+ if (Array.isArray(additionalDirectories) && additionalDirectories.length > 0) widening.push("permissions.additionalDirectories (each directory then counts as inside the workspace for reads and writes)");
88515
+ 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") + ")");
88516
+ if (widening.length > 0) logger?.warn(`Command Code permissions: the commandcode override widens what Command Code trusts: ${widening.join("; ")}.`);
88517
+ }
88518
+ /**
88519
+ * The fields of the `commandcode.permissions` override to merge into the
88520
+ * settings file's `permissions` object. Only the documented
88521
+ * `COMMANDCODE_PERMISSIONS_FIELD_KEYS` are written: the `allow`/`ask`/`deny`
88522
+ * lists are rulesync's (built from the shared `permission` block) and any
88523
+ * other key is ignored, so the override can never smuggle a grant past the
88524
+ * list handling. A value that widens trust — a `defaultMode` that removes
88525
+ * prompts (or replaces a stricter one already in the file or, at project
88526
+ * scope, in the user-global file), a non-empty `additionalDirectories`, a
88527
+ * `disableBypass` that does not disable — is still written, but named in one
88528
+ * warning: this file is
88529
+ * shareable through `rulesync fetch`, and a loosening should not be silent.
88530
+ */
88531
+ function commandcodePermissionsFields({ config, existingPermissions, global, logger }) {
88532
+ const override = config.commandcode?.permissions;
88533
+ if (!isRecord(override)) return {};
88534
+ const fields = {};
88535
+ for (const [key, value] of Object.entries(override)) {
88536
+ if (isPrototypePollutionKey(key) || value === void 0) continue;
88537
+ if (!COMMANDCODE_PERMISSIONS_FIELD_KEYS.includes(key)) {
88538
+ 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)" : ""}.`);
88539
+ continue;
88540
+ }
88541
+ fields[key] = value;
88542
+ }
88543
+ warnWideningCommandcodeFields({
88544
+ fields,
88545
+ existingPermissions,
88546
+ global,
88547
+ logger
88548
+ });
88549
+ return fields;
88550
+ }
88551
+ /**
88552
+ * Read the documented non-list `permissions` fields back for the
88553
+ * `commandcode.permissions` override, verbatim. A value of a type Command Code
88554
+ * does not document is skipped with a warning rather than imported into a
88555
+ * source that would then fail validation; it stays in the settings file,
88556
+ * which a regenerate leaves untouched. Nothing here reaches the shared
88557
+ * `permission` block, so a mode or directory set for Command Code never turns
88558
+ * into a grant for another target.
88559
+ */
88560
+ function importCommandcodePermissionsFields(permissions) {
88561
+ const fields = {};
88562
+ 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.`);
88563
+ const { defaultMode, additionalDirectories, disableBypass } = permissions;
88564
+ if (typeof defaultMode === "string") fields.defaultMode = defaultMode;
88565
+ else if (defaultMode !== void 0) skip("defaultMode");
88566
+ if (Array.isArray(additionalDirectories)) {
88567
+ const directories = additionalDirectories.filter((entry) => typeof entry === "string");
88568
+ if (directories.length < additionalDirectories.length) fallbackLogger.warn("Command Code permissions: 'permissions.additionalDirectories' holds entries that are not strings; only the string entries were imported.");
88569
+ fields.additionalDirectories = directories;
88570
+ } else if (additionalDirectories !== void 0) skip("additionalDirectories");
88571
+ if (typeof disableBypass === "boolean" || disableBypass === "disable") fields.disableBypass = disableBypass;
88572
+ else if (disableBypass !== void 0) skip("disableBypass");
88573
+ return fields;
88574
+ }
88575
+ /**
87517
88576
  * Permissions generator for Command Code.
87518
88577
  *
87519
88578
  * Rules live under the `permissions` key of `.commandcode/settings.json`
@@ -87521,8 +88580,10 @@ function parseCommandcodeRuleLists(permissions) {
87521
88580
  * Claude-style entries: `deny` (always wins), `ask`, `allow`. The same key
87522
88581
  * also carries `defaultMode`, `additionalDirectories` and `disableBypass`,
87523
88582
  * and the file holds `hooks` and other settings, so writes go through the
87524
- * shared-config gateway: rulesync replaces the three lists, keeps every
87525
- * sibling key, and never deletes the file.
88583
+ * shared-config gateway: rulesync replaces the three lists, merges those
88584
+ * three fields from the `commandcode.permissions` override (warning on values
88585
+ * that widen trust), keeps every other sibling key, and never deletes the
88586
+ * file. Import reads the three fields back into that override.
87526
88587
  *
87527
88588
  * Generate: `permission.<category>.<pattern>` becomes `Tool(pattern)` with
87528
88589
  * the friendly names (`Shell`, `Read`, `Edit`, `Write`, `WebFetch`,
@@ -87573,12 +88634,21 @@ var CommandcodePermissions = class CommandcodePermissions extends ToolPermission
87573
88634
  relativePath: join(paths.relativeDirPath, paths.relativeFilePath)
87574
88635
  });
87575
88636
  const existingPermissions = isRecord(existing[COMMANDCODE_PERMISSIONS_KEY]) ? existing[COMMANDCODE_PERMISSIONS_KEY] : {};
88637
+ const config = rulesyncPermissions.getJson();
87576
88638
  const lists = buildCommandcodeRuleLists({
87577
- config: rulesyncPermissions.getJson(),
88639
+ config,
87578
88640
  existingPermissions,
87579
88641
  logger
87580
88642
  });
87581
- const permissions = { ...existingPermissions };
88643
+ const permissions = {
88644
+ ...existingPermissions,
88645
+ ...commandcodePermissionsFields({
88646
+ config,
88647
+ existingPermissions,
88648
+ global,
88649
+ logger
88650
+ })
88651
+ };
87582
88652
  for (const key of [
87583
88653
  "allow",
87584
88654
  "ask",
@@ -87606,7 +88676,10 @@ var CommandcodePermissions = class CommandcodePermissions extends ToolPermission
87606
88676
  relativePath: join(this.getRelativeDirPath(), this.getRelativeFilePath())
87607
88677
  });
87608
88678
  const permissions = isRecord(settings[COMMANDCODE_PERMISSIONS_KEY]) ? settings[COMMANDCODE_PERMISSIONS_KEY] : {};
87609
- return this.toRulesyncPermissionsDefault({ fileContent: JSON.stringify({ permission: parseCommandcodeRuleLists(permissions) }, null, 2) });
88679
+ const imported = { permission: parseCommandcodeRuleLists(permissions) };
88680
+ const fields = importCommandcodePermissionsFields(permissions);
88681
+ if (Object.keys(fields).length > 0) imported.commandcode = { permissions: fields };
88682
+ return this.toRulesyncPermissionsDefault({ fileContent: JSON.stringify(imported, null, 2) });
87610
88683
  }
87611
88684
  };
87612
88685
  /**
@@ -88706,9 +89779,11 @@ function effectiveSafeCommandLine(entry) {
88706
89779
  * and without a Windows executable suffix. A `*` in the command word may
88707
89780
  * stand for a directory and part of a name, so when what follows it is the
88708
89781
  * tail of a wrapper name, everything before it collapses into `*`
88709
- * (`b*nice` -> `*nice`, `/u*v` -> `*v`; `rm*` is left alone). The rest of the pattern is lower-cased as well, for a
88710
- * nested wrapper spelled in another case. Used only to compare against the
88711
- * wrapper spellings of a safe line, where it can only withhold more.
89782
+ * (`b*nice` -> `*nice`, `/u*v` -> `*v`; `rm*` is left alone). The rest of
89783
+ * the pattern is lower-cased as well, for a nested wrapper spelled in another
89784
+ * case. Used only to compare against a lower-cased safe line, its `--` form
89785
+ * and its wrapper spellings. Lower-casing the arguments too can only withhold
89786
+ * more: a `go BUILD` deny also withholds `go build` (fail-closed).
88712
89787
  */
88713
89788
  function normalizeRestrictionCommandWord(pattern) {
88714
89789
  const space = pattern.indexOf(" ");
@@ -88725,9 +89800,9 @@ function normalizeRestrictionCommandWord(pattern) {
88725
89800
  * rules govern a command Crush would approve through it? Besides the line
88726
89801
  * itself, Crush approves it followed by `--` and behind a wrapper (or the
88727
89802
  * `time` keyword), whose name it normalizes (`./nice`, `/usr/bin/env`, `NICE`,
88728
- * `nohup.exe`). The line and its wrapper spellings are compared against the
88729
- * restrictions as written, and the wrapper spellings also against the
88730
- * restrictions with their command word normalized the same way — which keeps
89803
+ * `nohup.exe`). The line, its `--` form and its wrapper spellings are compared
89804
+ * against both the restrictions as written and those with their command word
89805
+ * normalized like Crush (including executable paths and case) — which keeps
88731
89806
  * an unrelated `rm *` from withholding the line, as a leading wildcard on the
88732
89807
  * spelling would. Canonically the stricter rule wins whatever its width
88733
89808
  * (`deny > ask > allow`), so any overlap withholds the line.
@@ -88751,7 +89826,7 @@ function createSafeCommandShadowTest(permission) {
88751
89826
  });
88752
89827
  const withSeparator = (spellings) => spellings.flatMap((spelling) => [spelling, `${spelling} --*`]);
88753
89828
  const wrapped = (base) => CRUSH_COMMAND_PREFIXES.map((prefix) => `${prefix}*${base}`);
88754
- return (line) => uniq$1([...withSeparator([line, ...wrapped(line)]).flatMap((spelling) => test(spelling)), ...withSeparator(wrapped(line.toLowerCase())).flatMap((spelling) => testNormalized(spelling).map((pattern) => originalOf.get(pattern) ?? pattern))]);
89829
+ return (line) => uniq$1([...withSeparator([line, ...wrapped(line)]).flatMap((spelling) => test(spelling)), ...withSeparator([line.toLowerCase(), ...wrapped(line.toLowerCase())]).flatMap((spelling) => testNormalized(spelling).map((pattern) => originalOf.get(pattern) ?? pattern))]);
88755
89830
  }
88756
89831
  function uniq$1(values) {
88757
89832
  return [...new Set(values)];
@@ -92522,7 +93597,14 @@ function convertJunieToRulesyncPermissions({ allowlist }) {
92522
93597
  * restriction is restated at the end of every other key that holds a looser
92523
93598
  * rule it overlaps, where it is matched after that rule. A `*` catch-all
92524
93599
  * (`{"*": {"*": "ask"}}` followed by per-tool allows) is the documented way to
92525
- * set an OpenCode default, so it is left where it is.
93600
+ * set an OpenCode default, so it is not restated in the later keys.
93601
+ *
93602
+ * The `*` key's own patterns are reordered allow, then ask, then deny, so the
93603
+ * strictest matching one wins there too. This disables an allow carve-out
93604
+ * under a broader ask or deny in that key (`{"*": "deny", "src/**": "allow"}`
93605
+ * denies `src/**` as well), so a warning is logged whenever the order changes,
93606
+ * unless `<target>.permission["*"]` (`allToolsOverridden`) replaces the key
93607
+ * with an exact order anyway.
92526
93608
  *
92527
93609
  * A restated rule must never land after an overlapping stricter one, or it
92528
93610
  * would loosen what that rule says. The tail of a key is therefore written
@@ -92531,15 +93613,23 @@ function convertJunieToRulesyncPermissions({ allowlist }) {
92531
93613
  * then the restated `*` denies. A key whose own catch-all is a deny covers
92532
93614
  * every input of a restated ask already, so such an ask is restated as a deny.
92533
93615
  */
92534
- function restateAllToolsRestrictionsLast(sharedPermission) {
93616
+ function restateAllToolsRestrictionsLast({ sharedPermission, toolTarget, allToolsOverridden = false, logger }) {
92535
93617
  const allToolsRules = Object.hasOwn(sharedPermission, "*") ? sharedPermission["*"] : void 0;
92536
93618
  const restrictions = Object.entries(allToolsRules ?? {}).filter(([pattern, action]) => action !== "allow" && pattern !== "*" && !isPrototypePollutionKey(pattern));
92537
- if (restrictions.length === 0) return sharedPermission;
93619
+ if (restrictions.length === 0 && !allToolsRules) return sharedPermission;
92538
93620
  const result = {};
92539
- for (const [key, rules] of Object.entries(sharedPermission)) result[key] = key === "*" ? rules : restateInKey({
92540
- rules,
92541
- restrictions
92542
- });
93621
+ for (const [key, rules] of Object.entries(sharedPermission)) {
93622
+ if (key !== "*") {
93623
+ result[key] = restateInKey({
93624
+ rules,
93625
+ restrictions
93626
+ });
93627
+ continue;
93628
+ }
93629
+ const sorted = sortRulesByActionPriority(rules);
93630
+ if (!allToolsOverridden && !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.`);
93631
+ result[key] = sorted;
93632
+ }
92543
93633
  return result;
92544
93634
  }
92545
93635
  function globsOverlap(left, right) {
@@ -92791,7 +93881,12 @@ var KiloPermissions = class KiloPermissions extends ToolPermissions {
92791
93881
  const rulesyncJson = rulesyncPermissions.getJson();
92792
93882
  const kiloOverride = rulesyncJson.kilo;
92793
93883
  const incomingPermission = {
92794
- ...restateAllToolsRestrictionsLast(honorAllToolsOnBash(rulesyncJson.permission)),
93884
+ ...restateAllToolsRestrictionsLast({
93885
+ sharedPermission: honorAllToolsOnBash(rulesyncJson.permission),
93886
+ toolTarget: "kilo",
93887
+ allToolsOverridden: Object.hasOwn(kiloOverride?.permission ?? {}, "*"),
93888
+ logger
93889
+ }),
92795
93890
  ...kiloOverride?.permission
92796
93891
  };
92797
93892
  if (!global && Object.hasOwn(incomingPermission, KILO_MARKDOWN_SOURCE_KEY)) {
@@ -94403,7 +95498,7 @@ function mergePatternRules(base, incoming) {
94403
95498
  action,
94404
95499
  existing: Object.hasOwn(merged, pattern) ? merged[pattern] : void 0
94405
95500
  })) merged[pattern] = action;
94406
- return Object.fromEntries(Object.entries(merged).toSorted(([, a], [, b]) => PERMISSION_ACTION_PRIORITY[a] - PERMISSION_ACTION_PRIORITY[b]));
95501
+ return sortRulesByActionPriority(merged);
94407
95502
  }
94408
95503
  function toCanonicalPermissionKey(opencodeKey) {
94409
95504
  return lookupOwn({
@@ -94464,7 +95559,7 @@ function fromOpencodeV2PermissionRules(rules) {
94464
95559
  * written under the key OpenCode actually reads. A folded `write` is merged
94465
95560
  * with any canonical `edit` rules rather than replacing them.
94466
95561
  */
94467
- function toOpencodeSharedPermission({ permission, toolTarget, logger }) {
95562
+ function toOpencodeSharedPermission({ permission, toolTarget, allToolsOverridden, logger }) {
94468
95563
  const sharedPermission = {};
94469
95564
  for (const [category, value] of Object.entries(honorAllToolsOnBash(permission))) {
94470
95565
  if (OPENCODE_UNSUPPORTED_PERMISSION_CATEGORIES.has(category)) {
@@ -94485,7 +95580,12 @@ function toOpencodeSharedPermission({ permission, toolTarget, logger }) {
94485
95580
  sharedPermission[key] = merged;
94486
95581
  } else sharedPermission[key] = value;
94487
95582
  }
94488
- return restateAllToolsRestrictionsLast(sharedPermission);
95583
+ return restateAllToolsRestrictionsLast({
95584
+ sharedPermission,
95585
+ toolTarget,
95586
+ allToolsOverridden,
95587
+ logger
95588
+ });
94489
95589
  }
94490
95590
  const OpencodePermissionsConfigSchema = z.looseObject({
94491
95591
  permission: z.optional(z.union([z.enum([
@@ -94589,6 +95689,7 @@ var OpencodePermissions = class extends ToolPermissions {
94589
95689
  const sharedPermission = toOpencodeSharedPermission({
94590
95690
  permission: rulesyncJson.permission ?? {},
94591
95691
  toolTarget: this.layout.toolTarget,
95692
+ allToolsOverridden: Object.hasOwn(overridePermission, "*"),
94592
95693
  logger
94593
95694
  });
94594
95695
  const isV2 = this.layout.configVersion === "v2";
@@ -100190,28 +101291,31 @@ function parseTraePermissionConfig({ fileContent, relativePath }) {
100190
101291
  const moduleLogger = fallbackLogger;
100191
101292
  /**
100192
101293
  * Vibe's builtin tool names are the snake_case of each tool class
100193
- * (`BaseTool.get_name()`): `Edit` → `edit`, `WebFetch` → `web_fetch`,
100194
- * `WebSearch` → `web_search`, alongside `read_file`, `write_file` and `bash`.
101294
+ * (`BaseTool.get_name()`): `Edit` → `edit`, alongside `read_file`,
101295
+ * `write_file` and `bash`.
100195
101296
  * `edit` and `write_file` are distinct tools — `write_file` has been
100196
101297
  * create-only since v2.14.0 — so the canonical `edit` and `write` categories
100197
101298
  * must not collapse onto one name.
100198
101299
  *
100199
- * `grep` and `agent` have no table here: since v3.0.0 every session runs on
100200
- * the Unified Harness, which reads `[tools.*]` only for its Rust builtins
100201
- * (`RUST_BUILTIN_TOOL_SOURCES`). There is no grep tool any more — searching
100202
- * goes through the shell — and subagents are spawned by the built-in
100203
- * `agents.spawn` tool, which the `enable_subagents` switch governs instead of
100204
- * a `[tools.task]` table. See {@link VIBE_RETIRED_TOOL_TABLES}.
101300
+ * `grep`, `agent`, `webfetch` and `websearch` have no table here: since
101301
+ * v3.0.0 every session runs on the Unified Harness, which reads `[tools.*]`
101302
+ * only for its Rust builtins (`RUST_BUILTIN_TOOL_SOURCES`). There is no grep
101303
+ * tool any more — searching goes through the shell — and subagents are
101304
+ * spawned by the built-in `agents.spawn` tool, which the `enable_subagents`
101305
+ * switch governs instead of a `[tools.task]` table. `web_fetch` and
101306
+ * `web_search` are in Vibe's `RETIRED_TOOL_NAMES`: pages are fetched and the
101307
+ * web searched by the `connector_web_search_open_url` /
101308
+ * `connector_web_search_web_search` connector tools. See
101309
+ * {@link VIBE_RETIRED_TOOL_TABLES}.
100205
101310
  * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.2/vibe/app_server/_unified_permissions.py
100206
101311
  * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.2/vibe/app_server/_ignored_tool_settings.py
101312
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/config/_setting_keys.py
100207
101313
  */
100208
101314
  const CANONICAL_TO_VIBE_TOOL_NAMES = {
100209
101315
  bash: "bash",
100210
101316
  read: "read_file",
100211
101317
  edit: "edit",
100212
- write: "write_file",
100213
- webfetch: "web_fetch",
100214
- websearch: "web_search"
101318
+ write: "write_file"
100215
101319
  };
100216
101320
  /**
100217
101321
  * The tables earlier rulesync versions wrote for canonical categories that
@@ -100219,15 +101323,38 @@ const CANONICAL_TO_VIBE_TOOL_NAMES = {
100219
101323
  * effect"), `[tools.task]` for the subagent tool v3.0.0 renamed to
100220
101324
  * `agents.*`, and `[tools.external_directory]` — Vibe has no such tool, and
100221
101325
  * its unused-settings check skips unknown tool names as custom/MCP tools, so
100222
- * that deny was silently inert. A regenerate that configures the category removes them — and
100223
- * the matching `disabled_tools` entry — instead of leaving an inert table.
101326
+ * that deny was silently inert. `[tools.web_fetch]` / `[tools.web_search]`
101327
+ * are inert for the same reason: Vibe 3.x retired both tools, and v3.1.3 warns
101328
+ * about a tool filter naming them. A regenerate that configures the category
101329
+ * removes them — and the matching `disabled_tools` entry — instead of leaving
101330
+ * an inert table.
100224
101331
  * Import still reads them (see {@link VIBE_TO_CANONICAL_TOOL_NAMES}), so a
100225
101332
  * Vibe 2.x config is lifted into the canonical categories rather than lost.
100226
101333
  */
100227
101334
  const VIBE_RETIRED_TOOL_TABLES = {
100228
101335
  grep: "grep",
100229
101336
  agent: "task",
100230
- external_directory: "external_directory"
101337
+ external_directory: "external_directory",
101338
+ webfetch: "web_fetch",
101339
+ websearch: "web_search"
101340
+ };
101341
+ /**
101342
+ * The connector tools that replaced Vibe's retired web builtins, by canonical
101343
+ * category, so the skip warning can say where to write the rule instead.
101344
+ * rulesync does not write them itself: whether their `allowlist` / `denylist`
101345
+ * keys carry the old tools' semantics is not documented upstream.
101346
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/core/config/_setting_keys.py
101347
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.3/vibe/plugins/builtins/vibe/skills/vibe/SKILL.md
101348
+ */
101349
+ const VIBE_WEB_CONNECTOR_TOOLS = {
101350
+ webfetch: {
101351
+ retired: "web_fetch",
101352
+ connector: "connector_web_search_open_url"
101353
+ },
101354
+ websearch: {
101355
+ retired: "web_search",
101356
+ connector: "connector_web_search_web_search"
101357
+ }
100231
101358
  };
100232
101359
  /** The canonical category Vibe's `enable_subagents` switch expresses. */
100233
101360
  const VIBE_SUBAGENT_CATEGORY = "agent";
@@ -100603,7 +101730,7 @@ function retireLegacyToolTables({ permission, tools, disabledTools, logger }) {
100603
101730
  }
100604
101731
  if (disabledTools.delete(legacyToolName)) removed.push(`disabled_tools entry '${legacyToolName}'`);
100605
101732
  }
100606
- 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.`);
101733
+ 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.`);
100607
101734
  }
100608
101735
  /**
100609
101736
  * Report the rules of a category that has no Vibe tool table. `grep` gets its
@@ -100619,6 +101746,14 @@ function warnOnUnmappedCategory({ category, rules, logger }) {
100619
101746
  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.`);
100620
101747
  return;
100621
101748
  }
101749
+ const webTool = lookupOwn({
101750
+ record: VIBE_WEB_CONNECTOR_TOOLS,
101751
+ key: category
101752
+ });
101753
+ if (webTool !== void 0) {
101754
+ 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.`);
101755
+ return;
101756
+ }
100622
101757
  logger?.warn(`Vibe has no tool table for the '${category}' category; skipping ${ruleCount} rule(s) instead of emitting an inert [tools.${category}] table.`);
100623
101758
  }
100624
101759
  /**
@@ -100829,7 +101964,7 @@ function retireWithheldAllows({ source, permission, tools, resolveNames }) {
100829
101964
  fromAllToolsCategory: false
100830
101965
  }));
100831
101966
  const globShadowed = createShadowingRestrictionsTest(restrictions);
100832
- const shadowed = (pattern) => category === "webfetch" ? restrictions.some((restriction) => urlPatternsOverlap(restriction.pattern, pattern)) : globShadowed(pattern).length > 0;
101967
+ const shadowed = (pattern) => globShadowed(pattern).length > 0;
100833
101968
  const retires = (pattern) => withheld.has(pattern) || restrictions.length > 0 && honored[pattern] !== "allow" && shadowed(pattern);
100834
101969
  for (const vibeToolName of resolveNames(category) ?? []) {
100835
101970
  if (!Object.hasOwn(tools, vibeToolName)) continue;
@@ -105996,4 +107131,4 @@ const CHECKS_IMPORT_STRATEGY = {
105996
107131
  };
105997
107132
  export { RulesyncRule as $, RULESYNC_RULES_RELATIVE_DIR_PATH as $n, getFileSizeAndExecutableBit as $t, CODEBUDDY_LOCAL_RULE_FILE_NAME as A, ToolTargetSchema as An, fallbackLogger as At, CLAUDECODE_LOCAL_RULE_FILE_NAME as B, RULESYNC_CONFIG_RELATIVE_FILE_PATH as Bn, assertDirectoryIfExists as Bt, LETTACODE_DIR as C, toPosixPath as Cn, SourceEntrySchema as Ct, COMMANDCODE_DIR as D, ALL_TOOL_TARGETS as Dn, ConsoleLogger as Dt, FACTORYDROID_SETTINGS_LOCAL_FILE_NAME as E, mapWithConcurrency as En, findControlCharacter as Et, sweepRefusalReason as F, FEATURE_SOURCE_TREE_ENTRIES as Fn, CLIError as Ft, toInstructionBudgetFile as G, RULESYNC_IGNORE_RELATIVE_FILE_PATH as Gn, assertWritablePathInsideRoot as Gt, CLAUDECODE_SETTINGS_LOCAL_FILE_NAME as H, RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH as Hn, assertNoSymlinkBelowRoot as Ht, CODEXCLI_BASH_RULES_FILE_NAME as I, MAX_FILE_SIZE as In, ErrorCodes as It, getLocalSkillDirNames as J, RULESYNC_MCP_SCHEMA_URL as Jn, directoryExists as Jt, classifyRemoteName as K, RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH as Kn, checkPathTraversal as Kt, CODEXCLI_DIR as L, RULESYNC_AIIGNORE_RELATIVE_FILE_PATH as Ln, parseJsonc as Lt, AUGMENTCODE_SETTINGS_LOCAL_FILE_NAME as M, ALL_FEATURES_WITH_WILDCARD as Mn, withFallbackLoggerTarget as Mt, caseFoldIdentity as N, DEPRECATED_FEATURE_REPLACEMENTS as Nn, resetRunWarningState as Nt, COMMANDCODE_SETTINGS_LOCAL_FILE_NAME as O, ALL_TOOL_TARGETS_WITH_WILDCARD as On, JsonLogger as Ot, groupSpellingsByCaseFoldedIdentity as P, CURATED_RULES_FEATURE_SUBDIR as Pn, withWarnOnceScope as Pt, RulesyncSkillFrontmatterSchema as Q, RULESYNC_RELATIVE_DIR_PATH as Qn, findFilesByGlobs as Qt, CLAUDECODE_AGENT_MEMORY_LOCAL_DIR_NAME as R, RULESYNC_CHECKS_RELATIVE_DIR_PATH as Rn, PathOutsideRootError as Rt, QWENCODE_LOCAL_RULE_FILE_NAME as S, splitPathSegments as Sn, GITIGNORE_DESTINATION_KEY as St, FACTORYDROID_DIR as T, writeFileContent as Tn, getSourceTransport as Tt, CLAUDECODE_SKILLS_DIR_PATH as U, RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH as Un, assertPathResolvesInsideRoot as Ut, CLAUDECODE_MEMORIES_DIR_NAME as V, RULESYNC_CONFIG_SCHEMA_URL as Vn, assertLandingOutsideVcsMetadata as Vt, findProjectInstructionBudgetFindings as W, RULESYNC_HOOKS_RELATIVE_FILE_PATH as Wn, assertTreeContainsNoSymlinks as Wt, RulesyncSubagentFrontmatterSchema as X, RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH as Xn, fileExists as Xt, RulesyncSubagent as Y, RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH as Yn, ensureDir as Yt, RulesyncSkill as Z, RULESYNC_PERMISSIONS_SCHEMA_URL as Zn, fileExistsStrict as Zt, SkillsProcessor as _, removeFileWithoutFollowingSymlinks as _n, mergeInputRootConfigs as _t, convertFromTool as a, listDirectoryEntryNames as an, formatMegabytes as ar, getRulesyncSourceCandidates as at, REASONIX_LOCAL_RULE_FILE_NAME as b, resolvedRelativePath as bn, CONFLICTING_TARGET_PAIRS as bt, ELLIPSIS_WIDTH as c, normalizePosixDirPath as cn, hasEnclosingMarkOutsideKeycap as cr, RulesyncCommandFrontmatterSchema as ct, McpProcessor as d, readFileContent as dn, stripControlCharactersKeepingLineFeeds as dr, stringifyFrontmatter as dt, getHomeDirectory as en, RULESYNC_SKILLS_RELATIVE_DIR_PATH as er, RulesyncRuleFrontmatterSchema as et, IgnoreProcessor as f, readFileContentOrNull as fn, stripControlCharactersKeepingLineFeedsAndTabs as fr, loadYaml as ft, SubagentsProcessor as g, removeFileStrict as gn, ConfigResolver as gt, RulesProcessor as h, removeFile as hn, SKILL_FILE_NAME as ht, inspectInputRoots as i, isSymlink as in, RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME as ir, RulesyncHooks as it, AUGMENTCODE_DIR as j, ALL_FEATURES as jn, warnOnConflictingFlags as jt, CODEBUDDY_DIR as k, PACKAGING_TOOL_TARGETS as kn, WarningCollectingLogger as kt, displayWidthOf as l, pathEscapesRoot as ln, quoteForLog as lr, RulesyncCheck as lt, ChecksProcessor as m, removeDirectoryStrict as mn, SHARED_USER_MANAGED_CONFIG_PATHS as mt, formatSourceLoadFailure as n, isFileSystemError as nn, RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH as nr, RulesyncMcp as nt, getProcessorRegistryEntry as o, listFilePathsRecursively as on, formatError as or, resolveRulesyncSourceWritePath as ot, HooksProcessor as p, removeDirectory as pn, stripHiddenCharacters as pr, isRecord as pt, hasWindowsFoldableName as q, RULESYNC_MCP_RELATIVE_FILE_PATH as qn, createTempDirectory as qt, generate as r, isRootDirPath as rn, RULESYNC_USER_CONFIG_DIR_NAME as rr, RulesyncIgnore as rt, parseCommaSeparatedList as s, listSubdirectoryNames as sn, truncateText as sr, RulesyncCommand as st, importFromTool as t, isFileNotFoundError as tn, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH as tr, RulesyncPermissions as tt, shortenToWidth as u, posixRelativePathEscapesRoot as un, stripControlCharacters as ur, RulesyncCheckFrontmatterSchema as ut, CRUSH_LOCAL_RULE_FILE_NAME as v, removeTempDirectory as vn, parseConfigFileContent as vt, LETTACODE_SETTINGS_LOCAL_FILE_NAME as w, writeFileBuffer as wn, assertTargetsFeaturesExclusive as wt, QWENCODE_DIR as x, runWithDirectoryRollback as xn, ConfigFileSchema as xt, CommandsProcessor as y, resolvePath as yn, resolveEffectiveInputRoots as yt, CLAUDECODE_DIR as z, RULESYNC_COMMANDS_RELATIVE_DIR_PATH as zn, applyFileMode as zt };
105998
107133
 
105999
- //# sourceMappingURL=import-C8KKmzZS.js.map
107134
+ //# sourceMappingURL=import-fiaj0fDK.js.map