rulesync 43.13.0 → 43.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -381,36 +381,36 @@ function formatError(error) {
381
381
  return boundErrorMessage(String(error));
382
382
  }
383
383
  // src/constants/rulesync-paths.ts
384
- const { join: join$359 } = node_path.posix;
384
+ const { join: join$363 } = node_path.posix;
385
385
  const RULESYNC_CONFIG_RELATIVE_FILE_PATH = "rulesync.jsonc";
386
386
  const RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH = "rulesync.local.jsonc";
387
387
  const RULESYNC_USER_CONFIG_DIR_NAME = "rulesync";
388
388
  const RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME = ".config";
389
389
  const RULESYNC_RELATIVE_DIR_PATH = ".rulesync";
390
390
  const RULES_FEATURE_SUBDIR = "rules";
391
- const CURATED_RULES_FEATURE_SUBDIR = join$359(RULES_FEATURE_SUBDIR, ".curated");
391
+ const CURATED_RULES_FEATURE_SUBDIR = join$363(RULES_FEATURE_SUBDIR, ".curated");
392
392
  const COMMANDS_FEATURE_SUBDIR = "commands";
393
393
  const SUBAGENTS_FEATURE_SUBDIR = "subagents";
394
394
  const CHECKS_FEATURE_SUBDIR = "checks";
395
395
  const SKILLS_FEATURE_SUBDIR = "skills";
396
- const CURATED_SKILLS_FEATURE_SUBDIR = join$359(SKILLS_FEATURE_SUBDIR, ".curated");
397
- const RULESYNC_RULES_RELATIVE_DIR_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, RULES_FEATURE_SUBDIR);
398
- const RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, CURATED_RULES_FEATURE_SUBDIR);
399
- const RULESYNC_COMMANDS_RELATIVE_DIR_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, COMMANDS_FEATURE_SUBDIR);
400
- const RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, SUBAGENTS_FEATURE_SUBDIR);
401
- const RULESYNC_CHECKS_RELATIVE_DIR_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, CHECKS_FEATURE_SUBDIR);
402
- const RULESYNC_MCP_RELATIVE_FILE_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, "mcp.jsonc");
403
- const RULESYNC_HOOKS_RELATIVE_FILE_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, "hooks.jsonc");
404
- const RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, "permissions.jsonc");
405
- join$359(RULESYNC_RELATIVE_DIR_PATH, "mcp.json");
406
- const RULESYNC_HOOKS_LEGACY_RELATIVE_FILE_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, "hooks.json");
407
- const RULESYNC_PERMISSIONS_LEGACY_RELATIVE_FILE_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, "permissions.json");
396
+ const CURATED_SKILLS_FEATURE_SUBDIR = join$363(SKILLS_FEATURE_SUBDIR, ".curated");
397
+ const RULESYNC_RULES_RELATIVE_DIR_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, RULES_FEATURE_SUBDIR);
398
+ const RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, CURATED_RULES_FEATURE_SUBDIR);
399
+ const RULESYNC_COMMANDS_RELATIVE_DIR_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, COMMANDS_FEATURE_SUBDIR);
400
+ const RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, SUBAGENTS_FEATURE_SUBDIR);
401
+ const RULESYNC_CHECKS_RELATIVE_DIR_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, CHECKS_FEATURE_SUBDIR);
402
+ const RULESYNC_MCP_RELATIVE_FILE_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, "mcp.jsonc");
403
+ const RULESYNC_HOOKS_RELATIVE_FILE_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, "hooks.jsonc");
404
+ const RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, "permissions.jsonc");
405
+ join$363(RULESYNC_RELATIVE_DIR_PATH, "mcp.json");
406
+ const RULESYNC_HOOKS_LEGACY_RELATIVE_FILE_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, "hooks.json");
407
+ const RULESYNC_PERMISSIONS_LEGACY_RELATIVE_FILE_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, "permissions.json");
408
408
  const RULESYNC_AIIGNORE_FILE_NAME = ".aiignore";
409
- const RULESYNC_AIIGNORE_RELATIVE_FILE_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, ".aiignore");
409
+ const RULESYNC_AIIGNORE_RELATIVE_FILE_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, ".aiignore");
410
410
  const RULESYNC_IGNORE_RELATIVE_FILE_PATH = ".rulesyncignore";
411
411
  const RULESYNC_OVERVIEW_FILE_NAME = "overview.md";
412
- const RULESYNC_SKILLS_RELATIVE_DIR_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, SKILLS_FEATURE_SUBDIR);
413
- const RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH = join$359(RULESYNC_RELATIVE_DIR_PATH, CURATED_SKILLS_FEATURE_SUBDIR);
412
+ const RULESYNC_SKILLS_RELATIVE_DIR_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, SKILLS_FEATURE_SUBDIR);
413
+ const RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH = join$363(RULESYNC_RELATIVE_DIR_PATH, CURATED_SKILLS_FEATURE_SUBDIR);
414
414
  const RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH = "rulesync.lock";
415
415
  const RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH = "rulesync-npm.lock.json";
416
416
  const RULESYNC_MCP_FILE_NAME = "mcp.jsonc";
@@ -767,6 +767,7 @@ const subagentsProcessorToolTargetTuple = [
767
767
  "omp",
768
768
  "opencode",
769
769
  "opencodev1",
770
+ "openbitfun",
770
771
  "pool",
771
772
  "qoder",
772
773
  "qwencode",
@@ -827,6 +828,7 @@ const skillsProcessorToolTargetTuple = [
827
828
  "omp",
828
829
  "opencode",
829
830
  "opencodev1",
831
+ "openbitfun",
830
832
  "pi",
831
833
  "pool",
832
834
  "qoder",
@@ -875,6 +877,7 @@ const hooksProcessorToolTargetTuple = [
875
877
  "omp",
876
878
  "opencode",
877
879
  "opencodev1",
880
+ "openbitfun",
878
881
  "pi",
879
882
  "pool",
880
883
  "factorydroid",
@@ -925,6 +928,7 @@ const permissionsProcessorToolTargetTuple = [
925
928
  "deepagents",
926
929
  "devin",
927
930
  "factorydroid",
931
+ "gitlabduo",
928
932
  "goose",
929
933
  "grokcli",
930
934
  "hermesagent",
@@ -5584,20 +5588,57 @@ const CANONICAL_TO_BOB_EVENT_NAMES = {
5584
5588
  stop: "Stop"
5585
5589
  };
5586
5590
  /**
5587
- * Hook events supported by IBM Bob's lifecycle hooks.
5591
+ * Hook events rulesync emits for IBM Bob from the shared `hooks` block.
5588
5592
  *
5589
5593
  * Bob reads `hooks` from `.bob/settings.json` (project) and
5590
5594
  * `~/.bob/settings/settings.json` (user) in the Claude-Code shape and fires
5591
- * seven events: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse,
5592
- * PreCompact, PostCompact and Stop (Bob IDE and Bob Shell list the same
5593
- * seven). Handlers are `command` or `http` hooks. `matcher` is a regex matched
5594
- * against the tool name on PreToolUse / PostToolUse, `source` on SessionStart
5595
- * and `trigger` on PreCompact / PostCompact; the other events ignore it.
5595
+ * seven documented events: SessionStart, UserPromptSubmit, PreToolUse,
5596
+ * PostToolUse, PreCompact, PostCompact and Stop (Bob IDE and Bob Shell list
5597
+ * the same seven). Handlers are `command` or `http` hooks. Bob Shell 2.1.0
5598
+ * adds more events; see {@link BOB_OPT_IN_HOOK_EVENTS} for why they are not
5599
+ * emitted from the shared block.
5596
5600
  *
5597
5601
  * @see https://bob.ibm.com/docs/shell/configuration/lifecycle-hooks
5598
5602
  * @see https://bob.ibm.com/docs/ide/configuration/lifecycle-hooks
5599
5603
  */
5600
5604
  const BOB_HOOK_EVENTS = eventsOf(CANONICAL_TO_BOB_EVENT_NAMES);
5605
+ /**
5606
+ * The {@link BOB_HOOK_EVENTS} whose `matcher` regex Bob applies: the tool name
5607
+ * on PreToolUse / PostToolUse, `source` on SessionStart and `trigger` on
5608
+ * PreCompact / PostCompact. UserPromptSubmit and Stop have no matchable value.
5609
+ */
5610
+ const BOB_MATCHER_HOOK_EVENTS = BOB_HOOK_EVENTS.filter((event) => event !== "beforeSubmitPrompt" && event !== "stop");
5611
+ /**
5612
+ * Canonical events that Bob Shell 2.1.0 (`@ibm/bob` on npm, 2026-11-09) can
5613
+ * fire under the native name given here, next to the override-only
5614
+ * `PermissionResolved`. They are not on the lifecycle-hooks pages yet.
5615
+ *
5616
+ * They are deliberately not emitted from the shared `hooks` block: Bob Shell
5617
+ * before 2.1.0 validates the `hooks` object strictly against the seven
5618
+ * documented keys, and on any unknown key it ignores that settings file's
5619
+ * whole `hooks` block (PreToolUse guards included). Writing them must
5620
+ * therefore be an explicit opt-in under the `bob.hooks` override block, by
5621
+ * their native name, which is emitted verbatim and imported back there.
5622
+ *
5623
+ * @see https://registry.npmjs.org/@ibm/bob/-/bob-2.1.0.tgz
5624
+ */
5625
+ const BOB_OPT_IN_HOOK_EVENTS = {
5626
+ sessionEnd: "SessionEnd",
5627
+ permissionRequest: "PermissionRequest",
5628
+ notification: "Notification"
5629
+ };
5630
+ /**
5631
+ * Every native event key Bob Shell 2.1.0's strict hooks schema accepts: the
5632
+ * seven documented events, the three opt-in ones and `PermissionResolved`,
5633
+ * which has no canonical counterpart. Any other key under `bob.hooks` is
5634
+ * dropped on generate, because one unknown key makes Bob ignore the file's
5635
+ * whole hooks block.
5636
+ */
5637
+ const BOB_NATIVE_HOOK_EVENTS = [
5638
+ ...Object.values(CANONICAL_TO_BOB_EVENT_NAMES),
5639
+ ...Object.values(BOB_OPT_IN_HOOK_EVENTS),
5640
+ "PermissionResolved"
5641
+ ];
5601
5642
  const BOB_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_BOB_EVENT_NAMES);
5602
5643
  const CANONICAL_TO_TABNINE_EVENT_NAMES = {
5603
5644
  sessionStart: "SessionStart",
@@ -5880,17 +5921,18 @@ const CONTINUE_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_CONTINUE_EVE
5880
5921
  * observers, `gateway_platform_event` and `transform_api_error_classification`.
5881
5922
  * Shell hooks are gated on the same set.
5882
5923
  *
5883
- * Verified against the tag `v0.23.2`: `VALID_HOOKS` holds 48 entries, grown
5924
+ * Verified against the tag `v0.23.4`: `VALID_HOOKS` holds 50 entries, grown
5884
5925
  * from 23 at `v2026.8.3` (v0.20.0) and 37 at `v2026.8.16` (v0.20.2) — v0.21
5885
5926
  * added `agent_loop_stopped` and `on_room_member_activity`, v0.21.5 added
5886
5927
  * `pre_auxiliary_call` and `post_auxiliary_call`, v0.21.6 added
5887
5928
  * `post_gateway_admission`, `on_human_input_request` and
5888
5929
  * `on_human_input_resolved`, v0.22.3 added `on_session_delete` and
5889
- * `post_compaction`, and v0.23.1 added `on_session_open` and
5890
- * `post_curator_run`. This list holds 47 of them — see
5930
+ * `post_compaction`, v0.23.1 added `on_session_open` and
5931
+ * `post_curator_run`, and v0.23.4 added `on_session_prompt` and
5932
+ * `on_session_prompt_settled`. This list holds 49 of them — see
5891
5933
  * {@link HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS} for the exclusion.
5892
5934
  *
5893
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py
5935
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/hermes_cli/plugins.py
5894
5936
  */
5895
5937
  const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5896
5938
  "pre_tool_call",
@@ -5916,6 +5958,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5916
5958
  "on_session_reset",
5917
5959
  "on_session_delete",
5918
5960
  "on_session_open",
5961
+ "on_session_prompt",
5962
+ "on_session_prompt_settled",
5919
5963
  "on_skill_lifecycle",
5920
5964
  "subagent_start",
5921
5965
  "subagent_stop",
@@ -5951,8 +5995,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5951
5995
  * rulesync only ever writes shell hooks, so these are excluded from
5952
5996
  * {@link HERMESAGENT_NATIVE_HOOK_EVENTS} and warned about with their own message.
5953
5997
  *
5954
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5955
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/agent/shell_hooks.py — `_parse_hooks_block`
5998
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5999
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/agent/shell_hooks.py — `_parse_hooks_block`
5956
6000
  */
5957
6001
  const HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS = ["transform_api_error_classification"];
5958
6002
  /**
@@ -5972,8 +6016,8 @@ const CANONICAL_TO_HERMESAGENT_EVENT_NAMES = {
5972
6016
  /**
5973
6017
  * Hook events supported by Hermes Agent's native Shell Hooks system.
5974
6018
  *
5975
- * Hermes validates hook events against a fixed `VALID_HOOKS` set — 48 entries as
5976
- * of v0.23.2 (tag `v0.23.2`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
6019
+ * Hermes validates hook events against a fixed `VALID_HOOKS` set — 50 entries as
6020
+ * of v0.23.4 (tag `v0.23.4`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
5977
6021
  * full list. Only the events with a clean 1:1 canonical equivalent are mapped
5978
6022
  * here. All other native events round-trip through `hermesagent.hooks`.
5979
6023
  * @see https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/hooks.md
@@ -6023,6 +6067,7 @@ const HooksConfigSchema = zod_mini.z.looseObject({
6023
6067
  amp: zod_mini.z.optional(zod_mini.z.looseObject({ hooks: zod_mini.z.optional(hooksRecordSchema) })),
6024
6068
  factorydroid: zod_mini.z.optional(zod_mini.z.looseObject({ hooks: zod_mini.z.optional(hooksRecordSchema) })),
6025
6069
  codexcli: zod_mini.z.optional(zod_mini.z.looseObject({ hooks: zod_mini.z.optional(hooksRecordSchema) })),
6070
+ openbitfun: zod_mini.z.optional(zod_mini.z.looseObject({ hooks: zod_mini.z.optional(hooksRecordSchema) })),
6026
6071
  goose: zod_mini.z.optional(zod_mini.z.looseObject({ hooks: zod_mini.z.optional(hooksRecordSchema) })),
6027
6072
  deepagents: zod_mini.z.optional(zod_mini.z.looseObject({ hooks: zod_mini.z.optional(hooksRecordSchema) })),
6028
6073
  kiro: zod_mini.z.optional(zod_mini.z.looseObject({ hooks: zod_mini.z.optional(hooksRecordSchema) })),
@@ -6599,6 +6644,32 @@ const CODEXCLI_HOOK_EVENTS = eventsOf(CANONICAL_TO_CODEXCLI_EVENT_NAMES);
6599
6644
  */
6600
6645
  const CODEXCLI_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_CODEXCLI_EVENT_NAMES);
6601
6646
  /**
6647
+ * Map canonical camelCase event names to OpenBitFun PascalCase. OpenBitFun
6648
+ * implements the Codex hook contract with Codex's event names, minus the
6649
+ * events it does not dispatch (`Interrupt`, `PreModelRequest`,
6650
+ * `PostModelRequest`).
6651
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/docs/features/agent-hooks.md
6652
+ */
6653
+ const CANONICAL_TO_OPENBITFUN_EVENT_NAMES = {
6654
+ sessionStart: "SessionStart",
6655
+ sessionEnd: "SessionEnd",
6656
+ preToolUse: "PreToolUse",
6657
+ postToolUse: "PostToolUse",
6658
+ beforeSubmitPrompt: "UserPromptSubmit",
6659
+ stop: "Stop",
6660
+ permissionRequest: "PermissionRequest",
6661
+ subagentStart: "SubagentStart",
6662
+ subagentStop: "SubagentStop",
6663
+ preCompact: "PreCompact",
6664
+ postCompact: "PostCompact"
6665
+ };
6666
+ /** Hook events supported by OpenBitFun. */
6667
+ const OPENBITFUN_HOOK_EVENTS = eventsOf(CANONICAL_TO_OPENBITFUN_EVENT_NAMES);
6668
+ /**
6669
+ * Map OpenBitFun PascalCase event names to canonical camelCase.
6670
+ */
6671
+ const OPENBITFUN_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_OPENBITFUN_EVENT_NAMES);
6672
+ /**
6602
6673
  * Map canonical camelCase event names to Goose PascalCase.
6603
6674
  */
6604
6675
  const CANONICAL_TO_GOOSE_EVENT_NAMES = {
@@ -9790,6 +9861,7 @@ const PermissionsConfigSchema = zod_mini.z.looseObject({
9790
9861
  commandcode: zod_mini.z.optional(CommandcodePermissionsOverrideSchema),
9791
9862
  lettacode: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9792
9863
  crush: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9864
+ gitlabduo: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9793
9865
  goose: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9794
9866
  omp: zod_mini.z.optional(OmpPermissionsOverrideSchema),
9795
9867
  pool: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
@@ -18299,6 +18371,14 @@ const GITLABDUO_DIR = (0, node_path.join)(".gitlab", "duo");
18299
18371
  const GITLABDUO_RULE_FILE_NAME = "chat-rules.md";
18300
18372
  /** MCP servers. @see https://docs.gitlab.com/user/gitlab_duo/model_context_protocol/mcp_clients/ */
18301
18373
  const GITLABDUO_MCP_FILE_NAME = "mcp.json";
18374
+ /**
18375
+ * Settings. Only the user file `~/.gitlab/duo/settings.json` carries the
18376
+ * `permissions` setting rulesync writes; the project files are deliberately not
18377
+ * read for it.
18378
+ *
18379
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/definitions.ts
18380
+ */
18381
+ const GITLABDUO_SETTINGS_FILE_NAME = "settings.json";
18302
18382
  /** Lifecycle hooks (experiment). @see https://docs.gitlab.com/user/gitlab_duo_cli/customize/ */
18303
18383
  const GITLABDUO_HOOKS_FILE_NAME = "hooks.json";
18304
18384
  /** Merge request review instructions. @see https://docs.gitlab.com/user/project/merge_requests/duo_in_merge_requests/ */
@@ -28093,6 +28173,135 @@ var PiSkill = class extends ToolSkill {
28093
28173
  var OmpSkill = class extends PiSkill {
28094
28174
  static layout = OMP_LAYOUT;
28095
28175
  };
28176
+ // src/constants/openbitfun-paths.ts
28177
+ /**
28178
+ * OpenBitFun configuration-layout conventions.
28179
+ *
28180
+ * OpenBitFun (formerly BitFun) keeps its project assets under a `.openbitfun/`
28181
+ * directory at the project root and its user assets under an OS-dependent
28182
+ * user root. Rules are not written here: OpenBitFun already reads the shared
28183
+ * `AGENTS.md` / `CLAUDE.md` / `.claude/rules/` files the `agentsmd` and
28184
+ * `claudecode` targets write.
28185
+ *
28186
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs
28187
+ */
28188
+ const OPENBITFUN_DIR = ".openbitfun";
28189
+ const OPENBITFUN_AGENTS_DIR_NAME = "agents";
28190
+ const OPENBITFUN_AGENTS_DIR_PATH = (0, node_path.join)(OPENBITFUN_DIR, OPENBITFUN_AGENTS_DIR_NAME);
28191
+ const OPENBITFUN_SKILLS_DIR_NAME = "skills";
28192
+ const OPENBITFUN_SKILLS_DIR_PATH = (0, node_path.join)(OPENBITFUN_DIR, OPENBITFUN_SKILLS_DIR_NAME);
28193
+ const OPENBITFUN_CONFIG_DIR_NAME = "config";
28194
+ const OPENBITFUN_CONFIG_DIR_PATH = (0, node_path.join)(OPENBITFUN_DIR, OPENBITFUN_CONFIG_DIR_NAME);
28195
+ const OPENBITFUN_HOOKS_FILE_NAME = "hooks.json";
28196
+ const OPENBITFUN_DATA_NAMESPACE = "openbitfun";
28197
+ /**
28198
+ * OpenBitFun's user root (`dirs::config_dir()/openbitfun`), relative to the
28199
+ * home directory (the processor resolves the home directory through
28200
+ * `outputRoot`).
28201
+ *
28202
+ * - macOS: `~/Library/Application Support/openbitfun`
28203
+ * - Windows: `%APPDATA%\openbitfun` (`~/AppData/Roaming/openbitfun`)
28204
+ * - Linux and others: `~/.config/openbitfun`
28205
+ *
28206
+ * `$XDG_CONFIG_HOME` and OpenBitFun's `OPENBITFUN_USER_ROOT` override are not
28207
+ * followed; the default locations are assumed (a non-default `$XDG_CONFIG_HOME`
28208
+ * is warned about, see `warnOpenbitfunXdgOverride`).
28209
+ */
28210
+ function openbitfunGlobalRootDir() {
28211
+ switch (process.platform) {
28212
+ case "darwin": return (0, node_path.join)("Library", "Application Support", OPENBITFUN_DATA_NAMESPACE);
28213
+ case "win32": return (0, node_path.join)("AppData", "Roaming", OPENBITFUN_DATA_NAMESPACE);
28214
+ default: return (0, node_path.join)(".config", OPENBITFUN_DATA_NAMESPACE);
28215
+ }
28216
+ }
28217
+ /**
28218
+ * OpenBitFun's user agents directory: `<user root>/agents`.
28219
+ */
28220
+ function openbitfunGlobalAgentsDir() {
28221
+ return (0, node_path.join)(openbitfunGlobalRootDir(), OPENBITFUN_AGENTS_DIR_NAME);
28222
+ }
28223
+ /**
28224
+ * OpenBitFun's user hooks directory: `<user root>/config` (holding `hooks.json`).
28225
+ */
28226
+ function openbitfunGlobalConfigDir() {
28227
+ return (0, node_path.join)(openbitfunGlobalRootDir(), OPENBITFUN_CONFIG_DIR_NAME);
28228
+ }
28229
+ /**
28230
+ * OpenBitFun's user skills directory (`user_skills_dir` in `path_manager.rs`).
28231
+ * It is not always under the user root: on Linux it lives in the data dir
28232
+ * (`dirs::data_local_dir()`), not the config dir.
28233
+ *
28234
+ * - macOS: `~/Library/Application Support/openbitfun/skills`
28235
+ * - Windows: `%APPDATA%\openbitfun\skills`
28236
+ * - Linux and others: `~/.local/share/openbitfun/skills`
28237
+ *
28238
+ * `$XDG_DATA_HOME` is not followed; the default location is assumed (a
28239
+ * non-default value is warned about, see `warnOpenbitfunXdgOverride`).
28240
+ */
28241
+ function openbitfunGlobalSkillsDir() {
28242
+ switch (process.platform) {
28243
+ case "darwin":
28244
+ case "win32": return (0, node_path.join)(openbitfunGlobalRootDir(), OPENBITFUN_SKILLS_DIR_NAME);
28245
+ default: return (0, node_path.join)(".local", "share", OPENBITFUN_DATA_NAMESPACE, OPENBITFUN_SKILLS_DIR_NAME);
28246
+ }
28247
+ }
28248
+ // src/utils/openbitfun.ts
28249
+ const XDG_OVERRIDES = {
28250
+ config: {
28251
+ envVar: "XDG_CONFIG_HOME",
28252
+ defaultDir: ".config"
28253
+ },
28254
+ data: {
28255
+ envVar: "XDG_DATA_HOME",
28256
+ defaultDir: (0, node_path.join)(".local", "share")
28257
+ }
28258
+ };
28259
+ /**
28260
+ * Warn, once per run, when an XDG base directory variable moves OpenBitFun's
28261
+ * user tree away from where rulesync writes it in global mode.
28262
+ *
28263
+ * On Linux OpenBitFun resolves its user root through the `dirs` crate
28264
+ * (`dirs::config_dir()`, and `dirs::data_local_dir()` for skills), which
28265
+ * follows `$XDG_CONFIG_HOME` / `$XDG_DATA_HOME` when set to an absolute path.
28266
+ * rulesync writes global files relative to the home directory, at the XDG
28267
+ * default location, so a non-default value means OpenBitFun reads elsewhere.
28268
+ * macOS and Windows do not use these variables.
28269
+ *
28270
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs
28271
+ */
28272
+ function warnOpenbitfunXdgOverride({ kind, logger }) {
28273
+ if (process.platform === "darwin" || process.platform === "win32") return;
28274
+ const { envVar, defaultDir } = XDG_OVERRIDES[kind];
28275
+ const value = process.env[envVar]?.trim();
28276
+ if (!value || !(0, node_path.isAbsolute)(value)) return;
28277
+ const defaultPath = (0, node_path.join)(getHomeDirectory(), defaultDir);
28278
+ if ((0, node_path.resolve)(value) === (0, node_path.resolve)(defaultPath)) return;
28279
+ warnOnceWithFallback(logger, `$${envVar} is set to ${value}, so OpenBitFun reads its user files from ${(0, node_path.join)(value, "openbitfun")}, but rulesync writes OpenBitFun's global files under ${(0, node_path.join)("~", defaultDir, "openbitfun")}. Move them there or unset $${envVar} for OpenBitFun.`);
28280
+ }
28281
+ // src/features/skills/openbitfun-skill.ts
28282
+ /**
28283
+ * OpenBitFun skills follow the Agent Skills layout (`<name>/SKILL.md` with
28284
+ * `name` and `description` frontmatter, plus optional supporting files), so
28285
+ * this target reuses {@link AgentsSkillsSkill} with OpenBitFun's locations:
28286
+ * `.openbitfun/skills/` (project) and the OS-dependent user skills directory
28287
+ * (global, see {@link openbitfunGlobalSkillsDir}). A project skill shadows a
28288
+ * user skill of the same name.
28289
+ *
28290
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/docs/interactive-capabilities/capabilities/feature.skills.md
28291
+ */
28292
+ var OpenbitfunSkill = class extends AgentsSkillsSkill {
28293
+ static getSettablePaths({ global = false } = {}) {
28294
+ return { relativeDirPath: global ? openbitfunGlobalSkillsDir() : OPENBITFUN_SKILLS_DIR_PATH };
28295
+ }
28296
+ static fromRulesyncSkill(params) {
28297
+ if (params.global) warnOpenbitfunXdgOverride({
28298
+ kind: "data",
28299
+ logger: params.logger
28300
+ });
28301
+ return super.fromRulesyncSkill(params);
28302
+ }
28303
+ static toolTarget = "openbitfun";
28304
+ };
28096
28305
  // src/constants/openclaw-paths.ts
28097
28306
  const OPENCLAW_WORKSPACE_DIR_PATH = (0, node_path.join)(".openclaw", "workspace");
28098
28307
  const OPENCLAW_RULE_FILE_NAME = "AGENTS.md";
@@ -30220,6 +30429,14 @@ const toolSkillFactories = /* @__PURE__ */ new Map([
30220
30429
  supportsGlobal: true
30221
30430
  }
30222
30431
  }],
30432
+ ["openbitfun", {
30433
+ class: OpenbitfunSkill,
30434
+ meta: {
30435
+ supportsProject: true,
30436
+ supportsSimulated: false,
30437
+ supportsGlobal: true
30438
+ }
30439
+ }],
30223
30440
  ["xum", {
30224
30441
  class: XumSkill,
30225
30442
  meta: {
@@ -36038,6 +36255,162 @@ var OmpSubagent = class extends FrontmatterMarkdownToolSubagent {
36038
36255
  };
36039
36256
  }
36040
36257
  };
36258
+ // src/features/subagents/openbitfun-subagent.ts
36259
+ /**
36260
+ * The `kind` rulesync writes: a delegated subagent rather than a top-level
36261
+ * agent mode. It is also OpenBitFun's default when `kind` is omitted.
36262
+ */
36263
+ const OPENBITFUN_SUBAGENT_KIND = "subagent";
36264
+ /**
36265
+ * Frontmatter of an OpenBitFun custom agent. `name` and `description` are
36266
+ * required; `tools` is a list or a comma-separated string. Unknown keys are
36267
+ * kept (looseObject), and OpenBitFun itself ignores keys it does not know.
36268
+ *
36269
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/src/crates/execution/agent-runtime/src/custom_agent.rs
36270
+ */
36271
+ const OpenbitfunSubagentFrontmatterSchema = zod_mini.z.looseObject({
36272
+ name: zod_mini.z.string(),
36273
+ description: zod_mini.z.string(),
36274
+ kind: zod_mini.z.optional(zod_mini.z.enum(["mode", "subagent"])),
36275
+ tools: zod_mini.z.optional(zod_mini.z.union([zod_mini.z.string(), zod_mini.z.array(zod_mini.z.string())])),
36276
+ model: zod_mini.z.optional(zod_mini.z.string()),
36277
+ readonly: zod_mini.z.optional(zod_mini.z.boolean()),
36278
+ review: zod_mini.z.optional(zod_mini.z.boolean())
36279
+ });
36280
+ /**
36281
+ * Subagent generator for OpenBitFun.
36282
+ *
36283
+ * OpenBitFun reads custom agents — Markdown with YAML frontmatter, the body
36284
+ * being the prompt — from `.openbitfun/agents/` (project) and
36285
+ * `<user root>/agents/` (user; see {@link openbitfunGlobalAgentsDir}).
36286
+ *
36287
+ * rulesync writes `name`, `description` and `kind: subagent`, then spreads the
36288
+ * `openbitfun` section (`kind`, `tools`, `model`, `readonly`, `review`, `id`,
36289
+ * `user_context_policy`, ...) on top, so a value set there wins. OpenBitFun
36290
+ * requires `description`, so an absent one is written as an empty string.
36291
+ *
36292
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/src/crates/execution/agent-runtime/src/custom_agent.rs
36293
+ */
36294
+ var OpenbitfunSubagent = class OpenbitfunSubagent extends ToolSubagent {
36295
+ frontmatter;
36296
+ body;
36297
+ constructor({ frontmatter, body, ...rest }) {
36298
+ if (rest.validate !== false) {
36299
+ const result = OpenbitfunSubagentFrontmatterSchema.safeParse(frontmatter);
36300
+ if (!result.success) throw new Error(`Invalid frontmatter in ${(0, node_path.join)(rest.relativeDirPath, rest.relativeFilePath)}: ${formatError(result.error)}`);
36301
+ }
36302
+ super({ ...rest });
36303
+ this.frontmatter = frontmatter;
36304
+ this.body = body;
36305
+ }
36306
+ static getSettablePaths({ global = false } = {}) {
36307
+ return { relativeDirPath: global ? openbitfunGlobalAgentsDir() : OPENBITFUN_AGENTS_DIR_PATH };
36308
+ }
36309
+ getFrontmatter() {
36310
+ return this.frontmatter;
36311
+ }
36312
+ getBody() {
36313
+ return this.body;
36314
+ }
36315
+ toRulesyncSubagent() {
36316
+ const { name, description, kind, ...restFields } = this.frontmatter;
36317
+ const openbitfunSection = {
36318
+ ...kind !== void 0 && kind !== OPENBITFUN_SUBAGENT_KIND && { kind },
36319
+ ...restFields
36320
+ };
36321
+ return new RulesyncSubagent({
36322
+ outputRoot: ".",
36323
+ frontmatter: {
36324
+ targets: ["*"],
36325
+ name,
36326
+ ...description && { description },
36327
+ ...Object.keys(openbitfunSection).length > 0 && { openbitfun: openbitfunSection }
36328
+ },
36329
+ body: this.body,
36330
+ relativeDirPath: RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH,
36331
+ relativeFilePath: this.getRelativeFilePath(),
36332
+ validate: true
36333
+ });
36334
+ }
36335
+ static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false, logger }) {
36336
+ if (global) warnOpenbitfunXdgOverride({
36337
+ kind: "config",
36338
+ logger
36339
+ });
36340
+ const rulesyncFrontmatter = rulesyncSubagent.getFrontmatter();
36341
+ const openbitfunSection = this.filterToolSpecificSection(rulesyncFrontmatter.openbitfun ?? {}, ["name", "description"]);
36342
+ const openbitfunFrontmatter = parseGeneratedSubagentFrontmatter({
36343
+ schema: OpenbitfunSubagentFrontmatterSchema,
36344
+ frontmatter: {
36345
+ name: rulesyncFrontmatter.name,
36346
+ description: rulesyncFrontmatter.description ?? "",
36347
+ kind: OPENBITFUN_SUBAGENT_KIND,
36348
+ ...openbitfunSection
36349
+ },
36350
+ toolTarget: "openbitfun",
36351
+ rulesyncSubagent
36352
+ });
36353
+ const body = rulesyncSubagent.getBody();
36354
+ return new OpenbitfunSubagent({
36355
+ outputRoot,
36356
+ frontmatter: openbitfunFrontmatter,
36357
+ body,
36358
+ relativeDirPath: this.getSettablePaths({ global }).relativeDirPath,
36359
+ relativeFilePath: rulesyncSubagent.getRelativeFilePath(),
36360
+ fileContent: stringifyFrontmatter(body, openbitfunFrontmatter),
36361
+ validate
36362
+ });
36363
+ }
36364
+ validate() {
36365
+ if (!this.frontmatter) return {
36366
+ success: true,
36367
+ error: null
36368
+ };
36369
+ return validateFrontmatterSchema({
36370
+ schema: OpenbitfunSubagentFrontmatterSchema,
36371
+ frontmatter: this.frontmatter,
36372
+ relativeDirPath: this.relativeDirPath,
36373
+ relativeFilePath: this.relativeFilePath
36374
+ });
36375
+ }
36376
+ static isTargetedByRulesyncSubagent(rulesyncSubagent) {
36377
+ return this.isTargetedByRulesyncSubagentDefault({
36378
+ rulesyncSubagent,
36379
+ toolTarget: "openbitfun"
36380
+ });
36381
+ }
36382
+ static async fromFile({ outputRoot = process.cwd(), relativeFilePath, validate = true, global = false }) {
36383
+ const paths = this.getSettablePaths({ global });
36384
+ const filePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, relativeFilePath);
36385
+ const fileContent = await readFileContent(filePath);
36386
+ const { frontmatter, body } = parseFrontmatter(fileContent, filePath);
36387
+ const result = OpenbitfunSubagentFrontmatterSchema.safeParse(frontmatter);
36388
+ if (!result.success) throw new Error(`Invalid frontmatter in ${filePath}: ${formatError(result.error)}`);
36389
+ return new OpenbitfunSubagent({
36390
+ outputRoot,
36391
+ relativeDirPath: paths.relativeDirPath,
36392
+ relativeFilePath,
36393
+ frontmatter: result.data,
36394
+ body: body.trim(),
36395
+ fileContent,
36396
+ validate
36397
+ });
36398
+ }
36399
+ static forDeletion({ outputRoot = process.cwd(), relativeDirPath, relativeFilePath }) {
36400
+ return new OpenbitfunSubagent({
36401
+ outputRoot,
36402
+ relativeDirPath,
36403
+ relativeFilePath,
36404
+ frontmatter: {
36405
+ name: "",
36406
+ description: ""
36407
+ },
36408
+ body: "",
36409
+ fileContent: "",
36410
+ validate: false
36411
+ });
36412
+ }
36413
+ };
36041
36414
  // src/features/subagents/opencodev1-subagent.ts
36042
36415
  /**
36043
36416
  * Subagent generator for **OpenCode V1** (OpenCode 1.x), which reads the V1
@@ -37089,8 +37462,208 @@ const VIBE_PROMPTS_DIR_PATH = (0, node_path.join)(".vibe", "prompts");
37089
37462
  * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.3/vibe/core/agents/models.py
37090
37463
  */
37091
37464
  const VIBE_RESERVED_AGENT_NAME = "main";
37465
+ /**
37466
+ * The approval policies Vibe ships since v3.1.4. `AgentRegistry._discover`
37467
+ * never loads an agents-directory file named after one as an agent, whatever
37468
+ * its `agent_type`: from a project's `.vibe/agents/` the file is ignored with
37469
+ * an `approval_policy.project_override_ignored` config issue, and from
37470
+ * `~/.vibe/agents/` it redefines that approval policy for every session. Vibe
37471
+ * compares the file stem exactly (`agent.name in BUILTIN_APPROVAL_POLICIES`).
37472
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/registry.py
37473
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/models.py
37474
+ */
37475
+ const VIBE_APPROVAL_POLICY_NAMES = /* @__PURE__ */ new Set([
37476
+ "ask",
37477
+ "accept-edits",
37478
+ "smart-approve",
37479
+ "auto-approve"
37480
+ ]);
37481
+ function vibeAgentFileStem(relativeFilePath) {
37482
+ return (0, node_path.basename)(relativeFilePath).replace(/\.(md|toml)$/, "");
37483
+ }
37092
37484
  function isReservedVibeAgentFileName(relativeFilePath) {
37093
- return (0, node_path.basename)(relativeFilePath).replace(/\.(md|toml)$/, "").toLowerCase() === VIBE_RESERVED_AGENT_NAME;
37485
+ return vibeAgentFileStem(relativeFilePath).toLowerCase() === VIBE_RESERVED_AGENT_NAME;
37486
+ }
37487
+ function isVibeApprovalPolicyFileName(relativeFilePath) {
37488
+ return VIBE_APPROVAL_POLICY_NAMES.has(vibeAgentFileStem(relativeFilePath));
37489
+ }
37490
+ /**
37491
+ * The keys Vibe ignores on a custom `agent_type = "agent"` profile since
37492
+ * v3.1.4, listing each as a config issue: `_agent_settings` drops every
37493
+ * `VibeConfigSchema` field outside its `_AGENT_KEYS`, plus `safety` and
37494
+ * `approval_policy`, because what runs without asking belongs to the approval
37495
+ * policy, not to the agent. A key outside this list is kept, as Vibe keeps it:
37496
+ * an agent key passes, and an unknown key (a typo such as `disabled_tool`)
37497
+ * stays so Vibe can report it — or refuse it under `strict_config`.
37498
+ * Generated from the `VibeConfigSchema` fields of v3.1.5 minus `_AGENT_KEYS`.
37499
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/models.py
37500
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/config/vibe_schema.py
37501
+ */
37502
+ const VIBE_AGENT_IGNORED_KEYS = /* @__PURE__ */ new Set([
37503
+ "safety",
37504
+ "approval_policy",
37505
+ "catalog_model_aliases",
37506
+ "catalog_recommended_model",
37507
+ "catalog_default_model",
37508
+ "utility_models",
37509
+ "active_transcribe_model",
37510
+ "transcribe_providers",
37511
+ "transcribe_models",
37512
+ "active_tts_model",
37513
+ "tts_providers",
37514
+ "tts_models",
37515
+ "outside_workdir",
37516
+ "mcp_servers",
37517
+ "enable_connectors",
37518
+ "enable_mcp",
37519
+ "experimental_enable_document_library_connector",
37520
+ "experimental_enable_mistral_mcp_connector",
37521
+ "connectors",
37522
+ "agent_paths",
37523
+ "enabled_agents",
37524
+ "disabled_agents",
37525
+ "installed_agents",
37526
+ "default_agent",
37527
+ "default_approval_policy",
37528
+ "vibe_bot_max_approval_policy",
37529
+ "vibe_bot_local_tools",
37530
+ "vibe_bot_local_tool_max_bytes",
37531
+ "smart_approve_available",
37532
+ "enable_auto_approve",
37533
+ "enabled_plugins",
37534
+ "disabled_plugins",
37535
+ "experimental_enable_remote_plugins",
37536
+ "experimental_enable_registry_skills",
37537
+ "enable_model_catalog",
37538
+ "enable_builtin_models",
37539
+ "experimental_enable_storage_usage",
37540
+ "enable_pr_monitoring",
37541
+ "experimental_local_runtime_session_api",
37542
+ "experimental_target_runtime",
37543
+ "enable_otel",
37544
+ "otel_endpoint",
37545
+ "otel_redaction",
37546
+ "console_base_url",
37547
+ "theme",
37548
+ "applied_migrations",
37549
+ "disable_welcome_banner_animation",
37550
+ "disable_selection_animation",
37551
+ "cursor_blink",
37552
+ "vim_keybindings",
37553
+ "show_dangerous_directory_warning",
37554
+ "autocopy_to_clipboard",
37555
+ "enable_mouse_capture",
37556
+ "enable_sticky_prompt",
37557
+ "collapse_turn_details",
37558
+ "enable_file_autocomplete",
37559
+ "file_watcher_for_autocomplete",
37560
+ "ask_confirmation_on_exit",
37561
+ "displayed_workdir",
37562
+ "context_warnings",
37563
+ "voice_mode_enabled",
37564
+ "narrator_enabled",
37565
+ "show_thinking_nodes",
37566
+ "show_subagent_status_list",
37567
+ "worktree_limit",
37568
+ "auto_worktree",
37569
+ "worktree_copy_on_write",
37570
+ "bypass_tool_permissions",
37571
+ "raise_on_compaction_failure",
37572
+ "enable_telemetry",
37573
+ "managed_shell_tools_enabled",
37574
+ "enable_background_processes",
37575
+ "enable_subagents",
37576
+ "max_subagents",
37577
+ "max_concurrent_subagents",
37578
+ "compaction_prompt_id",
37579
+ "title_prompt_id",
37580
+ "include_commit_signature",
37581
+ "include_model_info",
37582
+ "include_project_context",
37583
+ "include_prompt_detail",
37584
+ "strict_config",
37585
+ "enable_update_checks",
37586
+ "enable_auto_update",
37587
+ "enable_notifications",
37588
+ "keep_awake",
37589
+ "experimental_enable_tab_status",
37590
+ "enable_system_trust_store",
37591
+ "api_timeout",
37592
+ "api_retry_max_elapsed_time",
37593
+ "max_goal_token_budget",
37594
+ "api_stream_idle_timeout",
37595
+ "agent_max_output_tokens",
37596
+ "compaction_max_output_tokens",
37597
+ "compaction_reasoning_limit_tokens",
37598
+ "output_limit_retries",
37599
+ "api_connect_timeout",
37600
+ "api_write_timeout",
37601
+ "api_pool_timeout",
37602
+ "vibe_base_url",
37603
+ "vibe_code_sessions_base_url",
37604
+ "log_level",
37605
+ "project_context",
37606
+ "session_logging",
37607
+ "experiments"
37608
+ ]);
37609
+ /**
37610
+ * The legacy key Vibe folds into `disabled_tools` before it filters an agent
37611
+ * profile (`migrate_agent_profile_config`).
37612
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/_migration.py
37613
+ */
37614
+ const VIBE_LEGACY_BASE_DISABLED_KEY = "base_disabled";
37615
+ /** Per tool, an agent keeps only the shell timeouts and a narrowing `permission`. */
37616
+ const VIBE_AGENT_TOOL_KEYS = /* @__PURE__ */ new Set(["default_timeout", "max_timeout_seconds"]);
37617
+ const VIBE_AGENT_NARROWING_PERMISSIONS = /* @__PURE__ */ new Set(["ask", "never"]);
37618
+ /**
37619
+ * Fold a legacy `base_disabled` list into `disabled_tools` the way Vibe's
37620
+ * `migrate_agent_profile_config` does, so the restriction it carries is kept.
37621
+ */
37622
+ function migrateVibeBaseDisabled(tomlObj) {
37623
+ const legacyDisabled = tomlObj[VIBE_LEGACY_BASE_DISABLED_KEY];
37624
+ if (!Array.isArray(legacyDisabled)) return tomlObj;
37625
+ const rest = Object.fromEntries(Object.entries(tomlObj).filter(([key]) => key !== VIBE_LEGACY_BASE_DISABLED_KEY));
37626
+ const disabledTools = rest.disabled_tools;
37627
+ return {
37628
+ ...rest,
37629
+ disabled_tools: Array.isArray(disabledTools) ? [.../* @__PURE__ */ new Set([...disabledTools, ...legacyDisabled])] : legacyDisabled
37630
+ };
37631
+ }
37632
+ /**
37633
+ * Drop the settings Vibe ignores on an `agent_type = "agent"` profile, so the
37634
+ * generated file does not pretend to grant what Vibe refuses. Mirrors Vibe's
37635
+ * `_agent_settings`; returns the kept TOML object and the dotted keys that
37636
+ * were dropped.
37637
+ */
37638
+ function stripVibeAgentIgnoredSettings(tomlObj) {
37639
+ const kept = {};
37640
+ const dropped = [];
37641
+ for (const [key, value] of Object.entries(migrateVibeBaseDisabled(tomlObj))) {
37642
+ if (VIBE_AGENT_IGNORED_KEYS.has(key)) {
37643
+ dropped.push(key);
37644
+ continue;
37645
+ }
37646
+ if (key !== "tools" || typeof value !== "object" || value === null || Array.isArray(value)) {
37647
+ kept[key] = value;
37648
+ continue;
37649
+ }
37650
+ const tools = {};
37651
+ for (const [tool, settings] of Object.entries(value)) {
37652
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) {
37653
+ dropped.push(`tools.${tool}`);
37654
+ continue;
37655
+ }
37656
+ const own = {};
37657
+ for (const [setting, settingValue] of Object.entries(settings)) if (VIBE_AGENT_TOOL_KEYS.has(setting) || setting === "permission" && VIBE_AGENT_NARROWING_PERMISSIONS.has(settingValue)) own[setting] = settingValue;
37658
+ else dropped.push(`tools.${tool}.${setting}`);
37659
+ if (Object.keys(own).length > 0) tools[tool] = own;
37660
+ }
37661
+ if (Object.keys(tools).length > 0) kept.tools = tools;
37662
+ }
37663
+ return {
37664
+ kept,
37665
+ dropped: dropped.toSorted()
37666
+ };
37094
37667
  }
37095
37668
  /**
37096
37669
  * Vibe resolves a `system_prompt_id` by file name, and
@@ -37170,7 +37743,7 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37170
37743
  validate: true
37171
37744
  });
37172
37745
  }
37173
- static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false }) {
37746
+ static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false, logger }) {
37174
37747
  const frontmatter = rulesyncSubagent.getFrontmatter();
37175
37748
  const rawSection = frontmatter.vibe ?? {};
37176
37749
  const vibeSection = this.filterToolSpecificSection(rawSection, [
@@ -37188,7 +37761,13 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37188
37761
  ...vibeSection,
37189
37762
  ...promptBody ? { system_prompt_id: slug } : {}
37190
37763
  };
37191
- const body = smol_toml.stringify(tomlObj);
37764
+ let finalToml = tomlObj;
37765
+ if (tomlObj.agent_type === "agent") {
37766
+ const { kept, dropped } = stripVibeAgentIgnoredSettings(tomlObj);
37767
+ if (dropped.length > 0) logger?.warn(`Vibe subagent ${rulesyncSubagent.getRelativeFilePath()}: dropped ${dropped.map((key) => `'${key}'`).join(", ")}, which Vibe v3.1.4+ ignores on an agent_type = "agent" profile and reports as a config issue. What runs without asking belongs to the approval policy: set default_approval_policy and [tools.*] in config.toml, or use agent_type = "subagent".`);
37768
+ finalToml = kept;
37769
+ }
37770
+ const body = smol_toml.stringify(finalToml);
37192
37771
  const paths = this.getSettablePaths({ global });
37193
37772
  const relativeFilePath = rulesyncSubagent.getRelativeFilePath().replace(/\.md$/, ".toml");
37194
37773
  return new VibeSubagent({
@@ -37209,7 +37788,10 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37209
37788
  * with a warning.
37210
37789
  *
37211
37790
  * A subagent named `main` is skipped with a warning: Vibe reserves that name
37212
- * for hook matching and does not load an agent file called `main.toml`.
37791
+ * for hook matching and does not load an agent file called `main.toml`. So is
37792
+ * one named after an approval policy (`ask`, `accept-edits`, `smart-approve`,
37793
+ * `auto-approve`): Vibe ignores such a file in a project and treats it as a
37794
+ * redefinition of that policy in `~/.vibe/agents/`, never as an agent.
37213
37795
  */
37214
37796
  static fromRulesyncSubagents({ rulesyncSubagents, outputRoot = process.cwd(), global = false, logger }) {
37215
37797
  return rulesyncSubagents.flatMap((rulesyncSubagent) => {
@@ -37218,11 +37800,17 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37218
37800
  logger?.warn(`Skipping Vibe subagent ${sourcePath}: Vibe reserves the agent name '${VIBE_RESERVED_AGENT_NAME}' for hook matching and does not load an agent file named '${VIBE_RESERVED_AGENT_NAME}'. Rename the subagent file.`);
37219
37801
  return [];
37220
37802
  }
37803
+ if (isVibeApprovalPolicyFileName(sourcePath)) {
37804
+ const policy = vibeAgentFileStem(sourcePath);
37805
+ logger?.warn(`Skipping Vibe subagent ${sourcePath}: '${policy}' is a Vibe approval policy name (v3.1.4+), so Vibe never loads an agent file of that name — a project's .vibe/agents/ file is ignored and a ~/.vibe/agents/ file redefines the approval policy instead. Rename the subagent file.`);
37806
+ return [];
37807
+ }
37221
37808
  const agentFile = VibeSubagent.fromRulesyncSubagent({
37222
37809
  outputRoot,
37223
37810
  relativeDirPath: VibeSubagent.getSettablePaths({ global }).relativeDirPath,
37224
37811
  rulesyncSubagent,
37225
- global
37812
+ global,
37813
+ logger
37226
37814
  });
37227
37815
  const promptBody = rulesyncSubagent.getBody();
37228
37816
  if (!promptBody) return [agentFile];
@@ -37298,6 +37886,22 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37298
37886
  if (typeof promptId !== "string" || promptId === "" || /[\\/]/.test(promptId)) return;
37299
37887
  return await readFileContentOrNull((0, node_path.join)(outputRoot, VIBE_PROMPTS_DIR_PATH, `${promptId}.md`)) ?? void 0;
37300
37888
  }
37889
+ /**
37890
+ * A file in `.vibe/agents/` named after an approval policy is not an agent:
37891
+ * in `~/.vibe/agents/` it is the user's override of that policy (often a
37892
+ * narrower one), and in a project Vibe ignores it. It is therefore neither
37893
+ * imported as a subagent (with a warning) nor swept as an orphan, since
37894
+ * deleting a narrowing override would fall back to the broader builtin.
37895
+ */
37896
+ static async isFileOwned({ relativeFilePath, forDeletion = false, logger }) {
37897
+ if (!isVibeApprovalPolicyFileName(relativeFilePath)) return true;
37898
+ if (!forDeletion) logger?.warn(`Skipping Vibe agent file ${relativeFilePath}: '${vibeAgentFileStem(relativeFilePath)}' is a Vibe approval policy name (v3.1.4+), so the file overrides that approval policy rather than defining an agent, and it is not imported as a subagent.`);
37899
+ return false;
37900
+ }
37901
+ /** Never delete an approval-policy override; see {@link VibeSubagent.isFileOwned}. */
37902
+ isDeletable() {
37903
+ return this.promptFile || !isVibeApprovalPolicyFileName(this.getRelativeFilePath());
37904
+ }
37301
37905
  static forDeletion({ outputRoot = process.cwd(), relativeDirPath, relativeFilePath, global = false }) {
37302
37906
  return new VibeSubagent({
37303
37907
  outputRoot,
@@ -38187,6 +38791,15 @@ const toolSubagentFactories = /* @__PURE__ */ new Map([
38187
38791
  filePattern: "*.toml"
38188
38792
  }
38189
38793
  }],
38794
+ ["openbitfun", {
38795
+ class: OpenbitfunSubagent,
38796
+ meta: {
38797
+ supportsProject: true,
38798
+ supportsSimulated: false,
38799
+ supportsGlobal: true,
38800
+ filePattern: "*.md"
38801
+ }
38802
+ }],
38190
38803
  ["xum", {
38191
38804
  class: XumSubagent,
38192
38805
  meta: {
@@ -38471,7 +39084,9 @@ var SubagentsProcessor = class extends FeatureProcessor {
38471
39084
  const ownership = await Promise.all(subagentFilePaths.map((path) => factory.class.isFileOwned({
38472
39085
  outputRoot: rootOutputRoot,
38473
39086
  relativeDirPath: dirPath,
38474
- relativeFilePath: toRelativeFilePath(path)
39087
+ relativeFilePath: toRelativeFilePath(path),
39088
+ forDeletion,
39089
+ logger: this.logger
38475
39090
  })));
38476
39091
  ownedFilePaths = subagentFilePaths.filter((_, index) => ownership[index]);
38477
39092
  }
@@ -44786,7 +45401,7 @@ const TOOL_DISPLAY = [
44786
45401
  },
44787
45402
  {
44788
45403
  key: "firebender",
44789
- label: "Firebender",
45404
+ label: "Firebender ⚠️",
44790
45405
  group: "ai"
44791
45406
  },
44792
45407
  {
@@ -44804,6 +45419,11 @@ const TOOL_DISPLAY = [
44804
45419
  label: "OpenClaw",
44805
45420
  group: "ai"
44806
45421
  },
45422
+ {
45423
+ key: "openbitfun",
45424
+ label: "OpenBitFun",
45425
+ group: "ai"
45426
+ },
44807
45427
  {
44808
45428
  key: "mimocode",
44809
45429
  label: "MiMo Code",
@@ -46500,10 +47120,18 @@ var MimocodeRule = class extends OpenCodeRule {
46500
47120
  * from the working directory to the `.git` boundary and loads one instruction
46501
47121
  * file per directory level, preferring `AGENTS.md` over `CLAUDE.md` when both
46502
47122
  * exist. rulesync emits the project-root `AGENTS.md` (the same shared root file
46503
- * the agentsmd/codexcli targets write). Muse Code has user/global rules, but
46504
- * their path is not documented, so no global scope is supported here.
46505
- * (Verified against the official docs:
46506
- * https://dev.meta.ai/docs/muse-code/configuration.md)
47123
+ * the agentsmd/codexcli targets write). Muse Code also loads machine-wide user
47124
+ * rules; since 1.4.23 its changelog names `~/.claude/CLAUDE.md` as that file
47125
+ * (the filename of the alternative under Muse's own config directory is not
47126
+ * published). `~/.claude/CLAUDE.md` is exactly what the `claudecode` target
47127
+ * writes in global mode, so no global scope is supported here: emitting the
47128
+ * same file from two targets would make the result depend on target order.
47129
+ * `rulesync generate --targets claudecode --global` feeds Muse Code's user
47130
+ * rules instead, but only for the root rule (global non-root rules go to
47131
+ * `~/.claude/rules/*.md`, which Muse Code is not documented to read) and only
47132
+ * for rules that target `claudecode`. (Verified against the official docs:
47133
+ * https://dev.meta.ai/docs/muse-code/configuration and
47134
+ * https://dev.meta.ai/docs/muse-code/changelog)
46507
47135
  *
46508
47136
  * rulesync's topic-based non-root rules have no project subdirectory to map
46509
47137
  * onto, so their bodies are folded into the single root `AGENTS.md` by the
@@ -50918,9 +51546,10 @@ const AmpCheckFrontmatterSchema = zod_mini.z.looseObject({
50918
51546
  * Amp reads code review checks as Markdown files with YAML frontmatter,
50919
51547
  * scoped to the project (`.agents/checks/`) and user-wide (`~/.config/amp/checks/`;
50920
51548
  * Amp also reads `~/.config/agents/checks/`, which rulesync does not write).
50921
- * Since the docs rebuild the supported runner is the official
50922
- * `@amp/review-checks` plugin (`amp review` is deprecated); existing checks in
50923
- * this format continue to apply.
51549
+ * Amp has since removed `amp review` and deprecated project-defined checks
51550
+ * in `.agents/checks/`, together with the `@amp/review-checks` plugin that runs
51551
+ * them. rulesync keeps writing this format because Goose discovers the same
51552
+ * `.agents/checks/` directory and existing setups may still load the plugin.
50924
51553
  * @see https://ampcode.com/docs/review
50925
51554
  */
50926
51555
  var AmpCheck = class extends ToolCheck {
@@ -56499,9 +57128,12 @@ var SettingsJsonHooks = class extends ToolHooks {
56499
57128
  const config = rulesyncHooks.getJson();
56500
57129
  const generatedHooks = canonicalToToolHooks({
56501
57130
  config,
56502
- toolOverrideHooks: overrideHooksOf({
56503
- config,
56504
- overrideKey: this.getSpec().overrideKey
57131
+ toolOverrideHooks: knownOverrideHooks({
57132
+ hooks: overrideHooksOf({
57133
+ config,
57134
+ overrideKey: this.getSpec().overrideKey
57135
+ }),
57136
+ spec: this.getSpec()
56505
57137
  }),
56506
57138
  converterConfig: this.getConverterConfig(),
56507
57139
  logger
@@ -56564,6 +57196,16 @@ var SettingsJsonHooks = class extends ToolHooks {
56564
57196
  }
56565
57197
  };
56566
57198
  /**
57199
+ * The override hooks the tool can take: all of them, unless the spec lists
57200
+ * {@link SettingsJsonHooksSpec.knownOverrideEvents}, in which case only those
57201
+ * native names and the canonical supported events are kept.
57202
+ */
57203
+ function knownOverrideHooks({ hooks, spec }) {
57204
+ if (hooks === void 0 || spec.knownOverrideEvents === void 0) return hooks;
57205
+ const known = /* @__PURE__ */ new Set([...spec.converterConfig.supportedEvents, ...spec.knownOverrideEvents]);
57206
+ return Object.fromEntries(Object.entries(hooks).filter(([event]) => known.has(event)));
57207
+ }
57208
+ /**
56567
57209
  * The `hooks` map of a tool's override block (`config.<overrideKey>.hooks`),
56568
57210
  * or `undefined` when the block states none. The schema keeps every override
56569
57211
  * block loose, so the lookup goes through the record form.
@@ -56577,7 +57219,6 @@ function overrideHooksOf({ config, overrideKey }) {
56577
57219
  const hooks = override.hooks;
56578
57220
  return isPlainObject(hooks) ? hooks : void 0;
56579
57221
  }
56580
- // src/features/hooks/bob-hooks.ts
56581
57222
  const BOB_SPEC = {
56582
57223
  displayName: "Bob",
56583
57224
  overrideKey: "bob",
@@ -56586,11 +57227,12 @@ const BOB_SPEC = {
56586
57227
  canonicalToToolEventNames: CANONICAL_TO_BOB_EVENT_NAMES,
56587
57228
  toolToCanonicalEventNames: BOB_TO_CANONICAL_EVENT_NAMES,
56588
57229
  projectDirVar: "",
56589
- noMatcherEvents: /* @__PURE__ */ new Set(["beforeSubmitPrompt", "stop"]),
57230
+ noMatcherEvents: new Set(BOB_HOOK_EVENTS.filter((event) => !BOB_MATCHER_HOOK_EVENTS.includes(event))),
56590
57231
  supportedHookTypes: /* @__PURE__ */ new Set(["command", "http"]),
56591
57232
  importedHookTypeAliases: { https: "http" },
56592
57233
  wildcardMatcherMeansAll: true
56593
- }
57234
+ },
57235
+ knownOverrideEvents: BOB_NATIVE_HOOK_EVENTS
56594
57236
  };
56595
57237
  /**
56596
57238
  * IBM Bob lifecycle hooks.
@@ -57457,7 +58099,7 @@ function describeRejectedHandler(handler) {
57457
58099
  * MCP hooks are skipped with a startup warning). Matcher groups left without
57458
58100
  * handlers are removed. https://learn.chatgpt.com/docs/hooks
57459
58101
  */
57460
- function filterCodexHandlers({ hooks, logger }) {
58102
+ function filterCodexHandlers({ hooks, toolLabel, describeRejected, logger }) {
57461
58103
  const result = {};
57462
58104
  const skippedSessionEndTools = [];
57463
58105
  for (const [eventName, groups] of Object.entries(hooks)) {
@@ -57469,9 +58111,9 @@ function filterCodexHandlers({ hooks, logger }) {
57469
58111
  continue;
57470
58112
  }
57471
58113
  const handlers = entry.hooks.filter((handler) => {
57472
- const reason = describeRejectedHandler(handler);
58114
+ const reason = describeRejected(handler);
57473
58115
  if (reason !== void 0) {
57474
- logger?.warn(`Skipping a "${String(handler.type)}" hook on Codex CLI "${eventName}": ${reason}.`);
58116
+ logger?.warn(`Skipping a "${String(handler.type)}" hook on ${toolLabel} "${eventName}": ${reason}.`);
57475
58117
  return false;
57476
58118
  }
57477
58119
  if (eventName === "SessionEnd" && handler.type === "mcp_tool") skippedSessionEndTools.push(`${String(handler.server)}/${String(handler.tool)}`);
@@ -57488,6 +58130,56 @@ function filterCodexHandlers({ hooks, logger }) {
57488
58130
  return result;
57489
58131
  }
57490
58132
  /**
58133
+ * Generate the content of a Codex-shaped `hooks.json` (`{ hooks: { <Event>:
58134
+ * [matcher groups] } }`) at `relativeDirPath/relativeFilePath`. Shared by the
58135
+ * Codex CLI target and tools that read the same document (OpenBitFun), which
58136
+ * differ only in where the file lives, which events and handler types they
58137
+ * run, and which rulesync override section they read.
58138
+ */
58139
+ async function buildCodexStyleHooksFile({ outputRoot, relativeDirPath, relativeFilePath, rulesyncHooks, toolOverrideHooks, converterConfig, toolLabel, describeRejected = describeRejectedHandler, preserveUnowned, logger }) {
58140
+ const merged = mergeGeneratedHookLists({
58141
+ existingContent: await readFileContentOrNull((0, node_path.join)(outputRoot, relativeDirPath, relativeFilePath)) ?? "",
58142
+ generatedHooks: filterCodexHandlers({
58143
+ hooks: canonicalToToolHooks({
58144
+ config: rulesyncHooks.getJson(),
58145
+ toolOverrideHooks,
58146
+ converterConfig,
58147
+ logger
58148
+ }),
58149
+ toolLabel,
58150
+ describeRejected,
58151
+ logger
58152
+ }),
58153
+ shape: "matcher-groups",
58154
+ preserveUnowned,
58155
+ previouslyOwned: preserveUnowned ? await readPreviouslyOwnedHooks({
58156
+ outputRoot,
58157
+ relativeDirPath
58158
+ }) : void 0,
58159
+ logger
58160
+ });
58161
+ return {
58162
+ fileContent: JSON.stringify({ hooks: merged.hooks }, null, 2),
58163
+ owned: merged.owned
58164
+ };
58165
+ }
58166
+ /**
58167
+ * Convert the parsed content of a Codex-shaped `hooks.json` back to the
58168
+ * rulesync hooks JSON, with tool-only hooks under `overrideKey`.
58169
+ */
58170
+ function codexStyleHooksToRulesyncContent({ parsed, converterConfig, overrideKey, logger }) {
58171
+ const hooks = toolHooksToCanonical({
58172
+ hooks: parsed.hooks,
58173
+ converterConfig,
58174
+ logger
58175
+ });
58176
+ return JSON.stringify(buildImportedHooksConfig({
58177
+ logger,
58178
+ hooks,
58179
+ overrideKey
58180
+ }), null, 2);
58181
+ }
58182
+ /**
57491
58183
  * Build the content for `.codex/config.toml`, cleaning up the deprecated `codex_hooks` key.
57492
58184
  * Reads the existing file (if any), parses TOML, and returns the content without writing to
57493
58185
  * disk. The caller is responsible for writing via the normal write phase.
@@ -57559,51 +58251,37 @@ var CodexcliHooks = class CodexcliHooks extends ToolHooks {
57559
58251
  }
57560
58252
  static async fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false, preserveUnowned = false, logger }) {
57561
58253
  const paths = CodexcliHooks.getSettablePaths({ global });
57562
- const existingContent = await readFileContentOrNull((0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath)) ?? "";
57563
- const config = rulesyncHooks.getJson();
57564
- const merged = mergeGeneratedHookLists({
57565
- existingContent,
57566
- generatedHooks: filterCodexHandlers({
57567
- hooks: canonicalToToolHooks({
57568
- config,
57569
- toolOverrideHooks: config.codexcli?.hooks,
57570
- converterConfig: CODEXCLI_CONVERTER_CONFIG,
57571
- logger
57572
- }),
57573
- logger
57574
- }),
57575
- shape: "matcher-groups",
58254
+ const { fileContent, owned } = await buildCodexStyleHooksFile({
58255
+ outputRoot,
58256
+ relativeDirPath: paths.relativeDirPath,
58257
+ relativeFilePath: paths.relativeFilePath,
58258
+ rulesyncHooks,
58259
+ toolOverrideHooks: rulesyncHooks.getJson().codexcli?.hooks,
58260
+ converterConfig: CODEXCLI_CONVERTER_CONFIG,
58261
+ toolLabel: "Codex CLI",
57576
58262
  preserveUnowned,
57577
- previouslyOwned: preserveUnowned ? await readPreviouslyOwnedHooks({
57578
- outputRoot,
57579
- relativeDirPath: paths.relativeDirPath
57580
- }) : void 0,
57581
58263
  logger
57582
58264
  });
57583
- const fileContent = JSON.stringify({ hooks: merged.hooks }, null, 2);
57584
58265
  return new CodexcliHooks({
57585
58266
  outputRoot,
57586
58267
  relativeDirPath: paths.relativeDirPath,
57587
58268
  relativeFilePath: paths.relativeFilePath,
57588
58269
  fileContent,
57589
- ownedHookRefs: preserveUnowned ? merged.owned : void 0,
58270
+ ownedHookRefs: preserveUnowned ? owned : void 0,
57590
58271
  validate
57591
58272
  });
57592
58273
  }
57593
58274
  toRulesyncHooks({ logger } = {}) {
57594
- const hooks = toolHooksToCanonical({
57595
- hooks: this.parseFileContentOrThrow({
57596
- displayName: "Codex CLI",
57597
- parse: (fileContent) => JSON.parse(fileContent)
57598
- }).hooks,
58275
+ const parsed = this.parseFileContentOrThrow({
58276
+ displayName: "Codex CLI",
58277
+ parse: (fileContent) => JSON.parse(fileContent)
58278
+ });
58279
+ return this.toRulesyncHooksDefault({ fileContent: codexStyleHooksToRulesyncContent({
58280
+ parsed,
57599
58281
  converterConfig: CODEXCLI_CONVERTER_CONFIG,
58282
+ overrideKey: "codexcli",
57600
58283
  logger
57601
- });
57602
- return this.toRulesyncHooksDefault({ fileContent: JSON.stringify(buildImportedHooksConfig({
57603
- logger,
57604
- hooks,
57605
- overrideKey: "codexcli"
57606
- }), null, 2) });
58284
+ }) });
57607
58285
  }
57608
58286
  static supportsPreserveUnowned() {
57609
58287
  return true;
@@ -60005,7 +60683,7 @@ function canonicalToHermesHooks({ config, toolOverrideHooks, logger }) {
60005
60683
  for (const [nativeEvent, definitions] of Object.entries(toolOverrideHooks ?? {})) {
60006
60684
  if (HERMESAGENT_CANONICAL_EVENTS.has(nativeEvent)) continue;
60007
60685
  if (HERMESAGENT_SHELL_UNSUPPORTED_EVENTS.has(nativeEvent)) logger?.warn(`Hermes hook event "${nativeEvent}" is Python-plugin-only; Hermes Agent refuses it for shell hooks, so the generated entry will never run.`);
60008
- else if (!HERMESAGENT_NATIVE_EVENTS.has(nativeEvent)) logger?.warn(`Hermes hook event "${nativeEvent}" is not documented by Hermes Agent v0.23.2; preserving it for forward compatibility.`);
60686
+ else if (!HERMESAGENT_NATIVE_EVENTS.has(nativeEvent)) logger?.warn(`Hermes hook event "${nativeEvent}" is not documented by Hermes Agent v0.23.4; preserving it for forward compatibility.`);
60009
60687
  setHermesHookEntries({
60010
60688
  result,
60011
60689
  event: nativeEvent,
@@ -60682,7 +61360,9 @@ function buildRunHelperLinesFor(cwdExpression) {
60682
61360
  * hook denies it:
60683
61361
  * - exit code 2 → deny, with the command's stderr as the reason;
60684
61362
  * - exit code 0 with JSON stdout whose `hookSpecificOutput.permissionDecision`
60685
- * is `"deny"` → deny, with `permissionDecisionReason` as the reason;
61363
+ * is `"deny"` → deny, with `permissionDecisionReason` as the reason; when it
61364
+ * sets no `permissionDecision`, the deprecated top-level `decision: "block"`
61365
+ * that Claude Code still honors denies too, with `reason` as the reason;
60686
61366
  * - exit code 0 otherwise → allow;
60687
61367
  * - any other non-zero exit → deny too, with stderr or the exit code;
60688
61368
  * - more than 1 MiB of stdout → deny, without parsing it;
@@ -60717,12 +61397,13 @@ const PRE_TOOL_USE_RESULT_HELPER_LINES = [
60717
61397
  " } catch {",
60718
61398
  " return;",
60719
61399
  " }",
60720
- " const specific = parsed && typeof parsed === \"object\" ? parsed.hookSpecificOutput : undefined;",
60721
- " if (specific && typeof specific === \"object\" && specific.permissionDecision === \"deny\") {",
61400
+ " if (!parsed || typeof parsed !== \"object\") return;",
61401
+ " const specific = parsed.hookSpecificOutput;",
61402
+ " const hasDecision = typeof specific === \"object\" && specific !== null && specific.permissionDecision !== undefined;",
61403
+ " const reason = hasDecision ? specific.permissionDecisionReason : parsed.reason;",
61404
+ " if (hasDecision ? specific.permissionDecision === \"deny\" : parsed.decision === \"block\") {",
60722
61405
  " throw new Error(",
60723
- " (typeof specific.permissionDecisionReason === \"string\" &&",
60724
- " sanitizeBlockReason(specific.permissionDecisionReason)) ||",
60725
- " \"Blocked by a preToolUse hook.\",",
61406
+ " (typeof reason === \"string\" && sanitizeBlockReason(reason)) || \"Blocked by a preToolUse hook.\",",
60726
61407
  " );",
60727
61408
  " }",
60728
61409
  " return;",
@@ -62498,11 +63179,123 @@ const PI_SETTLE_BLOCKING_EVENT = "agent_before_settle";
62498
63179
  * @see https://github.com/can1357/oh-my-pi/blob/fa5ff4a3a977a28b93d025f4cf50f046e019f18c/packages/coding-agent/src/session/agent-session.ts
62499
63180
  */
62500
63181
  const OMP_SESSION_STOP_BLOCKING_EVENT = "session_stop";
63182
+ /**
63183
+ * Pi's `resolveToCwd` (`core/tools/path-utils.ts`), which calls
63184
+ * `resolvePath(path, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true })`
63185
+ * from `utils/paths.ts`: Unicode spaces become plain spaces, a leading `@` is
63186
+ * dropped, on Windows Git Bash / WSL drive paths are converted, `~` is
63187
+ * expanded, a `file://` URL is converted, and the result is resolved against
63188
+ * cwd. Pi has no URL passthrough, so any other `scheme://` text is a relative
63189
+ * path too.
63190
+ *
63191
+ * @see https://github.com/earendil-works/pi/blob/v1.6.0/packages/coding-agent/src/utils/paths.ts
63192
+ */
63193
+ const PI_PATH_RESOLVER_LINES = [
63194
+ "function absoluteToolPath(path: unknown, cwd: string): unknown {",
63195
+ " if (typeof path !== \"string\") return path;",
63196
+ " let normalized = path.replace(/[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g, \" \");",
63197
+ " if (normalized.startsWith(\"@\")) normalized = normalized.slice(1);",
63198
+ " if (process.platform === \"win32\" && normalized.startsWith(\"/\") && !normalized.startsWith(\"//\") && !normalized.includes(\"\\\\\")) {",
63199
+ " const drive = normalized.match(/^\\/(?:mnt\\/|cygdrive\\/)?([a-z])(?:\\/(.*))?$/i);",
63200
+ " if (drive?.[1]) normalized = `${drive[1].toUpperCase()}:\\\\${drive[2]?.replaceAll(\"/\", \"\\\\\") ?? \"\"}`;",
63201
+ " }",
63202
+ " if (normalized === \"~\") normalized = homedir();",
63203
+ " else if (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {",
63204
+ " normalized = joinPath(homedir(), normalized.slice(2));",
63205
+ " } else if (/^file:\\/\\//.test(normalized)) {",
63206
+ " try {",
63207
+ " normalized = fileURLToPath(normalized);",
63208
+ " } catch {",
63209
+ " return path;",
63210
+ " }",
63211
+ " }",
63212
+ " return resolvePath(cwd, normalized);",
63213
+ "}"
63214
+ ];
63215
+ /**
63216
+ * oh-my-pi's `resolveToCwd` (`tools/path-utils.ts`): `expandPath` strips a
63217
+ * stray leading `:` before a path shape, strips a leading `@` only before an
63218
+ * absolute path, `~` or an internal URL, turns Unicode spaces into plain
63219
+ * spaces, converts a `file://` URL and expands `~`; an internal URL is not a
63220
+ * filesystem path, a bare root (`/`) is the workspace root, and anything else
63221
+ * is resolved against cwd. Windows drive-alias handling is not mirrored.
63222
+ *
63223
+ * @see https://github.com/can1357/oh-my-pi/blob/76b7d843d59bc83cc40cd5decadc89dc808a14e6/packages/coding-agent/src/tools/path-utils.ts
63224
+ */
63225
+ const OMP_PATH_RESOLVER_LINES = [
63226
+ `const INTERNAL_URL_SCHEME = /^(?:${[
63227
+ "skill",
63228
+ "rule",
63229
+ "memory",
63230
+ "out",
63231
+ "agent",
63232
+ "history",
63233
+ "local",
63234
+ "proc",
63235
+ "cfg",
63236
+ "ssh",
63237
+ "security",
63238
+ "vault",
63239
+ "issue",
63240
+ "pr",
63241
+ "mr",
63242
+ "mcp",
63243
+ "omp",
63244
+ "help",
63245
+ "attachment",
63246
+ "conflict"
63247
+ ].join("|")}):\\/\\/?/i;`,
63248
+ "",
63249
+ "function absoluteToolPath(path: unknown, cwd: string): unknown {",
63250
+ " if (typeof path !== \"string\") return path;",
63251
+ " let normalized = /^:(?=[/\\\\~]|\\.\\.?[/\\\\]|[A-Za-z]:)/.test(path) ? path.slice(1) : path;",
63252
+ " if (normalized.startsWith(\"@\")) {",
63253
+ " const rest = normalized.slice(1);",
63254
+ " if (rest.startsWith(\"/\") || rest === \"~\" || rest.startsWith(\"~/\") || win32Path.isAbsolute(rest) || INTERNAL_URL_SCHEME.test(rest)) {",
63255
+ " normalized = rest;",
63256
+ " }",
63257
+ " }",
63258
+ " normalized = normalized.replace(/[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g, \" \");",
63259
+ " if (normalized.toLowerCase().startsWith(\"file://\")) {",
63260
+ " try {",
63261
+ " normalized = fileURLToPath(normalized);",
63262
+ " } catch {",
63263
+ " // oh-my-pi keeps an unconvertible `file://` text as written.",
63264
+ " }",
63265
+ " }",
63266
+ " if (normalized === \"~\") normalized = homedir();",
63267
+ " else if (normalized.startsWith(\"~/\")) normalized = joinPath(homedir(), normalized.slice(2));",
63268
+ " if (INTERNAL_URL_SCHEME.test(normalized)) return normalized;",
63269
+ " if (/^\\/+$/.test(normalized)) return resolvePath(cwd);",
63270
+ " return resolvePath(cwd, normalized);",
63271
+ "}"
63272
+ ];
63273
+ /**
63274
+ * Tool names both Pi and oh-my-pi share with a canonical counterpart. Pi's
63275
+ * `powershell` tool is deliberately left out: Rulesync has no canonical name
63276
+ * for it, so it keeps its own.
63277
+ */
63278
+ const SHARED_CANONICAL_TOOL_NAMES = {
63279
+ bash: "Bash",
63280
+ read: "Read",
63281
+ write: "Write",
63282
+ edit: "Edit",
63283
+ grep: "Grep"
63284
+ };
62501
63285
  const PI_EXTENSION_DIALECT = {
62502
63286
  overrideKey: "pi",
62503
63287
  typesPackage: "@earendil-works/pi-coding-agent",
62504
63288
  promptPassLine: "return { action: \"continue\" };",
62505
- promptCancelLine: "return { action: \"handled\" };"
63289
+ promptCancelLine: "return { action: \"handled\" };",
63290
+ toolNames: {
63291
+ ...SHARED_CANONICAL_TOOL_NAMES,
63292
+ find: "Glob"
63293
+ },
63294
+ editTextKeys: {
63295
+ old: "oldText",
63296
+ new: "newText"
63297
+ },
63298
+ pathResolverLines: PI_PATH_RESOLVER_LINES
62506
63299
  };
62507
63300
  /**
62508
63301
  * oh-my-pi's `emitInput` stops at the first result with `handled` set and
@@ -62514,7 +63307,16 @@ const OMP_EXTENSION_DIALECT = {
62514
63307
  overrideKey: "omp",
62515
63308
  typesPackage: "@oh-my-pi/pi-coding-agent",
62516
63309
  promptPassLine: "return {};",
62517
- promptCancelLine: "return { handled: true };"
63310
+ promptCancelLine: "return { handled: true };",
63311
+ toolNames: {
63312
+ ...SHARED_CANONICAL_TOOL_NAMES,
63313
+ glob: "Glob"
63314
+ },
63315
+ editTextKeys: {
63316
+ old: "old_string",
63317
+ new: "new_string"
63318
+ },
63319
+ pathResolverLines: OMP_PATH_RESOLVER_LINES
62518
63320
  };
62519
63321
  const PI_BLOCKING_MODE_BY_EVENT = {
62520
63322
  [PI_BLOCKING_EVENT]: "tool",
@@ -62538,7 +63340,284 @@ function failureLinesByMode(dialect) {
62538
63340
  };
62539
63341
  }
62540
63342
  /**
62541
- * Helper emitted alongside blocking handlers. `promisify(exec)` rejects on a
63343
+ * Canonical events whose command receives Claude Code's JSON input for the
63344
+ * event on stdin, mapped to its `hook_event_name`; every other command gets an
63345
+ * empty stdin, as in the OpenCode-style plugin (`STDIN_PAYLOADS` in
63346
+ * `opencode-style-generator.ts`). All three ride on Pi's tool events, whose
63347
+ * `event.toolName`, `event.toolCallId` and `event.input` the payload is built
63348
+ * from. A payload is serialized lazily, once per invocation, by the first
63349
+ * handler that runs.
63350
+ *
63351
+ * @see https://github.com/earendil-works/pi/blob/v1.6.0/packages/coding-agent/docs/extensions.md#tool_call
63352
+ * @see https://code.claude.com/docs/en/hooks
63353
+ */
63354
+ const STDIN_PAYLOAD_EVENTS = {
63355
+ preToolUse: "PreToolUse",
63356
+ postToolUse: "PostToolUse",
63357
+ postToolUseFailure: "PostToolUseFailure"
63358
+ };
63359
+ /**
63360
+ * The fields each payload adds to the tool call's own (`session_id`, `cwd`,
63361
+ * `hook_event_name`, `tool_name`, `tool_input`, `tool_use_id`), as TypeScript
63362
+ * object entries evaluated against the `tool_result` event.
63363
+ */
63364
+ const STDIN_PAYLOAD_EXTRA_FIELDS = {
63365
+ PreToolUse: "",
63366
+ PostToolUse: "tool_response: { content: event.content, details: event.details }",
63367
+ PostToolUseFailure: "error: toolResultText(event.content)"
63368
+ };
63369
+ /**
63370
+ * Helpers emitted when a handler receives a stdin payload or tests a matcher.
63371
+ *
63372
+ * `claudeToolName` maps the dialect's built-in tool names to the canonical
63373
+ * Claude Code names Rulesync uses elsewhere (`bash` → `Bash`, ...). MCP tools
63374
+ * are already named `mcp__<server>__<tool>` by Pi, and other tools keep their
63375
+ * own name.
63376
+ *
63377
+ * `claudeToolInput` passes the tool's arguments through, except for the file
63378
+ * tools: `path` becomes Claude Code's absolute `file_path`, resolved against
63379
+ * the session cwd the way Pi's `resolveToCwd` does, and on Pi each `edits`
63380
+ * entry's `oldText` / `newText` becomes `old_string` / `new_string` (oh-my-pi
63381
+ * already uses those, see `editTextKeys`). When the call has no top-level
63382
+ * `old_string` / `new_string`, every edit's text is joined into them, as
63383
+ * Claude Code's `Edit` input carries, so a guard reading those sees every
63384
+ * change. The mapped keys are written last and any same-named key the model
63385
+ * added is dropped, so an extra argument (Pi's schemas allow them) cannot make
63386
+ * a guard check a different file or text than the one the tool acts on.
63387
+ */
63388
+ function buildToolPayloadHelperLines(dialect) {
63389
+ return [
63390
+ `const CLAUDE_TOOL_NAMES: Record<string, string> = ${JSON.stringify(dialect.toolNames)};`,
63391
+ "",
63392
+ "function claudeToolName(toolName: string): string {",
63393
+ " return Object.hasOwn(CLAUDE_TOOL_NAMES, toolName) ? (CLAUDE_TOOL_NAMES[toolName] ?? toolName) : toolName;",
63394
+ "}",
63395
+ "",
63396
+ "function matchesTool(matcher: RegExp, toolName: string): boolean {",
63397
+ " return matcher.test(toolName) || matcher.test(claudeToolName(toolName));",
63398
+ "}",
63399
+ "",
63400
+ ...dialect.pathResolverLines,
63401
+ "",
63402
+ `const EDIT_TEXT_KEYS = ${JSON.stringify(dialect.editTextKeys)};`,
63403
+ "const CLAUDE_EDIT_TEXT_KEYS = EDIT_TEXT_KEYS.old === \"old_string\";",
63404
+ "",
63405
+ "function claudeEditEntry(edit: unknown): unknown {",
63406
+ " if (CLAUDE_EDIT_TEXT_KEYS || !edit || typeof edit !== \"object\") return edit;",
63407
+ " const {",
63408
+ " [EDIT_TEXT_KEYS.old]: oldText,",
63409
+ " [EDIT_TEXT_KEYS.new]: newText,",
63410
+ " old_string: _old,",
63411
+ " new_string: _new,",
63412
+ " ...others",
63413
+ " } = edit as Record<string, unknown>;",
63414
+ " return { ...others, old_string: oldText, new_string: newText };",
63415
+ "}",
63416
+ "",
63417
+ "function joinedEditText(edits: unknown[], key: string): string | undefined {",
63418
+ " const texts = edits",
63419
+ " .map((edit: unknown) => (edit as Record<string, unknown> | null)?.[key])",
63420
+ " .filter((text): text is string => typeof text === \"string\");",
63421
+ " return texts.length > 0 ? texts.join(\"\\n\") : undefined;",
63422
+ "}",
63423
+ "",
63424
+ "function claudeToolInput(toolName: string, input: unknown, cwd: string): unknown {",
63425
+ " if (![\"read\", \"write\", \"edit\"].includes(toolName)) return input;",
63426
+ " if (!input || typeof input !== \"object\" || Array.isArray(input)) return input;",
63427
+ " const { path, file_path: _filePath, ...rest } = input as Record<string, unknown>;",
63428
+ " if (!CLAUDE_EDIT_TEXT_KEYS) {",
63429
+ " delete rest.old_string;",
63430
+ " delete rest.new_string;",
63431
+ " }",
63432
+ " // The raw `path` stays, so a guard can check what the model wrote too.",
63433
+ " const claudeInput: Record<string, unknown> = { ...rest, path, file_path: absoluteToolPath(path, cwd) };",
63434
+ " if (!Array.isArray(rest.edits)) return claudeInput;",
63435
+ " const edits = rest.edits.map(claudeEditEntry);",
63436
+ " return {",
63437
+ " ...claudeInput,",
63438
+ " edits,",
63439
+ " old_string: claudeInput.old_string ?? joinedEditText(edits, \"old_string\"),",
63440
+ " new_string: claudeInput.new_string ?? joinedEditText(edits, \"new_string\"),",
63441
+ " };",
63442
+ "}",
63443
+ "",
63444
+ "function toolResultText(content: unknown): string {",
63445
+ " if (!Array.isArray(content)) return \"\";",
63446
+ " return content",
63447
+ " .map((block: unknown) => {",
63448
+ " const part = block as { type?: unknown; text?: unknown } | null;",
63449
+ " return part?.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\";",
63450
+ " })",
63451
+ " .filter(Boolean)",
63452
+ " .join(\"\\n\");",
63453
+ "}",
63454
+ "",
63455
+ "type ToolHookEvent = { toolName: string; toolCallId?: string; input?: unknown };",
63456
+ "",
63457
+ "function toolHookInput(",
63458
+ " hookEventName: string,",
63459
+ " event: ToolHookEvent,",
63460
+ " ctx: ExtensionContext | undefined,",
63461
+ " extra: Record<string, unknown> = {},",
63462
+ "): string {",
63463
+ " const cwd = ctx?.cwd ?? process.cwd();",
63464
+ " return JSON.stringify({",
63465
+ " session_id: ctx?.sessionManager?.getSessionId?.(),",
63466
+ " cwd,",
63467
+ " hook_event_name: hookEventName,",
63468
+ " tool_name: claudeToolName(event.toolName),",
63469
+ " tool_input: claudeToolInput(event.toolName, event.input, cwd),",
63470
+ " tool_use_id: event.toolCallId,",
63471
+ " ...extra,",
63472
+ " });",
63473
+ "}"
63474
+ ];
63475
+ }
63476
+ /**
63477
+ * Helpers emitted alongside `tool_call` handlers. A command that exits 0 may
63478
+ * still decide the call the way Claude Code reads a `PreToolUse` hook's JSON
63479
+ * stdout: `hookSpecificOutput.permissionDecision` `"deny"` or `"ask"` (with
63480
+ * `permissionDecisionReason`) or, when no `permissionDecision` is given, the
63481
+ * deprecated top-level `decision: "block"` (with `reason`). Output that is not
63482
+ * such JSON allows the call, so hooks that print plain text keep working. The
63483
+ * deny side is the OpenCode-style plugin's `__rulesyncEnforcePreToolUseResult`
63484
+ * contract, plus the deprecated form Claude Code still honors.
63485
+ *
63486
+ * Pi has no permission prompt of its own, so `"ask"` is put to the user with
63487
+ * `ctx.ui.confirm` when a UI is attached, and denies the call when none is (print
63488
+ * and JSON modes) or the dialog fails: a hook asking for a human must not pass
63489
+ * silently.
63490
+ */
63491
+ const TOOL_DECISION_HELPER_LINES = [
63492
+ "type ToolHookDecision = { kind: \"deny\" | \"ask\"; reason: string };",
63493
+ "",
63494
+ "function toolHookDecision(stdout: string): ToolHookDecision | undefined {",
63495
+ " let parsed: unknown;",
63496
+ " try {",
63497
+ " parsed = JSON.parse(stdout);",
63498
+ " } catch {",
63499
+ " return undefined;",
63500
+ " }",
63501
+ " if (!parsed || typeof parsed !== \"object\") return undefined;",
63502
+ " const output = parsed as { decision?: unknown; reason?: unknown; hookSpecificOutput?: unknown };",
63503
+ " const specific = output.hookSpecificOutput as",
63504
+ " | { permissionDecision?: unknown; permissionDecisionReason?: unknown }",
63505
+ " | null",
63506
+ " | undefined;",
63507
+ " const hasDecision = typeof specific === \"object\" && specific !== null && specific.permissionDecision !== undefined;",
63508
+ " const decision = hasDecision ? specific?.permissionDecision : output.decision === \"block\" ? \"deny\" : undefined;",
63509
+ " if (decision !== \"deny\" && decision !== \"ask\") return undefined;",
63510
+ " const reason = hasDecision ? specific?.permissionDecisionReason : output.reason;",
63511
+ " return {",
63512
+ " kind: decision,",
63513
+ " reason:",
63514
+ " (typeof reason === \"string\" && sanitizeBlockReason(reason)) ||",
63515
+ " (decision === \"ask\" ? \"A preToolUse hook asked for confirmation.\" : \"Blocked by a preToolUse hook.\"),",
63516
+ " };",
63517
+ "}",
63518
+ "",
63519
+ "async function allowsToolCall(",
63520
+ " decision: ToolHookDecision,",
63521
+ " ctx: ExtensionContext | undefined,",
63522
+ "): Promise<boolean> {",
63523
+ " if (decision.kind !== \"ask\" || !ctx?.hasUI) return false;",
63524
+ " try {",
63525
+ " return await ctx.ui.confirm(\"Allow this tool call?\", decision.reason);",
63526
+ " } catch {",
63527
+ " return false;",
63528
+ " }",
63529
+ "}"
63530
+ ];
63531
+ /**
63532
+ * Runs a hook command through the platform shell with `input` as its stdin
63533
+ * (empty when the event has no payload, so a command that reads stdin never
63534
+ * waits on Pi's own), bounded by the hook's `timeout` in seconds (Claude
63535
+ * Code's default of 600 when unset, as in the OpenCode-style plugin). A stdin
63536
+ * the command never reads is not an error.
63537
+ *
63538
+ * The command runs in its own process group (except on Windows), so a command
63539
+ * past its timeout is killed together with everything it started, and the
63540
+ * call rejects with a `HookTimeoutError` right away rather than waiting for a
63541
+ * descendant still holding its output open. Like `promisify(exec)`, which
63542
+ * earlier versions used, a non-zero exit rejects with an error carrying
63543
+ * `code`, `stdout` and `stderr`, and more than 1 MiB on either stream rejects
63544
+ * and kills the command.
63545
+ *
63546
+ * A detached group does not get the terminal's Ctrl+C, so the extension
63547
+ * kills every command still running on `session_shutdown`, after the other
63548
+ * handlers (including a `sessionEnd` hook's) have run: Pi awaits them in
63549
+ * registration order. A Pi process killed outright never fires it, and since
63550
+ * the timeout timer lives in that process too, its commands then keep running
63551
+ * with no deadline until they exit on their own.
63552
+ */
63553
+ const RUN_HELPER_LINES = [
63554
+ "const MAX_HOOK_OUTPUT_LENGTH = 1024 * 1024;",
63555
+ "",
63556
+ "class HookTimeoutError extends Error {}",
63557
+ "",
63558
+ "// Kills of the commands still running, for `session_shutdown`.",
63559
+ "const runningHookCommands = new Set<() => void>();",
63560
+ "",
63561
+ "function run(",
63562
+ " command: string,",
63563
+ " { input = \"\", seconds }: { input?: string; seconds: number },",
63564
+ "): Promise<{ stdout: string; stderr: string }> {",
63565
+ " return new Promise((resolve, reject) => {",
63566
+ " const detached = process.platform !== \"win32\";",
63567
+ " const child = spawn(command, { shell: true, detached, windowsHide: true });",
63568
+ " const output = { stdout: \"\", stderr: \"\" };",
63569
+ " let settled = false;",
63570
+ " const finish = (error?: Error) => {",
63571
+ " if (settled) return;",
63572
+ " settled = true;",
63573
+ " clearTimeout(timer);",
63574
+ " runningHookCommands.delete(killTree);",
63575
+ " if (error) reject(error);",
63576
+ " else resolve(output);",
63577
+ " };",
63578
+ " const killTree = () => {",
63579
+ " try {",
63580
+ " if (detached && child.pid !== undefined) process.kill(-child.pid, \"SIGKILL\");",
63581
+ " else child.kill(\"SIGKILL\");",
63582
+ " } catch {",
63583
+ " // Already gone.",
63584
+ " }",
63585
+ " child.stdout?.destroy();",
63586
+ " child.stderr?.destroy();",
63587
+ " };",
63588
+ " runningHookCommands.add(killTree);",
63589
+ " const timer = setTimeout(() => {",
63590
+ " killTree();",
63591
+ " finish(new HookTimeoutError(`Hook command timed out after ${seconds} seconds.`));",
63592
+ " }, seconds * 1000);",
63593
+ " for (const stream of [\"stdout\", \"stderr\"] as const) {",
63594
+ " child[stream]?.setEncoding(\"utf8\");",
63595
+ " child[stream]?.on(\"data\", (chunk: string) => {",
63596
+ " output[stream] += chunk;",
63597
+ " if (output[stream].length <= MAX_HOOK_OUTPUT_LENGTH) return;",
63598
+ " killTree();",
63599
+ " finish(new Error(`Hook command wrote more than 1 MiB to ${stream}.`));",
63600
+ " });",
63601
+ " }",
63602
+ " child.on(\"error\", (error) => finish(error));",
63603
+ " child.on(\"close\", (code, signal) => {",
63604
+ " if (code === 0) return finish();",
63605
+ " finish(",
63606
+ " Object.assign(new Error(`Command failed: ${command}`), {",
63607
+ " code,",
63608
+ " signal,",
63609
+ " stdout: output.stdout,",
63610
+ " stderr: output.stderr,",
63611
+ " }),",
63612
+ " );",
63613
+ " });",
63614
+ " child.stdin?.on(\"error\", () => {});",
63615
+ " child.stdin?.end(input);",
63616
+ " });",
63617
+ "}"
63618
+ ];
63619
+ /**
63620
+ * Helper emitted alongside blocking handlers. `run` rejects on a
62542
63621
  * non-zero exit with an error carrying `stdout` / `stderr` / `code`, so the
62543
63622
  * reason is derived from the rejection rather than from a resolved exit code.
62544
63623
  * A command that could not be run at all (spawn failure, `maxBuffer` overflow)
@@ -62642,7 +63721,9 @@ function collectPiHandlers({ effectiveHooks, eventMap }) {
62642
63721
  handlers.push({
62643
63722
  command: def.command,
62644
63723
  matcher: def.matcher ? def.matcher : void 0,
62645
- onlyOnError: PI_ERROR_GATED_CANONICAL_EVENTS.has(canonicalEvent)
63724
+ onlyOnError: PI_ERROR_GATED_CANONICAL_EVENTS.has(canonicalEvent),
63725
+ ...hookTimingOf(def),
63726
+ ...PI_TOOL_EVENTS.has(piEvent) && STDIN_PAYLOAD_EVENTS[canonicalEvent] ? { payload: STDIN_PAYLOAD_EVENTS[canonicalEvent] } : {}
62646
63727
  });
62647
63728
  }
62648
63729
  if (handlers.length > 0) {
@@ -62657,22 +63738,63 @@ function buildCommandLines({ handler, usesToolName, blocking, dialect }) {
62657
63738
  const lines = [];
62658
63739
  const conditions = [];
62659
63740
  if (handler.onlyOnError) conditions.push("event.isError");
62660
- if (usesToolName && handler.matcher) conditions.push(`new RegExp(${matcherToEmbeddedLiteral(handler.matcher)}).test(event.toolName)`);
63741
+ if (usesToolName && handler.matcher) conditions.push(`matchesTool(new RegExp(${matcherToEmbeddedLiteral(handler.matcher)}), event.toolName)`);
62661
63742
  const gated = conditions.length > 0;
62662
63743
  const indent = gated ? " " : " ";
62663
- const embeddedCommand = JSON.stringify(handler.command);
63744
+ const options = [...handler.payload ? [`input: ${payloadAccessorName(handler.payload)}()`] : [], `seconds: ${handler.timeout}`];
63745
+ const runCall = `run(${JSON.stringify(handler.command)}, { ${options.join(", ")} })`;
62664
63746
  if (gated) lines.push(` if (${conditions.join(" && ")}) {`);
62665
63747
  const onFailure = failureLinesByMode(dialect)[blocking];
62666
- if (onFailure.length > 0) {
63748
+ if (blocking === "tool") {
62667
63749
  lines.push(`${indent}try {`);
62668
- lines.push(`${indent} await run(${embeddedCommand});`);
63750
+ lines.push(`${indent} const decision = toolHookDecision((await ${runCall}).stdout);`);
63751
+ lines.push(`${indent} if (decision && !(await allowsToolCall(decision, ctx))) return { block: true, reason: decision.reason };`);
63752
+ lines.push(`${indent}} catch (error) {`);
63753
+ if (handler.failClosed === false) {
63754
+ lines.push(`${indent} if (error instanceof HookTimeoutError) {`);
63755
+ lines.push(`${indent} console.error("[rulesync-hooks] preToolUse hook timed out");`);
63756
+ lines.push(`${indent} } else {`);
63757
+ for (const line of onFailure) lines.push(`${indent} ${line}`);
63758
+ lines.push(`${indent} }`);
63759
+ } else for (const line of onFailure) lines.push(`${indent} ${line}`);
63760
+ lines.push(`${indent}}`);
63761
+ } else if (onFailure.length > 0) {
63762
+ lines.push(`${indent}try {`);
63763
+ lines.push(`${indent} await ${runCall};`);
62669
63764
  lines.push(`${indent}} catch (error) {`);
62670
63765
  for (const line of onFailure) lines.push(`${indent} ${line}`);
62671
63766
  lines.push(`${indent}}`);
62672
- } else lines.push(`${indent}await run(${embeddedCommand});`);
63767
+ } else lines.push(`${indent}await ${runCall};`);
62673
63768
  if (gated) lines.push(" }");
62674
63769
  return lines;
62675
63770
  }
63771
+ /** The per-invocation closure a handler calls for its serialized payload. */
63772
+ function payloadAccessorName(hookEventName) {
63773
+ return `${hookEventName.charAt(0).toLowerCase()}${hookEventName.slice(1)}Input`;
63774
+ }
63775
+ /** Lazily serialized payloads the handlers of one subscription use. */
63776
+ function buildPayloadLines(handlers) {
63777
+ const payloads = [...new Set(handlers.flatMap((h) => h.payload ? [h.payload] : []))];
63778
+ const lines = [];
63779
+ for (const payload of payloads) {
63780
+ const accessor = payloadAccessorName(payload);
63781
+ const extra = STDIN_PAYLOAD_EXTRA_FIELDS[payload] ?? "";
63782
+ const extraArgument = extra ? `, { ${extra} }` : "";
63783
+ lines.push(` let ${accessor}Cache: string | undefined;`);
63784
+ lines.push(` const ${accessor} = () => (${accessor}Cache ??= toolHookInput(${JSON.stringify(payload)}, event, ctx${extraArgument}));`);
63785
+ }
63786
+ return lines;
63787
+ }
63788
+ /**
63789
+ * The handler's parameter list. `ctx` is the second handler argument, so the
63790
+ * prompt gate and the payload builders (which read the session id and cwd)
63791
+ * name both.
63792
+ */
63793
+ function handlerParams({ handlers, readsEvent, isPromptGate }) {
63794
+ const usesPayload = handlers.some((h) => h.payload);
63795
+ if (isPromptGate || usesPayload) return "event, ctx";
63796
+ return readsEvent || handlers.some((h) => h.onlyOnError) ? "event" : "";
63797
+ }
62676
63798
  function buildSubscriptionLines(handlerGroups, dialect) {
62677
63799
  const lines = [];
62678
63800
  for (const [piEvent, handlers] of Object.entries(handlerGroups)) {
@@ -62682,13 +63804,17 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62682
63804
  const isSessionStopGate = blocking === "sessionStop";
62683
63805
  const collectsStopFailures = isSettleGate || isSessionStopGate;
62684
63806
  const usesToolName = PI_TOOL_EVENTS.has(piEvent) && handlers.some((h) => h.matcher);
62685
- const usesErrorFlag = handlers.some((h) => h.onlyOnError);
62686
63807
  const gatesOnAssistant = PI_ASSISTANT_MESSAGE_EVENTS.has(piEvent);
62687
- const params = isPromptGate ? "event, ctx" : usesToolName || usesErrorFlag || gatesOnAssistant || isPromptGate || collectsStopFailures ? "event" : "";
63808
+ const params = handlerParams({
63809
+ handlers,
63810
+ readsEvent: usesToolName || gatesOnAssistant || collectsStopFailures,
63811
+ isPromptGate
63812
+ });
62688
63813
  lines.push(` pi.on(${JSON.stringify(piEvent)}, async (${params}) => {`);
62689
63814
  if (gatesOnAssistant) lines.push(` if (event.message.role !== "assistant") return;`);
62690
63815
  if (isPromptGate) lines.push(` if (event.source === "extension") ${dialect.promptPassLine}`);
62691
63816
  if (collectsStopFailures) lines.push(" const stopHookFailures: unknown[] = [];");
63817
+ lines.push(...buildPayloadLines(handlers));
62692
63818
  for (const handler of handlers) lines.push(...buildCommandLines({
62693
63819
  handler,
62694
63820
  usesToolName,
@@ -62724,6 +63850,10 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62724
63850
  }
62725
63851
  return lines;
62726
63852
  }
63853
+ /** Whether a handler belongs to a tool event, where its matcher is tested. */
63854
+ function handlerGroupHasToolEvent(handlerGroups, handler) {
63855
+ return Object.entries(handlerGroups).some(([piEvent, handlers]) => PI_TOOL_EVENTS.has(piEvent) && handlers.includes(handler));
63856
+ }
62727
63857
  /**
62728
63858
  * Generate the rulesync-owned Pi extension (a TypeScript module with a
62729
63859
  * default-export factory receiving Pi's ExtensionAPI) that subscribes to the
@@ -62738,6 +63868,12 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62738
63868
  * command's output as feedback.
62739
63869
  * `postToolUse` and `postToolUseFailure` share Pi's `tool_result` event; the
62740
63870
  * latter's commands run only when `event.isError` is set.
63871
+ * Commands on the tool events receive Claude Code's hook input on stdin (see
63872
+ * `STDIN_PAYLOAD_EVENTS`), and a tool matcher is tested against both Pi's tool
63873
+ * name and its canonical Claude Code name. On `tool_call`, a command that exits
63874
+ * 0 with a JSON deny decision also denies the call, and one past its `timeout`
63875
+ * denies it unless the hook sets `failClosed: false`, mirroring the
63876
+ * OpenCode-style plugin.
62741
63877
  *
62742
63878
  * @see https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md
62743
63879
  */
@@ -62757,7 +63893,9 @@ function generatePiExtensionCode({ config, supportedEvents, eventMap, dialect =
62757
63893
  const hasPromptGate = Boolean(handlerGroups[PI_PROMPT_BLOCKING_EVENT]);
62758
63894
  const hasSettleGate = Boolean(handlerGroups[PI_SETTLE_BLOCKING_EVENT]);
62759
63895
  const hasSessionStopGate = Boolean(handlerGroups[OMP_SESSION_STOP_BLOCKING_EVENT]);
62760
- const needsBlockReasonHelper = Boolean(handlerGroups[PI_BLOCKING_EVENT]) || hasPromptGate || hasSettleGate || hasSessionStopGate;
63896
+ const needsToolHelpers = Object.values(handlerGroups).flat().some((h) => h.payload || h.matcher && handlerGroupHasToolEvent(handlerGroups, h));
63897
+ const hasToolGate = Boolean(handlerGroups[PI_BLOCKING_EVENT]);
63898
+ const needsBlockReasonHelper = hasToolGate || hasPromptGate || hasSettleGate || hasSessionStopGate;
62761
63899
  const lines = ["// Generated by rulesync. Do not edit manually."];
62762
63900
  if (subscriptionLines.length === 0) {
62763
63901
  lines.push("export default function () {}");
@@ -62767,34 +63905,33 @@ function generatePiExtensionCode({ config, supportedEvents, eventMap, dialect =
62767
63905
  const importedTypes = [
62768
63906
  ...hasSettleGate ? ["AgentBeforeSettleEvent", "AgentBeforeSettleEventResult"] : [],
62769
63907
  "ExtensionAPI",
62770
- ...hasPromptGate ? ["ExtensionContext"] : []
63908
+ ...hasPromptGate || needsToolHelpers ? ["ExtensionContext"] : []
62771
63909
  ].join(", ");
62772
- lines.push("import { exec } from \"node:child_process\";");
62773
- lines.push("import { promisify } from \"node:util\";");
63910
+ lines.push("import { spawn } from \"node:child_process\";");
63911
+ if (needsToolHelpers) {
63912
+ lines.push("import { homedir } from \"node:os\";");
63913
+ lines.push(dialect.pathResolverLines === OMP_PATH_RESOLVER_LINES ? "import { join as joinPath, resolve as resolvePath, win32 as win32Path } from \"node:path\";" : "import { join as joinPath, resolve as resolvePath } from \"node:path\";");
63914
+ lines.push("import { fileURLToPath } from \"node:url\";");
63915
+ }
62774
63916
  lines.push("");
62775
63917
  lines.push(`import type { ${importedTypes} } from ${JSON.stringify(dialect.typesPackage)};`);
62776
63918
  lines.push("");
62777
- lines.push("const run = promisify(exec);");
62778
- lines.push("");
62779
- if (needsBlockReasonHelper) {
62780
- lines.push(...BLOCK_REASON_HELPER_LINES);
62781
- lines.push("");
62782
- }
62783
- if (hasPromptGate) {
62784
- lines.push(...PROMPT_GATE_HELPER_LINES);
62785
- lines.push("");
62786
- }
62787
- if (hasSettleGate || hasSessionStopGate) {
62788
- lines.push(...STOP_HOOK_BLOCK_HELPER_LINES);
62789
- lines.push("");
62790
- }
62791
- if (hasSettleGate) {
62792
- lines.push(...STOP_HOOK_HELPER_LINES);
62793
- lines.push("");
62794
- }
63919
+ const helperBlocks = [
63920
+ [true, RUN_HELPER_LINES],
63921
+ [needsBlockReasonHelper, BLOCK_REASON_HELPER_LINES],
63922
+ [hasToolGate, TOOL_DECISION_HELPER_LINES],
63923
+ [needsToolHelpers, needsToolHelpers ? buildToolPayloadHelperLines(dialect) : []],
63924
+ [hasPromptGate, PROMPT_GATE_HELPER_LINES],
63925
+ [hasSettleGate || hasSessionStopGate, STOP_HOOK_BLOCK_HELPER_LINES],
63926
+ [hasSettleGate, STOP_HOOK_HELPER_LINES]
63927
+ ];
63928
+ for (const [included, block] of helperBlocks) if (included) lines.push(...block, "");
62795
63929
  lines.push("export default function (pi: ExtensionAPI) {");
62796
63930
  if (hasSettleGate) lines.push(" let stopHookContinued = false;");
62797
63931
  lines.push(...subscriptionLines);
63932
+ lines.push(" pi.on(\"session_shutdown\", async () => {");
63933
+ lines.push(" for (const kill of [...runningHookCommands]) kill();");
63934
+ lines.push(" });");
62798
63935
  lines.push("}");
62799
63936
  lines.push("");
62800
63937
  return lines.join("\n");
@@ -62857,6 +63994,162 @@ var OmpHooks = class OmpHooks extends ToolHooks {
62857
63994
  });
62858
63995
  }
62859
63996
  };
63997
+ // src/features/hooks/openbitfun-hooks.ts
63998
+ /**
63999
+ * Canonical (Claude Code) tool names whose OpenBitFun runtime name differs.
64000
+ * OpenBitFun's shell tool is `ExecCommand`; its own Claude-dialect skill hook
64001
+ * adapter maps `Bash` onto it, with the shell command in `tool_input.cmd`.
64002
+ * `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `WebSearch`, `Skill` and
64003
+ * `LS` share their names, so they need no entry.
64004
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/src/crates/execution/agent-runtime/src/skills/hooks.rs
64005
+ */
64006
+ const CANONICAL_TO_OPENBITFUN_TOOL_NAMES = { Bash: "ExecCommand" };
64007
+ const OPENBITFUN_TO_CANONICAL_TOOL_NAMES = Object.fromEntries(Object.entries(CANONICAL_TO_OPENBITFUN_TOOL_NAMES).map(([canonical, tool]) => [tool, canonical]));
64008
+ /**
64009
+ * OpenBitFun's built-in tool names (the default custom-agent tool sets in
64010
+ * `custom_agent.rs`, plus `LS`). Capitalized matcher names outside this set
64011
+ * are warned about on events that gate a tool call.
64012
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/src/crates/execution/agent-runtime/src/custom_agent.rs
64013
+ */
64014
+ const OPENBITFUN_TOOL_NAMES = /* @__PURE__ */ new Set([
64015
+ "Read",
64016
+ "Glob",
64017
+ "Grep",
64018
+ "LS",
64019
+ "Write",
64020
+ "Edit",
64021
+ "Delete",
64022
+ "ExecCommand",
64023
+ "WriteStdin",
64024
+ "ExecControl",
64025
+ "AgentSpawn",
64026
+ "AgentFork",
64027
+ "AgentSendInput",
64028
+ "AgentControl",
64029
+ "AgentList",
64030
+ "AgentWait",
64031
+ "ListModels",
64032
+ "Skill",
64033
+ "WebSearch",
64034
+ "WebFetch"
64035
+ ]);
64036
+ /**
64037
+ * Events whose hooks can deny a tool call, so a matcher that never matches
64038
+ * makes the guard fail open. The keys are canonical names, or OpenBitFun's own
64039
+ * names when the hook comes from the `openbitfun.hooks` override block.
64040
+ */
64041
+ const TOOL_GATING_EVENTS = /* @__PURE__ */ new Set([
64042
+ "preToolUse",
64043
+ "permissionRequest",
64044
+ "PreToolUse",
64045
+ "PermissionRequest"
64046
+ ]);
64047
+ function canonicalToOpenbitfunMatcher({ matcher, eventName, warn }) {
64048
+ const translated = replaceMatcherNames(matcher, CANONICAL_TO_OPENBITFUN_TOOL_NAMES);
64049
+ if (TOOL_GATING_EVENTS.has(eventName)) {
64050
+ const unknown = capitalizedMatcherNames(translated).filter((name) => !OPENBITFUN_TOOL_NAMES.has(name));
64051
+ if (unknown.length > 0) warn(`${unknown.map((name) => quoteValueForWarning(name)).join(", ")} in the "${eventName}" matcher ${quoteValueForWarning(matcher)} is not an OpenBitFun built-in tool, so it is written as-is and will likely never match there, and the hook will not run for that tool.`);
64052
+ }
64053
+ return translated;
64054
+ }
64055
+ function openbitfunToCanonicalMatcher(matcher) {
64056
+ return replaceMatcherNames(matcher, OPENBITFUN_TO_CANONICAL_TOOL_NAMES);
64057
+ }
64058
+ /**
64059
+ * Why OpenBitFun would skip a generated handler, or `undefined` when it runs
64060
+ * it. OpenBitFun's `parse_handler` treats a command handler whose `timeout` is
64061
+ * not a positive integer as invalid and skips that handler.
64062
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/src/crates/execution/agent-runtime/src/native_hooks/settings.rs
64063
+ */
64064
+ function describeRejectedOpenbitfunHandler(handler) {
64065
+ const { timeout } = handler;
64066
+ if (timeout !== void 0 && (typeof timeout !== "number" || !Number.isSafeInteger(timeout) || timeout <= 0)) return `its "timeout" ${JSON.stringify(timeout) ?? String(timeout)} is not a positive integer, so OpenBitFun would skip it as invalid`;
64067
+ }
64068
+ /**
64069
+ * OpenBitFun implements the Codex hook contract: the same `hooks.json`
64070
+ * document, handler fields and matcher semantics (regexes anchored to the
64071
+ * whole tool name). It differs in the events it dispatches, in running only
64072
+ * `type: "command"` handlers (`prompt` and `agent` handlers are parsed but
64073
+ * skipped), in its runtime tool names (`ExecCommand` for `Bash`), and in the
64074
+ * handler fields it reads: `command`, `commandWindows`, `timeout` and
64075
+ * `statusMessage` only, so Codex's `async` and `additionalContextLimit` are
64076
+ * not forwarded.
64077
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/docs/features/agent-hooks.md
64078
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/src/crates/execution/agent-runtime/src/native_hooks/settings.rs
64079
+ */
64080
+ const OPENBITFUN_CONVERTER_CONFIG = {
64081
+ ...CODEXCLI_CONVERTER_CONFIG,
64082
+ supportedEvents: OPENBITFUN_HOOK_EVENTS,
64083
+ canonicalToToolEventNames: CANONICAL_TO_OPENBITFUN_EVENT_NAMES,
64084
+ toolToCanonicalEventNames: OPENBITFUN_TO_CANONICAL_EVENT_NAMES,
64085
+ supportedHookTypes: /* @__PURE__ */ new Set(["command"]),
64086
+ numberPassthroughFields: [],
64087
+ booleanPassthroughFields: [],
64088
+ matcherTranslation: {
64089
+ toTool: canonicalToOpenbitfunMatcher,
64090
+ toCanonical: openbitfunToCanonicalMatcher
64091
+ }
64092
+ };
64093
+ /**
64094
+ * Hooks generator for OpenBitFun: a Codex-shaped `hooks.json` at
64095
+ * `.openbitfun/config/hooks.json` (project) and `<user root>/config/hooks.json`
64096
+ * (global; see {@link openbitfunGlobalConfigDir}). Both layers are additive.
64097
+ *
64098
+ * Project hooks are off by default in OpenBitFun: they only run once the
64099
+ * `app.hooks.project_hooks_enabled` setting is turned on.
64100
+ *
64101
+ * @see https://github.com/openBitFun/OpenBitFun/blob/main/docs/features/agent-hooks.md
64102
+ */
64103
+ var OpenbitfunHooks = class OpenbitfunHooks extends ToolHooks {
64104
+ static getSettablePaths({ global = false } = {}) {
64105
+ return {
64106
+ relativeDirPath: global ? openbitfunGlobalConfigDir() : OPENBITFUN_CONFIG_DIR_PATH,
64107
+ relativeFilePath: OPENBITFUN_HOOKS_FILE_NAME
64108
+ };
64109
+ }
64110
+ static async fromRulesyncHooks({ outputRoot = process.cwd(), rulesyncHooks, validate = true, global = false, preserveUnowned = false, logger }) {
64111
+ if (global) warnOpenbitfunXdgOverride({
64112
+ kind: "config",
64113
+ logger
64114
+ });
64115
+ const paths = OpenbitfunHooks.getSettablePaths({ global });
64116
+ const { fileContent, owned } = await buildCodexStyleHooksFile({
64117
+ outputRoot,
64118
+ relativeDirPath: paths.relativeDirPath,
64119
+ relativeFilePath: paths.relativeFilePath,
64120
+ rulesyncHooks,
64121
+ toolOverrideHooks: rulesyncHooks.getJson().openbitfun?.hooks,
64122
+ converterConfig: OPENBITFUN_CONVERTER_CONFIG,
64123
+ toolLabel: "OpenBitFun",
64124
+ describeRejected: describeRejectedOpenbitfunHandler,
64125
+ preserveUnowned,
64126
+ logger
64127
+ });
64128
+ return new OpenbitfunHooks({
64129
+ outputRoot,
64130
+ relativeDirPath: paths.relativeDirPath,
64131
+ relativeFilePath: paths.relativeFilePath,
64132
+ fileContent,
64133
+ ownedHookRefs: preserveUnowned ? owned : void 0,
64134
+ validate
64135
+ });
64136
+ }
64137
+ toRulesyncHooks({ logger } = {}) {
64138
+ const parsed = this.parseFileContentOrThrow({
64139
+ displayName: "OpenBitFun",
64140
+ parse: (fileContent) => JSON.parse(fileContent)
64141
+ });
64142
+ return this.toRulesyncHooksDefault({ fileContent: codexStyleHooksToRulesyncContent({
64143
+ parsed,
64144
+ converterConfig: OPENBITFUN_CONVERTER_CONFIG,
64145
+ overrideKey: "openbitfun",
64146
+ logger
64147
+ }) });
64148
+ }
64149
+ static supportsPreserveUnowned() {
64150
+ return true;
64151
+ }
64152
+ };
62860
64153
  // src/features/hooks/opencodev1-hooks.ts
62861
64154
  /**
62862
64155
  * Hooks generator for **OpenCode V1** (OpenCode 1.x). OpenCode 2.x does not
@@ -64937,6 +66230,16 @@ const toolHooksFactories = /* @__PURE__ */ new Map([
64937
66230
  ...converterCapabilities(CODEXCLI_CONVERTER_CONFIG),
64938
66231
  supportsMatcher: true
64939
66232
  }],
66233
+ ["openbitfun", {
66234
+ class: OpenbitfunHooks,
66235
+ meta: {
66236
+ supportsProject: true,
66237
+ supportsGlobal: true,
66238
+ supportsImport: true
66239
+ },
66240
+ ...converterCapabilities(OPENBITFUN_CONVERTER_CONFIG),
66241
+ supportsMatcher: true
66242
+ }],
64940
66243
  ["commandcode", {
64941
66244
  class: CommandcodeHooks,
64942
66245
  meta: {
@@ -65219,7 +66522,13 @@ const toolHooksFactories = /* @__PURE__ */ new Map([
65219
66522
  },
65220
66523
  ...converterCapabilities(BobHooks.getConverterConfig()),
65221
66524
  supportsMatcher: true,
65222
- matcherEvents: ["preToolUse", "postToolUse"]
66525
+ matcherEvents: BOB_MATCHER_HOOK_EVENTS,
66526
+ dropsUnknownOverrideEvents: true,
66527
+ overrideOnlyEvents: BOB_NATIVE_HOOK_EVENTS,
66528
+ overrideOptIn: {
66529
+ events: BOB_OPT_IN_HOOK_EVENTS,
66530
+ note: "They need Bob Shell 2.1.0 or later, and an older Bob Shell ignores the whole hooks block of a settings file that names them."
66531
+ }
65223
66532
  }],
65224
66533
  ["continue", {
65225
66534
  class: ContinueHooks,
@@ -65545,12 +66854,26 @@ var HooksProcessor = class extends FeatureProcessor {
65545
66854
  ...overrideHooks
65546
66855
  };
65547
66856
  {
65548
- const skipped = unsupportedEventNames({
66857
+ const optInEvents = factory.overrideOptIn?.events ?? {};
66858
+ const isOptIn = (e) => Object.hasOwn(optInEvents, e);
66859
+ const overrideKeys = new Set(Object.keys(overrideHooks));
66860
+ const skippedEvents = unsupportedEventNames({
65549
66861
  factory,
65550
66862
  sharedHooks,
65551
66863
  effectiveHooks
65552
66864
  });
66865
+ const skipped = skippedEvents.filter((e) => !isOptIn(e));
66866
+ const optIn = skippedEvents.filter(isOptIn).filter((e) => Object.hasOwn(sharedHooks, e) && !overrideKeys.has(optInEvents[e] ?? ""));
66867
+ const misnamed = skippedEvents.filter(isOptIn).filter((e) => overrideKeys.has(e));
65553
66868
  if (skipped.length > 0) this.logger.warn(`Skipped hook event(s) for ${this.toolTarget} (not supported): ${skipped.join(", ")}`);
66869
+ if (optIn.length > 0) {
66870
+ const nativeNames = optIn.map((e) => optInEvents[e]).join(", ");
66871
+ this.logger.warn(`Skipped hook event(s) for ${this.toolTarget}: ${optIn.join(", ")}. ${factory.overrideOptIn?.note} To opt in, author them under the "${overrideKey}.hooks" override with the native name(s) ${nativeNames}.`);
66872
+ }
66873
+ if (misnamed.length > 0) {
66874
+ const nativeNames = misnamed.map((e) => optInEvents[e]).join(", ");
66875
+ this.logger.warn(`Skipped "${overrideKey}.hooks" key(s) for ${this.toolTarget}: ${misnamed.join(", ")}. Use the native name(s) ${nativeNames} instead.`);
66876
+ }
65554
66877
  }
65555
66878
  {
65556
66879
  const supportedHookTypes = new Set(factory.supportedHookTypes);
@@ -73510,7 +74833,8 @@ const HERMES_OPAQUE_MAPPING_KEYS = [
73510
74833
  * alias — `auth` (`oauth` for OAuth 2.1/PKCE), mTLS `client_cert` (string PEM
73511
74834
  * path, or `[cert, key]`/`[cert, key, password]` list) and `client_key`,
73512
74835
  * `connect_timeout` (seconds), `supports_parallel_tool_calls`, `protocol`,
73513
- * `lazy`, `events` (see {@link copyHermesBoolLikeFields}), `keepalive_interval`,
74836
+ * `lazy`, `events` (see {@link copyHermesBoolLikeFields}), `single_instance`,
74837
+ * `keepalive_interval`,
73514
74838
  * `elicitation`, `trust`, `identity_header`, and
73515
74839
  * the cost keys (see {@link copyHermesCostFields}) —
73516
74840
  * verbatim from `source` to `target`. Field names are identical on both sides
@@ -73561,6 +74885,10 @@ function copyHermesAdvancedFields(source, target, logger) {
73561
74885
  target.skip_preflight = source.skip_preflight;
73562
74886
  copied = true;
73563
74887
  }
74888
+ if (typeof source.single_instance === "boolean") {
74889
+ target.single_instance = source.single_instance;
74890
+ copied = true;
74891
+ }
73564
74892
  if (typeof source.keepalive_interval === "number") {
73565
74893
  target.keepalive_interval = source.keepalive_interval;
73566
74894
  copied = true;
@@ -84152,7 +85480,7 @@ function buildVscodeCommandLists({ rules, toolLabel, logger, prefixSemantics = "
84152
85480
  };
84153
85481
  }
84154
85482
  // src/features/permissions/bob-permissions.ts
84155
- const TOOL_LABEL = "IBM Bob";
85483
+ const TOOL_LABEL$1 = "IBM Bob";
84156
85484
  /** The top-level settings key holding Bob's auto-approval configuration. */
84157
85485
  const APPROVAL_KEY$1 = "approval";
84158
85486
  /** The top-level settings key holding Bob's per-feature auto-approve toggles. */
@@ -84234,7 +85562,7 @@ function warnAboutSkippedCategories({ permission, bashStated, authorsGroupSwitch
84234
85562
  if (skipped.length === 0) return;
84235
85563
  const names = skipped.map((category) => `'${category}'`).join(", ");
84236
85564
  const hint = authorsGroupSwitches ? "" : ` ${GROUP_SWITCH_HINT}`;
84237
- warnWithFallback(logger, bashStated ? `${TOOL_LABEL} only models shell-command permissions (${SURFACE_LABEL}); ${names} allow rules cannot be represented and were skipped.${hint}` : `${TOOL_LABEL} only models shell-command permissions (${SURFACE_LABEL}), and .rulesync/permissions.jsonc states no 'bash' category, so ${names} ${skipped.length === 1 ? "was" : "were"} skipped and the command lists were left untouched.${hint}`);
85565
+ warnWithFallback(logger, bashStated ? `${TOOL_LABEL$1} only models shell-command permissions (${SURFACE_LABEL}); ${names} allow rules cannot be represented and were skipped.${hint}` : `${TOOL_LABEL$1} only models shell-command permissions (${SURFACE_LABEL}), and .rulesync/permissions.jsonc states no 'bash' category, so ${names} ${skipped.length === 1 ? "was" : "were"} skipped and the command lists were left untouched.${hint}`);
84238
85566
  }
84239
85567
  /**
84240
85568
  * Warn about what the `bob` override writes that Bob does not document: an
@@ -84254,7 +85582,7 @@ function warnAboutUndocumentedSettings({ override, logger }) {
84254
85582
  ...outsideWorkspace.length > 0 ? [`'enableOutsideWorkspace' for group(s) ${quoteAll(outsideWorkspace)}`] : []
84255
85583
  ];
84256
85584
  if (parts.length === 0) return;
84257
- warnWithFallback(logger, `${TOOL_LABEL} permissions: the bob override sets ${parts.join("; ")}, which Bob does not document; they were written as authored. Bob documents the groups ${quoteAll(BOB_PERMISSION_GROUP_IDS)}, the '${AUTO_APPROVE_KEY}' toggle(s) ${quoteAll(BOB_AUTO_APPROVE_KEYS)}, and 'enableOutsideWorkspace' for the '${OUTSIDE_WORKSPACE_GROUP_ID}' group only.`);
85585
+ warnWithFallback(logger, `${TOOL_LABEL$1} permissions: the bob override sets ${parts.join("; ")}, which Bob does not document; they were written as authored. Bob documents the groups ${quoteAll(BOB_PERMISSION_GROUP_IDS)}, the '${AUTO_APPROVE_KEY}' toggle(s) ${quoteAll(BOB_AUTO_APPROVE_KEYS)}, and 'enableOutsideWorkspace' for the '${OUTSIDE_WORKSPACE_GROUP_ID}' group only.`);
84258
85586
  }
84259
85587
  /**
84260
85588
  * Name what the `bob` override newly auto-approves. The settings file is Bob's
@@ -84273,7 +85601,7 @@ function warnAboutNewAutoApprovals({ settings, override, filePath, logger }) {
84273
85601
  ...Object.entries(override?.autoApprove ?? {}).filter(([key, value]) => value === true && existingAutoApprove[key] !== true).map(([key]) => quoteValueForWarning(`${AUTO_APPROVE_KEY}.${key}`))
84274
85602
  ]);
84275
85603
  if (added.size === 0) return;
84276
- warnWithFallback(logger, `${TOOL_LABEL} permissions: the bob override now auto-approves ${[...added].join(", ")} in ${filePath}, Bob's user settings, so this applies to every project on this machine. Check it if .rulesync/permissions.jsonc arrived with a repository you cloned.`);
85604
+ warnWithFallback(logger, `${TOOL_LABEL$1} permissions: the bob override now auto-approves ${[...added].join(", ")} in ${filePath}, Bob's user settings, so this applies to every project on this machine. Check it if .rulesync/permissions.jsonc arrived with a repository you cloned.`);
84277
85605
  }
84278
85606
  /**
84279
85607
  * Split the canonical `bash` rules — plus the restricting rules of the
@@ -84290,7 +85618,7 @@ function buildBobCommandLists({ permission, logger }) {
84290
85618
  normalizePattern: widenToPrefixGlob$1
84291
85619
  });
84292
85620
  warnAboutUnwrittenCommandRules({
84293
- toolLabel: TOOL_LABEL,
85621
+ toolLabel: TOOL_LABEL$1,
84294
85622
  surfaceLabel: SURFACE_LABEL,
84295
85623
  foreignRestrictingCategories,
84296
85624
  shadowedAllowPatterns,
@@ -84305,7 +85633,7 @@ function buildBobCommandLists({ permission, logger }) {
84305
85633
  for (const pattern of deny) lists[pattern] = "deny";
84306
85634
  return buildVscodeCommandLists({
84307
85635
  rules: lists,
84308
- toolLabel: TOOL_LABEL,
85636
+ toolLabel: TOOL_LABEL$1,
84309
85637
  logger,
84310
85638
  prefixSemantics: "documented-prefix"
84311
85639
  });
@@ -84477,7 +85805,7 @@ var BobPermissions = class BobPermissions extends ToolPermissions {
84477
85805
  const rules = importVscodeCommandLists({
84478
85806
  allowed: toStringArray$1(entry?.approvedCommands),
84479
85807
  denied: toStringArray$1(entry?.deniedCommands),
84480
- toolLabel: TOOL_LABEL,
85808
+ toolLabel: TOOL_LABEL$1,
84481
85809
  logger,
84482
85810
  prefixSemantics: "documented-prefix"
84483
85811
  });
@@ -85274,6 +86602,7 @@ const CLAUDECODE_UNHONORED_KEY_SOURCES = {
85274
86602
  disableMobileSimulatorTools: "managed settings",
85275
86603
  disableRemotePreviewScripts: "managed settings",
85276
86604
  disableSideloadFlags: "managed settings",
86605
+ enforceAnthropicSignIn: "managed settings",
85277
86606
  externalEditorContext: "~/.claude.json",
85278
86607
  forceRemoteSettingsRefresh: "managed settings",
85279
86608
  gatewayInternalNetworks: "managed settings",
@@ -85426,12 +86755,14 @@ const CLAUDECODE_ENV_IGNORED_IN_EVERY_FILE = /* @__PURE__ */ new Set([
85426
86755
  "CLAUDE_CODE_DISABLE_MOUNTED_DRIVE_RM_PROMPT",
85427
86756
  "CLAUDE_CODE_DISABLE_POWERSHELL_CMD_RM_DENY",
85428
86757
  "CLAUDE_CODE_DISABLE_SUBSTITUTION_RM_PROMPT",
86758
+ "CLAUDE_CODE_DISABLE_ULTRAREVIEW_TRUST_CHECK",
85429
86759
  "CLAUDE_CODE_EVEN_MORE_DANGEROUSLY_SKIP_PERMISSIONS",
85430
86760
  "CLAUDE_CODE_MESSAGING_SOCKET",
85431
86761
  "CLAUDE_CODE_MESSAGING_TOKEN",
85432
86762
  "CLAUDE_CODE_PROJECT_DIR_NAME",
85433
86763
  "CLAUDE_CODE_REMOTE",
85434
86764
  "CLAUDE_CODE_RESTRICTED",
86765
+ "CLAUDE_CODE_STRICT_INLINE_SHELL_RM_PROMPT",
85435
86766
  "CLAUDE_CODE_WARN_DISK_FREE_GIB",
85436
86767
  "CLAUDE_CODE_WARN_MEMORY_FREE_GIB"
85437
86768
  ]);
@@ -85443,6 +86774,13 @@ const CLAUDECODE_ENV_IGNORED_IN_EVERY_FILE = /* @__PURE__ */ new Set([
85443
86774
  * dialog, and whether it processes attachments or expands `@` file mentions,
85444
86775
  * and the screen reader (`CLAUDE_AX_*`) variables. Claude Code drops them there, so they are skipped at project scope and emitted only under `--global`.
85445
86776
  *
86777
+ * `OTEL_RESOURCE_INCLUDE_HOST` (Claude Code v2.1.326+) adds the machine's name
86778
+ * and ID to telemetry, so it sits with the telemetry group. The reference lists
86779
+ * `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE` separately: Code Mode follows it only
86780
+ * from the shell, user settings or a `--settings` file, and a project `0` does
86781
+ * not keep Code Mode off either, so any project value is skipped while user
86782
+ * settings (`--global`) still honor it.
86783
+ *
85446
86784
  * Only the names the settings reference lists are covered; its directory,
85447
86785
  * Windows and sign-in groups are introduced with "such as", so an unlisted member of those
85448
86786
  * families is still written. Windows variable names are case-insensitive, so
@@ -85461,6 +86799,7 @@ const CLAUDECODE_ENV_PROJECT_IGNORED_NAMES = /* @__PURE__ */ new Set([
85461
86799
  "CLAUDE_CODE_DISABLE_FILE_MENTIONS",
85462
86800
  "CLAUDE_CODE_ENABLE_TELEMETRY",
85463
86801
  "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
86802
+ "CLAUDE_CODE_EXPERIMENTAL_CODE_MODE",
85464
86803
  "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
85465
86804
  "CLAUDE_CODE_OAUTH_SCOPES",
85466
86805
  "CLAUDE_CODE_OAUTH_TOKEN",
@@ -85479,6 +86818,7 @@ const CLAUDECODE_ENV_PROJECT_IGNORED_NAMES = /* @__PURE__ */ new Set([
85479
86818
  "OTEL_EXPORTER_PROMETHEUS_PORT",
85480
86819
  "OTEL_LOG_ASSISTANT_RESPONSES",
85481
86820
  "OTEL_LOG_RAW_API_BODIES",
86821
+ "OTEL_RESOURCE_INCLUDE_HOST",
85482
86822
  "TEMP",
85483
86823
  "TMP",
85484
86824
  "TMPDIR"
@@ -90675,9 +92015,9 @@ function createSafeCommandShadowTest(permission) {
90675
92015
  });
90676
92016
  const withSeparator = (spellings) => spellings.flatMap((spelling) => [spelling, `${spelling} --*`]);
90677
92017
  const wrapped = (base) => CRUSH_COMMAND_PREFIXES.map((prefix) => `${prefix}*${base}`);
90678
- return (line) => uniq$11([...withSeparator([line, ...wrapped(line)]).flatMap((spelling) => test(spelling)), ...withSeparator([line.toLowerCase(), ...wrapped(line.toLowerCase())]).flatMap((spelling) => testNormalized(spelling).map((pattern) => originalOf.get(pattern) ?? pattern))]);
92018
+ return (line) => uniq$12([...withSeparator([line, ...wrapped(line)]).flatMap((spelling) => test(spelling)), ...withSeparator([line.toLowerCase(), ...wrapped(line.toLowerCase())]).flatMap((spelling) => testNormalized(spelling).map((pattern) => originalOf.get(pattern) ?? pattern))]);
90679
92019
  }
90680
- function uniq$11(values) {
92020
+ function uniq$12(values) {
90681
92021
  return [...new Set(values)];
90682
92022
  }
90683
92023
  function stringList(value) {
@@ -90812,8 +92152,8 @@ var CrushPermissions = class CrushPermissions extends ToolPermissions {
90812
92152
  });
90813
92153
  const preservedAllowed = (isStringArray(existingPermissions?.["allowed_tools"]) ? existingPermissions[CRUSH_ALLOWED_TOOLS_KEY] : []).filter((entry) => entry.includes(":") || !managedToolNames.has(entry));
90814
92154
  const preservedDisabled = (isStringArray(existingOptions?.["disabled_tools"]) ? existingOptions[CRUSH_DISABLED_TOOLS_KEY] : []).filter((entry) => !managedToolNames.has(entry));
90815
- const allowedList = uniq$11([...preservedAllowed, ...generated.allowed]);
90816
- const disabledList = uniq$11([...preservedDisabled, ...generated.disabled]);
92155
+ const allowedList = uniq$12([...preservedAllowed, ...generated.allowed]);
92156
+ const disabledList = uniq$12([...preservedDisabled, ...generated.disabled]);
90817
92157
  const permissionsHasContent = allowedList.length > 0 || commands.safe.length > 0 || commands.blocked.length > 0;
90818
92158
  const patch = {};
90819
92159
  if (permissionsHasContent || existingPermissions !== void 0) patch[CRUSH_PERMISSIONS_KEY] = {
@@ -90867,7 +92207,7 @@ function rebuildCrushCommandLists({ config, existingPermissions, logger }) {
90867
92207
  shadowTest,
90868
92208
  logger
90869
92209
  });
90870
- const safe = uniq$11([...preserveSafeCommands({
92210
+ const safe = uniq$12([...preserveSafeCommands({
90871
92211
  existing: stringList(existingPermissions?.[CRUSH_SAFE_COMMANDS_KEY]),
90872
92212
  bashRules,
90873
92213
  shadowTest,
@@ -90889,7 +92229,7 @@ function rebuildCrushCommandLists({ config, existingPermissions, logger }) {
90889
92229
  }
90890
92230
  return {
90891
92231
  safe,
90892
- blocked: uniq$11([...existingBlocked, ...blocked])
92232
+ blocked: uniq$12([...existingBlocked, ...blocked])
90893
92233
  };
90894
92234
  }
90895
92235
  /**
@@ -91004,8 +92344,8 @@ function convertRulesyncToCrushLists({ config, logger }) {
91004
92344
  else if (catchAllAction === "deny") lists.disabled.push(toolName);
91005
92345
  }
91006
92346
  return {
91007
- allowed: uniq$11(lists.allowed),
91008
- disabled: uniq$11(lists.disabled)
92347
+ allowed: uniq$12(lists.allowed),
92348
+ disabled: uniq$12(lists.disabled)
91009
92349
  };
91010
92350
  }
91011
92351
  /**
@@ -91064,8 +92404,8 @@ function convertBashCommandRules({ bashRules, shadowTest, logger }) {
91064
92404
  lists.blocked.push(name);
91065
92405
  }
91066
92406
  return {
91067
- safe: uniq$11(lists.safe),
91068
- blocked: uniq$11(lists.blocked)
92407
+ safe: uniq$12(lists.safe),
92408
+ blocked: uniq$12(lists.blocked)
91069
92409
  };
91070
92410
  }
91071
92411
  /**
@@ -92990,6 +94330,263 @@ function convertFactorydroidToRulesyncPermissions({ allow, deny }) {
92990
94330
  for (const pattern of deny) bash[pattern] = "deny";
92991
94331
  return { permission: Object.keys(bash).length > 0 ? { bash } : {} };
92992
94332
  }
94333
+ // src/features/permissions/gitlabduo-permissions.ts
94334
+ const GITLABDUO_GLOBAL_ONLY_MESSAGE = "GitLab Duo CLI reads the permissions setting only from the user settings file; use --global to sync ~/.gitlab/duo/settings.json";
94335
+ const TOOL_LABEL = "GitLab Duo CLI";
94336
+ const PERMISSIONS_KEY = "permissions";
94337
+ /** The Duo tool that runs a shell command; the only one rulesync writes statements for. */
94338
+ const COMMAND_TOOL_NAME = "run_command";
94339
+ /** The server refuses a pattern longer than this (`MAX_PATTERN_LENGTH`). */
94340
+ const MAX_PATTERN_LENGTH = 256;
94341
+ /**
94342
+ * Characters a written pattern must not hold:
94343
+ * - `; & | < > $ \` ( ) { }` and line breaks are shell metacharacters the
94344
+ * server refuses in a command-tool pattern.
94345
+ * - Quotes and the backslash are taken off by the shell-style word split the
94346
+ * server reads a pattern through, so the pattern would be matched as
94347
+ * something other than what it says.
94348
+ * - `[` and `]` start an `fnmatch` character class inside a token, which the
94349
+ * canonical glob does not read the same way.
94350
+ */
94351
+ const UNSUPPORTED_PATTERN_CHARACTERS = /[;&|<>$`(){}\n\r'"\\[\]]/;
94352
+ /** Quotes and the backslash escape, which a shell-style word split takes off. */
94353
+ const SHELL_QUOTING_CHARACTERS = /['"\\]/g;
94354
+ /** A canonical pattern may spell "any arguments" as a trailing `:*` (`git:*`). */
94355
+ const TRAILING_ARGUMENT_WILDCARD = /:\*$/;
94356
+ /** Glob characters that make a Duo pattern match more than its literal spelling. */
94357
+ const GLOB_CHARACTERS = /[*?[\]]/;
94358
+ /**
94359
+ * Permissions adapter for GitLab Duo CLI.
94360
+ *
94361
+ * Duo CLI 10.5.0 reads a `permissions` array of
94362
+ * `{ action, resource, effect }` statements from the managed settings file and
94363
+ * the user's `~/.gitlab/duo/settings.json`. The project files
94364
+ * (`.gitlab/duo/settings.json`, `.gitlab/duo/settings.local.json`) are
94365
+ * deliberately not read for it, so this surface is **global only**.
94366
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/definitions.ts
94367
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/tool_permissions.ts
94368
+ *
94369
+ * Only `allow` is enforced: each allow statement is submitted to the GitLab
94370
+ * instance as a session pattern approval when a session starts. `ask` and
94371
+ * `deny` statements are accepted but only logged. rulesync therefore writes
94372
+ * allow statements only, and never one that could auto-approve something the
94373
+ * canonical file restricts:
94374
+ *
94375
+ * - Only canonical `bash` `allow` rules are written, as
94376
+ * `{ action: "run_command", resource: <pattern>, effect: "allow" }`. Other
94377
+ * categories have no Duo spelling that is known to match no wider than the
94378
+ * canonical rule (the server matches other tools' patterns against their raw
94379
+ * JSON arguments), so their allow rules are skipped with a warning.
94380
+ * - Every `deny` and `ask` rule under `bash` or the all-tools `*` category
94381
+ * withholds the allow rules that could match the same command, because Duo
94382
+ * cannot enforce the restriction itself. A deny is also reported: the command
94383
+ * is asked about, not blocked.
94384
+ * - The GitLab server matches a command-tool pattern token by token
94385
+ * (`CommandPatternMatcher`): a literal token must match exactly, `*` is one
94386
+ * token that does not start with `-`, and a token holding a glob is matched
94387
+ * on its own. That is never wider than the canonical glob, where `*` spans
94388
+ * any characters. A trailing `:*` is written as ` *`. A pattern the server
94389
+ * refuses (a lone `*`, `**`, shell metacharacters, more than 256 characters)
94390
+ * or would read differently (quotes, escapes, character classes) is skipped
94391
+ * with a warning.
94392
+ * @see https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/models/ai/duo_workflows/command_pattern_matcher.rb
94393
+ *
94394
+ * On generate, the statements rulesync owns — those for `run_command` — are
94395
+ * replaced, and every other statement and key of the file is kept, with the
94396
+ * comments outside the `permissions` array (the array is rewritten whole).
94397
+ * On import, `run_command` statements come back under `bash`. An allow is
94398
+ * skipped when its resource holds a glob, which the canonical glob would read
94399
+ * more widely than Duo does, or when the server would refuse it, since it
94400
+ * approves nothing in Duo but would approve the command for other tools.
94401
+ */
94402
+ var GitlabduoPermissions = class GitlabduoPermissions extends ToolPermissions {
94403
+ constructor(params) {
94404
+ super({
94405
+ ...params,
94406
+ fileContent: params.fileContent ?? "{}"
94407
+ });
94408
+ }
94409
+ /**
94410
+ * `settings.json` holds every Duo CLI setting, so rulesync never brings it
94411
+ * into existence just to hold nothing.
94412
+ */
94413
+ shouldSkipCreationWhenPayloadEmpty() {
94414
+ return true;
94415
+ }
94416
+ static getSettablePaths(_options = {}) {
94417
+ return {
94418
+ relativeDirPath: GITLABDUO_DIR,
94419
+ relativeFilePath: GITLABDUO_SETTINGS_FILE_NAME
94420
+ };
94421
+ }
94422
+ static async fromFile({ outputRoot = process.cwd(), validate = true, global = false }) {
94423
+ if (!global) throw new Error(GITLABDUO_GLOBAL_ONLY_MESSAGE);
94424
+ const paths = GitlabduoPermissions.getSettablePaths({ global });
94425
+ const fileContent = await readFileContentOrNull((0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath)) ?? "{}";
94426
+ return new GitlabduoPermissions({
94427
+ outputRoot,
94428
+ relativeDirPath: paths.relativeDirPath,
94429
+ relativeFilePath: paths.relativeFilePath,
94430
+ fileContent,
94431
+ validate,
94432
+ global: true
94433
+ });
94434
+ }
94435
+ static async fromRulesyncPermissions({ outputRoot = process.cwd(), rulesyncPermissions, logger, global = false }) {
94436
+ if (!global) throw new Error(GITLABDUO_GLOBAL_ONLY_MESSAGE);
94437
+ const paths = GitlabduoPermissions.getSettablePaths({ global });
94438
+ const filePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
94439
+ const existingContent = await readFileContentOrNull(filePath) ?? "";
94440
+ const baseContent = existingContent.trim() === "" ? "{}" : existingContent;
94441
+ const existing = parseSettings({
94442
+ content: baseContent,
94443
+ filePath
94444
+ })[PERMISSIONS_KEY];
94445
+ const generated = convertRulesyncToGitlabduoStatements({
94446
+ config: rulesyncPermissions.getJson(),
94447
+ logger
94448
+ });
94449
+ let fileContent = baseContent;
94450
+ if (existing !== void 0 && !Array.isArray(existing)) warnWithFallback(logger, `${TOOL_LABEL}: '${PERMISSIONS_KEY}' in ${filePath} is not an array, so it was left untouched rather than overwritten, and no rule was written.`);
94451
+ else {
94452
+ const statements = [...(existing ?? []).filter((statement) => !(isPlainObject(statement) && statement.action === COMMAND_TOOL_NAME)), ...generated];
94453
+ if (statements.length > 0 || existing !== void 0) {
94454
+ const edits = (0, jsonc_parser.modify)(baseContent, [PERMISSIONS_KEY], statements.length > 0 ? statements : void 0, { formattingOptions: {
94455
+ insertSpaces: true,
94456
+ tabSize: 2
94457
+ } });
94458
+ fileContent = (0, jsonc_parser.applyEdits)(baseContent, edits);
94459
+ }
94460
+ }
94461
+ return new GitlabduoPermissions({
94462
+ outputRoot,
94463
+ relativeDirPath: paths.relativeDirPath,
94464
+ relativeFilePath: paths.relativeFilePath,
94465
+ fileContent,
94466
+ validate: true,
94467
+ global: true
94468
+ });
94469
+ }
94470
+ toRulesyncPermissions() {
94471
+ const selfPath = (0, node_path.join)(this.getRelativeDirPath(), this.getRelativeFilePath());
94472
+ const raw = parseSettings({
94473
+ content: this.getFileContent() || "{}",
94474
+ filePath: selfPath
94475
+ })[PERMISSIONS_KEY];
94476
+ const statements = Array.isArray(raw) ? raw : [];
94477
+ if (raw !== void 0 && !Array.isArray(raw)) warnWithFallback(void 0, `${TOOL_LABEL} ignores '${PERMISSIONS_KEY}' unless it is an array, so nothing was imported from ${selfPath}.`);
94478
+ const bash = {};
94479
+ const skippedAllows = [];
94480
+ for (const statement of statements) {
94481
+ if (!isDuoPermissionStatement(statement) || statement.action !== COMMAND_TOOL_NAME) continue;
94482
+ const { resource, effect } = statement;
94483
+ if (effect === "allow" && (GLOB_CHARACTERS.test(resource) || toGitlabduoCommandResource(resource) !== resource)) {
94484
+ skippedAllows.push(resource);
94485
+ continue;
94486
+ }
94487
+ const previous = bash[resource];
94488
+ if (previous === void 0 || rank(effect) > rank(previous)) bash[resource] = effect;
94489
+ }
94490
+ if (skippedAllows.length > 0) warnWithFallback(void 0, `The run_command allow statement(s) for ${(0, es_toolkit.uniq)(skippedAllows).join(", ")} in ${selfPath} were not imported: a glob matches more as a canonical pattern than in ${TOOL_LABEL} (where '*' is one argument that is not a flag), and a pattern the GitLab server refuses approves nothing in Duo but would for other tools.`);
94491
+ const config = { permission: Object.keys(bash).length > 0 ? { [SHELL_PERMISSION_CATEGORY]: bash } : {} };
94492
+ return RulesyncPermissions.fromImportedFileContent({
94493
+ outputRoot: this.outputRoot,
94494
+ sourcePath: this.getRelativePathFromCwd(),
94495
+ fileContent: JSON.stringify(config, null, 2)
94496
+ });
94497
+ }
94498
+ };
94499
+ function rank(effect) {
94500
+ return effect === "deny" ? 2 : effect === "ask" ? 1 : 0;
94501
+ }
94502
+ function isDuoPermissionStatement(value) {
94503
+ return isPlainObject(value) && typeof value.action === "string" && value.action.length > 0 && typeof value.resource === "string" && (value.effect === "allow" || value.effect === "ask" || value.effect === "deny");
94504
+ }
94505
+ function parseSettings({ content, filePath }) {
94506
+ let parsed;
94507
+ try {
94508
+ parsed = parseJsonc$6(content);
94509
+ } catch (error) {
94510
+ throw new Error(`Failed to parse GitLab Duo CLI settings at ${filePath}: ${formatError(error)}`, { cause: error });
94511
+ }
94512
+ if (!isPlainObject(parsed)) throw new Error(`GitLab Duo CLI settings at ${filePath} must contain a JSON object.`);
94513
+ return parsed;
94514
+ }
94515
+ /**
94516
+ * A canonical command pattern as Duo's token matcher reads it: trimmed, runs
94517
+ * of whitespace collapsed to one space (Duo splits a command into words, so
94518
+ * `git push` and `git push` are one command), and a trailing `:*` ("any
94519
+ * arguments") spelled ` *`.
94520
+ */
94521
+ function normalizeGitlabduoCommandPattern(pattern) {
94522
+ let normalized = pattern.trim();
94523
+ if (TRAILING_ARGUMENT_WILDCARD.test(normalized)) normalized = `${normalized.slice(0, -2)} *`;
94524
+ return normalized.trim().split(/\s+/).join(" ");
94525
+ }
94526
+ /**
94527
+ * The Duo `resource` for a canonical `bash` allow pattern, or `null` when the
94528
+ * server would refuse it or read it differently from what it says. The result
94529
+ * never matches a command the canonical pattern does not match.
94530
+ */
94531
+ function toGitlabduoCommandResource(pattern) {
94532
+ const resource = normalizeGitlabduoCommandPattern(pattern);
94533
+ if (resource === "" || resource === "*" || resource.length > MAX_PATTERN_LENGTH) return null;
94534
+ if (UNSUPPORTED_PATTERN_CHARACTERS.test(resource)) return null;
94535
+ if (resource.includes("**")) return null;
94536
+ return resource;
94537
+ }
94538
+ /**
94539
+ * Convert the canonical config into the `run_command` allow statements Duo CLI
94540
+ * enforces, reporting every rule that could not be carried.
94541
+ */
94542
+ function convertRulesyncToGitlabduoStatements({ config, logger }) {
94543
+ const { rules, foreignRestrictingCategories, ignoredAllToolsAllowPatterns } = collectShellCommandRules(config.permission);
94544
+ const restrictions = (0, es_toolkit.uniq)(rules.filter(({ action }) => action !== "allow").flatMap(({ pattern }) => [
94545
+ pattern,
94546
+ normalizeGitlabduoCommandPattern(pattern),
94547
+ normalizeGitlabduoCommandPattern(pattern.replaceAll(SHELL_QUOTING_CHARACTERS, ""))
94548
+ ]).filter((pattern) => pattern !== "")).map((pattern) => ({
94549
+ pattern,
94550
+ fromAllToolsCategory: false
94551
+ }));
94552
+ const budget = createIntersectionBudget();
94553
+ const shadowingRestrictions = createShadowingRestrictionsTest(restrictions, { budget });
94554
+ const resources = [];
94555
+ const shadowedAllowPatterns = [];
94556
+ const unsupportedPatterns = [];
94557
+ for (const { pattern, action } of rules) {
94558
+ if (action !== "allow") continue;
94559
+ const resource = toGitlabduoCommandResource(pattern);
94560
+ if (resource === null) {
94561
+ unsupportedPatterns.push(pattern);
94562
+ continue;
94563
+ }
94564
+ if (shadowingRestrictions(resource).length > 0) {
94565
+ shadowedAllowPatterns.push(pattern);
94566
+ continue;
94567
+ }
94568
+ resources.push(resource);
94569
+ }
94570
+ warnAboutUnwrittenCommandRules({
94571
+ toolLabel: TOOL_LABEL,
94572
+ surfaceLabel: `${PERMISSIONS_KEY} statements for ${COMMAND_TOOL_NAME}`,
94573
+ foreignRestrictingCategories,
94574
+ shadowedAllowPatterns: (0, es_toolkit.uniq)(shadowedAllowPatterns),
94575
+ ignoredAllToolsAllowPatterns,
94576
+ intersectionBudgetExhausted: budget.remaining === 0,
94577
+ logger
94578
+ });
94579
+ const denyPatterns = (0, es_toolkit.uniq)(rules.filter(({ action }) => action === "deny").map(({ pattern }) => pattern));
94580
+ if (denyPatterns.length > 0) warnWithFallback(logger, `${TOOL_LABEL} enforces only allow statements in '${PERMISSIONS_KEY}' (ask and deny are logged and ignored), so the deny rule(s) for ${denyPatterns.join(", ")} were not written. Those commands are asked about rather than blocked.`);
94581
+ const foreignAllowCategories = Object.entries(config.permission).filter(([category, categoryRules]) => category !== "bash" && category !== "*" && Object.values(categoryRules).includes("allow")).map(([category]) => category);
94582
+ if (foreignAllowCategories.length > 0) warnWithFallback(logger, `${TOOL_LABEL}: only 'bash' allow rules are written (as ${COMMAND_TOOL_NAME} statements), so the allow rules of '${foreignAllowCategories.join("', '")}' were skipped.`);
94583
+ if (unsupportedPatterns.length > 0) warnWithFallback(logger, `${TOOL_LABEL} refuses a ${COMMAND_TOOL_NAME} pattern that is a lone '*', holds '**' or a shell metacharacter, or is longer than ${MAX_PATTERN_LENGTH} characters, and reads quotes, escapes and '[...]' differently from the canonical glob, so the allow rule(s) for ${(0, es_toolkit.uniq)(unsupportedPatterns).join(", ")} were skipped.`);
94584
+ return (0, es_toolkit.uniq)(resources).map((resource) => ({
94585
+ action: COMMAND_TOOL_NAME,
94586
+ resource,
94587
+ effect: "allow"
94588
+ }));
94589
+ }
92993
94590
  // src/features/permissions/goose-permissions.ts
92994
94591
  const GOOSE_GLOBAL_ONLY_MESSAGE = "Goose permissions are global-only; use --global to sync ~/.config/goose/permission.yaml";
92995
94592
  const GOOSE_USER_KEY = "user";
@@ -105308,6 +106905,13 @@ const toolPermissionsFactories = /* @__PURE__ */ new Map([
105308
106905
  supportsGlobal: true
105309
106906
  }
105310
106907
  }],
106908
+ ["gitlabduo", {
106909
+ class: GitlabduoPermissions,
106910
+ meta: {
106911
+ supportsProject: false,
106912
+ supportsGlobal: true
106913
+ }
106914
+ }],
105311
106915
  ["goose", {
105312
106916
  class: GoosePermissions,
105313
106917
  meta: {