rulesync 43.13.0 → 43.14.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$360 } = 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$360(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$360(SKILLS_FEATURE_SUBDIR, ".curated");
397
+ const RULESYNC_RULES_RELATIVE_DIR_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, RULES_FEATURE_SUBDIR);
398
+ const RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, CURATED_RULES_FEATURE_SUBDIR);
399
+ const RULESYNC_COMMANDS_RELATIVE_DIR_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, COMMANDS_FEATURE_SUBDIR);
400
+ const RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, SUBAGENTS_FEATURE_SUBDIR);
401
+ const RULESYNC_CHECKS_RELATIVE_DIR_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, CHECKS_FEATURE_SUBDIR);
402
+ const RULESYNC_MCP_RELATIVE_FILE_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, "mcp.jsonc");
403
+ const RULESYNC_HOOKS_RELATIVE_FILE_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, "hooks.jsonc");
404
+ const RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, "permissions.jsonc");
405
+ join$360(RULESYNC_RELATIVE_DIR_PATH, "mcp.json");
406
+ const RULESYNC_HOOKS_LEGACY_RELATIVE_FILE_PATH = join$360(RULESYNC_RELATIVE_DIR_PATH, "hooks.json");
407
+ const RULESYNC_PERMISSIONS_LEGACY_RELATIVE_FILE_PATH = join$360(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$360(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$360(RULESYNC_RELATIVE_DIR_PATH, SKILLS_FEATURE_SUBDIR);
413
+ const RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH = join$360(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";
@@ -925,6 +925,7 @@ const permissionsProcessorToolTargetTuple = [
925
925
  "deepagents",
926
926
  "devin",
927
927
  "factorydroid",
928
+ "gitlabduo",
928
929
  "goose",
929
930
  "grokcli",
930
931
  "hermesagent",
@@ -5584,20 +5585,57 @@ const CANONICAL_TO_BOB_EVENT_NAMES = {
5584
5585
  stop: "Stop"
5585
5586
  };
5586
5587
  /**
5587
- * Hook events supported by IBM Bob's lifecycle hooks.
5588
+ * Hook events rulesync emits for IBM Bob from the shared `hooks` block.
5588
5589
  *
5589
5590
  * Bob reads `hooks` from `.bob/settings.json` (project) and
5590
5591
  * `~/.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.
5592
+ * seven documented events: SessionStart, UserPromptSubmit, PreToolUse,
5593
+ * PostToolUse, PreCompact, PostCompact and Stop (Bob IDE and Bob Shell list
5594
+ * the same seven). Handlers are `command` or `http` hooks. Bob Shell 2.1.0
5595
+ * adds more events; see {@link BOB_OPT_IN_HOOK_EVENTS} for why they are not
5596
+ * emitted from the shared block.
5596
5597
  *
5597
5598
  * @see https://bob.ibm.com/docs/shell/configuration/lifecycle-hooks
5598
5599
  * @see https://bob.ibm.com/docs/ide/configuration/lifecycle-hooks
5599
5600
  */
5600
5601
  const BOB_HOOK_EVENTS = eventsOf(CANONICAL_TO_BOB_EVENT_NAMES);
5602
+ /**
5603
+ * The {@link BOB_HOOK_EVENTS} whose `matcher` regex Bob applies: the tool name
5604
+ * on PreToolUse / PostToolUse, `source` on SessionStart and `trigger` on
5605
+ * PreCompact / PostCompact. UserPromptSubmit and Stop have no matchable value.
5606
+ */
5607
+ const BOB_MATCHER_HOOK_EVENTS = BOB_HOOK_EVENTS.filter((event) => event !== "beforeSubmitPrompt" && event !== "stop");
5608
+ /**
5609
+ * Canonical events that Bob Shell 2.1.0 (`@ibm/bob` on npm, 2026-11-09) can
5610
+ * fire under the native name given here, next to the override-only
5611
+ * `PermissionResolved`. They are not on the lifecycle-hooks pages yet.
5612
+ *
5613
+ * They are deliberately not emitted from the shared `hooks` block: Bob Shell
5614
+ * before 2.1.0 validates the `hooks` object strictly against the seven
5615
+ * documented keys, and on any unknown key it ignores that settings file's
5616
+ * whole `hooks` block (PreToolUse guards included). Writing them must
5617
+ * therefore be an explicit opt-in under the `bob.hooks` override block, by
5618
+ * their native name, which is emitted verbatim and imported back there.
5619
+ *
5620
+ * @see https://registry.npmjs.org/@ibm/bob/-/bob-2.1.0.tgz
5621
+ */
5622
+ const BOB_OPT_IN_HOOK_EVENTS = {
5623
+ sessionEnd: "SessionEnd",
5624
+ permissionRequest: "PermissionRequest",
5625
+ notification: "Notification"
5626
+ };
5627
+ /**
5628
+ * Every native event key Bob Shell 2.1.0's strict hooks schema accepts: the
5629
+ * seven documented events, the three opt-in ones and `PermissionResolved`,
5630
+ * which has no canonical counterpart. Any other key under `bob.hooks` is
5631
+ * dropped on generate, because one unknown key makes Bob ignore the file's
5632
+ * whole hooks block.
5633
+ */
5634
+ const BOB_NATIVE_HOOK_EVENTS = [
5635
+ ...Object.values(CANONICAL_TO_BOB_EVENT_NAMES),
5636
+ ...Object.values(BOB_OPT_IN_HOOK_EVENTS),
5637
+ "PermissionResolved"
5638
+ ];
5601
5639
  const BOB_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_BOB_EVENT_NAMES);
5602
5640
  const CANONICAL_TO_TABNINE_EVENT_NAMES = {
5603
5641
  sessionStart: "SessionStart",
@@ -5880,17 +5918,18 @@ const CONTINUE_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_CONTINUE_EVE
5880
5918
  * observers, `gateway_platform_event` and `transform_api_error_classification`.
5881
5919
  * Shell hooks are gated on the same set.
5882
5920
  *
5883
- * Verified against the tag `v0.23.2`: `VALID_HOOKS` holds 48 entries, grown
5921
+ * Verified against the tag `v0.23.4`: `VALID_HOOKS` holds 50 entries, grown
5884
5922
  * from 23 at `v2026.8.3` (v0.20.0) and 37 at `v2026.8.16` (v0.20.2) — v0.21
5885
5923
  * added `agent_loop_stopped` and `on_room_member_activity`, v0.21.5 added
5886
5924
  * `pre_auxiliary_call` and `post_auxiliary_call`, v0.21.6 added
5887
5925
  * `post_gateway_admission`, `on_human_input_request` and
5888
5926
  * `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
5927
+ * `post_compaction`, v0.23.1 added `on_session_open` and
5928
+ * `post_curator_run`, and v0.23.4 added `on_session_prompt` and
5929
+ * `on_session_prompt_settled`. This list holds 49 of them — see
5891
5930
  * {@link HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS} for the exclusion.
5892
5931
  *
5893
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py
5932
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/hermes_cli/plugins.py
5894
5933
  */
5895
5934
  const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5896
5935
  "pre_tool_call",
@@ -5916,6 +5955,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5916
5955
  "on_session_reset",
5917
5956
  "on_session_delete",
5918
5957
  "on_session_open",
5958
+ "on_session_prompt",
5959
+ "on_session_prompt_settled",
5919
5960
  "on_skill_lifecycle",
5920
5961
  "subagent_start",
5921
5962
  "subagent_stop",
@@ -5951,8 +5992,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5951
5992
  * rulesync only ever writes shell hooks, so these are excluded from
5952
5993
  * {@link HERMESAGENT_NATIVE_HOOK_EVENTS} and warned about with their own message.
5953
5994
  *
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`
5995
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5996
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/agent/shell_hooks.py — `_parse_hooks_block`
5956
5997
  */
5957
5998
  const HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS = ["transform_api_error_classification"];
5958
5999
  /**
@@ -5972,8 +6013,8 @@ const CANONICAL_TO_HERMESAGENT_EVENT_NAMES = {
5972
6013
  /**
5973
6014
  * Hook events supported by Hermes Agent's native Shell Hooks system.
5974
6015
  *
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
6016
+ * Hermes validates hook events against a fixed `VALID_HOOKS` set — 50 entries as
6017
+ * of v0.23.4 (tag `v0.23.4`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
5977
6018
  * full list. Only the events with a clean 1:1 canonical equivalent are mapped
5978
6019
  * here. All other native events round-trip through `hermesagent.hooks`.
5979
6020
  * @see https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/hooks.md
@@ -9790,6 +9831,7 @@ const PermissionsConfigSchema = zod_mini.z.looseObject({
9790
9831
  commandcode: zod_mini.z.optional(CommandcodePermissionsOverrideSchema),
9791
9832
  lettacode: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9792
9833
  crush: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9834
+ gitlabduo: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9793
9835
  goose: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
9794
9836
  omp: zod_mini.z.optional(OmpPermissionsOverrideSchema),
9795
9837
  pool: zod_mini.z.optional(CanonicalPermissionsOverrideSchema),
@@ -18299,6 +18341,14 @@ const GITLABDUO_DIR = (0, node_path.join)(".gitlab", "duo");
18299
18341
  const GITLABDUO_RULE_FILE_NAME = "chat-rules.md";
18300
18342
  /** MCP servers. @see https://docs.gitlab.com/user/gitlab_duo/model_context_protocol/mcp_clients/ */
18301
18343
  const GITLABDUO_MCP_FILE_NAME = "mcp.json";
18344
+ /**
18345
+ * Settings. Only the user file `~/.gitlab/duo/settings.json` carries the
18346
+ * `permissions` setting rulesync writes; the project files are deliberately not
18347
+ * read for it.
18348
+ *
18349
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/definitions.ts
18350
+ */
18351
+ const GITLABDUO_SETTINGS_FILE_NAME = "settings.json";
18302
18352
  /** Lifecycle hooks (experiment). @see https://docs.gitlab.com/user/gitlab_duo_cli/customize/ */
18303
18353
  const GITLABDUO_HOOKS_FILE_NAME = "hooks.json";
18304
18354
  /** Merge request review instructions. @see https://docs.gitlab.com/user/project/merge_requests/duo_in_merge_requests/ */
@@ -37089,8 +37139,208 @@ const VIBE_PROMPTS_DIR_PATH = (0, node_path.join)(".vibe", "prompts");
37089
37139
  * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.3/vibe/core/agents/models.py
37090
37140
  */
37091
37141
  const VIBE_RESERVED_AGENT_NAME = "main";
37142
+ /**
37143
+ * The approval policies Vibe ships since v3.1.4. `AgentRegistry._discover`
37144
+ * never loads an agents-directory file named after one as an agent, whatever
37145
+ * its `agent_type`: from a project's `.vibe/agents/` the file is ignored with
37146
+ * an `approval_policy.project_override_ignored` config issue, and from
37147
+ * `~/.vibe/agents/` it redefines that approval policy for every session. Vibe
37148
+ * compares the file stem exactly (`agent.name in BUILTIN_APPROVAL_POLICIES`).
37149
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/registry.py
37150
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/models.py
37151
+ */
37152
+ const VIBE_APPROVAL_POLICY_NAMES = /* @__PURE__ */ new Set([
37153
+ "ask",
37154
+ "accept-edits",
37155
+ "smart-approve",
37156
+ "auto-approve"
37157
+ ]);
37158
+ function vibeAgentFileStem(relativeFilePath) {
37159
+ return (0, node_path.basename)(relativeFilePath).replace(/\.(md|toml)$/, "");
37160
+ }
37092
37161
  function isReservedVibeAgentFileName(relativeFilePath) {
37093
- return (0, node_path.basename)(relativeFilePath).replace(/\.(md|toml)$/, "").toLowerCase() === VIBE_RESERVED_AGENT_NAME;
37162
+ return vibeAgentFileStem(relativeFilePath).toLowerCase() === VIBE_RESERVED_AGENT_NAME;
37163
+ }
37164
+ function isVibeApprovalPolicyFileName(relativeFilePath) {
37165
+ return VIBE_APPROVAL_POLICY_NAMES.has(vibeAgentFileStem(relativeFilePath));
37166
+ }
37167
+ /**
37168
+ * The keys Vibe ignores on a custom `agent_type = "agent"` profile since
37169
+ * v3.1.4, listing each as a config issue: `_agent_settings` drops every
37170
+ * `VibeConfigSchema` field outside its `_AGENT_KEYS`, plus `safety` and
37171
+ * `approval_policy`, because what runs without asking belongs to the approval
37172
+ * policy, not to the agent. A key outside this list is kept, as Vibe keeps it:
37173
+ * an agent key passes, and an unknown key (a typo such as `disabled_tool`)
37174
+ * stays so Vibe can report it — or refuse it under `strict_config`.
37175
+ * Generated from the `VibeConfigSchema` fields of v3.1.5 minus `_AGENT_KEYS`.
37176
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/models.py
37177
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/config/vibe_schema.py
37178
+ */
37179
+ const VIBE_AGENT_IGNORED_KEYS = /* @__PURE__ */ new Set([
37180
+ "safety",
37181
+ "approval_policy",
37182
+ "catalog_model_aliases",
37183
+ "catalog_recommended_model",
37184
+ "catalog_default_model",
37185
+ "utility_models",
37186
+ "active_transcribe_model",
37187
+ "transcribe_providers",
37188
+ "transcribe_models",
37189
+ "active_tts_model",
37190
+ "tts_providers",
37191
+ "tts_models",
37192
+ "outside_workdir",
37193
+ "mcp_servers",
37194
+ "enable_connectors",
37195
+ "enable_mcp",
37196
+ "experimental_enable_document_library_connector",
37197
+ "experimental_enable_mistral_mcp_connector",
37198
+ "connectors",
37199
+ "agent_paths",
37200
+ "enabled_agents",
37201
+ "disabled_agents",
37202
+ "installed_agents",
37203
+ "default_agent",
37204
+ "default_approval_policy",
37205
+ "vibe_bot_max_approval_policy",
37206
+ "vibe_bot_local_tools",
37207
+ "vibe_bot_local_tool_max_bytes",
37208
+ "smart_approve_available",
37209
+ "enable_auto_approve",
37210
+ "enabled_plugins",
37211
+ "disabled_plugins",
37212
+ "experimental_enable_remote_plugins",
37213
+ "experimental_enable_registry_skills",
37214
+ "enable_model_catalog",
37215
+ "enable_builtin_models",
37216
+ "experimental_enable_storage_usage",
37217
+ "enable_pr_monitoring",
37218
+ "experimental_local_runtime_session_api",
37219
+ "experimental_target_runtime",
37220
+ "enable_otel",
37221
+ "otel_endpoint",
37222
+ "otel_redaction",
37223
+ "console_base_url",
37224
+ "theme",
37225
+ "applied_migrations",
37226
+ "disable_welcome_banner_animation",
37227
+ "disable_selection_animation",
37228
+ "cursor_blink",
37229
+ "vim_keybindings",
37230
+ "show_dangerous_directory_warning",
37231
+ "autocopy_to_clipboard",
37232
+ "enable_mouse_capture",
37233
+ "enable_sticky_prompt",
37234
+ "collapse_turn_details",
37235
+ "enable_file_autocomplete",
37236
+ "file_watcher_for_autocomplete",
37237
+ "ask_confirmation_on_exit",
37238
+ "displayed_workdir",
37239
+ "context_warnings",
37240
+ "voice_mode_enabled",
37241
+ "narrator_enabled",
37242
+ "show_thinking_nodes",
37243
+ "show_subagent_status_list",
37244
+ "worktree_limit",
37245
+ "auto_worktree",
37246
+ "worktree_copy_on_write",
37247
+ "bypass_tool_permissions",
37248
+ "raise_on_compaction_failure",
37249
+ "enable_telemetry",
37250
+ "managed_shell_tools_enabled",
37251
+ "enable_background_processes",
37252
+ "enable_subagents",
37253
+ "max_subagents",
37254
+ "max_concurrent_subagents",
37255
+ "compaction_prompt_id",
37256
+ "title_prompt_id",
37257
+ "include_commit_signature",
37258
+ "include_model_info",
37259
+ "include_project_context",
37260
+ "include_prompt_detail",
37261
+ "strict_config",
37262
+ "enable_update_checks",
37263
+ "enable_auto_update",
37264
+ "enable_notifications",
37265
+ "keep_awake",
37266
+ "experimental_enable_tab_status",
37267
+ "enable_system_trust_store",
37268
+ "api_timeout",
37269
+ "api_retry_max_elapsed_time",
37270
+ "max_goal_token_budget",
37271
+ "api_stream_idle_timeout",
37272
+ "agent_max_output_tokens",
37273
+ "compaction_max_output_tokens",
37274
+ "compaction_reasoning_limit_tokens",
37275
+ "output_limit_retries",
37276
+ "api_connect_timeout",
37277
+ "api_write_timeout",
37278
+ "api_pool_timeout",
37279
+ "vibe_base_url",
37280
+ "vibe_code_sessions_base_url",
37281
+ "log_level",
37282
+ "project_context",
37283
+ "session_logging",
37284
+ "experiments"
37285
+ ]);
37286
+ /**
37287
+ * The legacy key Vibe folds into `disabled_tools` before it filters an agent
37288
+ * profile (`migrate_agent_profile_config`).
37289
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/_migration.py
37290
+ */
37291
+ const VIBE_LEGACY_BASE_DISABLED_KEY = "base_disabled";
37292
+ /** Per tool, an agent keeps only the shell timeouts and a narrowing `permission`. */
37293
+ const VIBE_AGENT_TOOL_KEYS = /* @__PURE__ */ new Set(["default_timeout", "max_timeout_seconds"]);
37294
+ const VIBE_AGENT_NARROWING_PERMISSIONS = /* @__PURE__ */ new Set(["ask", "never"]);
37295
+ /**
37296
+ * Fold a legacy `base_disabled` list into `disabled_tools` the way Vibe's
37297
+ * `migrate_agent_profile_config` does, so the restriction it carries is kept.
37298
+ */
37299
+ function migrateVibeBaseDisabled(tomlObj) {
37300
+ const legacyDisabled = tomlObj[VIBE_LEGACY_BASE_DISABLED_KEY];
37301
+ if (!Array.isArray(legacyDisabled)) return tomlObj;
37302
+ const rest = Object.fromEntries(Object.entries(tomlObj).filter(([key]) => key !== VIBE_LEGACY_BASE_DISABLED_KEY));
37303
+ const disabledTools = rest.disabled_tools;
37304
+ return {
37305
+ ...rest,
37306
+ disabled_tools: Array.isArray(disabledTools) ? [.../* @__PURE__ */ new Set([...disabledTools, ...legacyDisabled])] : legacyDisabled
37307
+ };
37308
+ }
37309
+ /**
37310
+ * Drop the settings Vibe ignores on an `agent_type = "agent"` profile, so the
37311
+ * generated file does not pretend to grant what Vibe refuses. Mirrors Vibe's
37312
+ * `_agent_settings`; returns the kept TOML object and the dotted keys that
37313
+ * were dropped.
37314
+ */
37315
+ function stripVibeAgentIgnoredSettings(tomlObj) {
37316
+ const kept = {};
37317
+ const dropped = [];
37318
+ for (const [key, value] of Object.entries(migrateVibeBaseDisabled(tomlObj))) {
37319
+ if (VIBE_AGENT_IGNORED_KEYS.has(key)) {
37320
+ dropped.push(key);
37321
+ continue;
37322
+ }
37323
+ if (key !== "tools" || typeof value !== "object" || value === null || Array.isArray(value)) {
37324
+ kept[key] = value;
37325
+ continue;
37326
+ }
37327
+ const tools = {};
37328
+ for (const [tool, settings] of Object.entries(value)) {
37329
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) {
37330
+ dropped.push(`tools.${tool}`);
37331
+ continue;
37332
+ }
37333
+ const own = {};
37334
+ 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;
37335
+ else dropped.push(`tools.${tool}.${setting}`);
37336
+ if (Object.keys(own).length > 0) tools[tool] = own;
37337
+ }
37338
+ if (Object.keys(tools).length > 0) kept.tools = tools;
37339
+ }
37340
+ return {
37341
+ kept,
37342
+ dropped: dropped.toSorted()
37343
+ };
37094
37344
  }
37095
37345
  /**
37096
37346
  * Vibe resolves a `system_prompt_id` by file name, and
@@ -37170,7 +37420,7 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37170
37420
  validate: true
37171
37421
  });
37172
37422
  }
37173
- static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false }) {
37423
+ static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false, logger }) {
37174
37424
  const frontmatter = rulesyncSubagent.getFrontmatter();
37175
37425
  const rawSection = frontmatter.vibe ?? {};
37176
37426
  const vibeSection = this.filterToolSpecificSection(rawSection, [
@@ -37188,7 +37438,13 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37188
37438
  ...vibeSection,
37189
37439
  ...promptBody ? { system_prompt_id: slug } : {}
37190
37440
  };
37191
- const body = smol_toml.stringify(tomlObj);
37441
+ let finalToml = tomlObj;
37442
+ if (tomlObj.agent_type === "agent") {
37443
+ const { kept, dropped } = stripVibeAgentIgnoredSettings(tomlObj);
37444
+ 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".`);
37445
+ finalToml = kept;
37446
+ }
37447
+ const body = smol_toml.stringify(finalToml);
37192
37448
  const paths = this.getSettablePaths({ global });
37193
37449
  const relativeFilePath = rulesyncSubagent.getRelativeFilePath().replace(/\.md$/, ".toml");
37194
37450
  return new VibeSubagent({
@@ -37209,7 +37465,10 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37209
37465
  * with a warning.
37210
37466
  *
37211
37467
  * 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`.
37468
+ * for hook matching and does not load an agent file called `main.toml`. So is
37469
+ * one named after an approval policy (`ask`, `accept-edits`, `smart-approve`,
37470
+ * `auto-approve`): Vibe ignores such a file in a project and treats it as a
37471
+ * redefinition of that policy in `~/.vibe/agents/`, never as an agent.
37213
37472
  */
37214
37473
  static fromRulesyncSubagents({ rulesyncSubagents, outputRoot = process.cwd(), global = false, logger }) {
37215
37474
  return rulesyncSubagents.flatMap((rulesyncSubagent) => {
@@ -37218,11 +37477,17 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37218
37477
  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
37478
  return [];
37220
37479
  }
37480
+ if (isVibeApprovalPolicyFileName(sourcePath)) {
37481
+ const policy = vibeAgentFileStem(sourcePath);
37482
+ 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.`);
37483
+ return [];
37484
+ }
37221
37485
  const agentFile = VibeSubagent.fromRulesyncSubagent({
37222
37486
  outputRoot,
37223
37487
  relativeDirPath: VibeSubagent.getSettablePaths({ global }).relativeDirPath,
37224
37488
  rulesyncSubagent,
37225
- global
37489
+ global,
37490
+ logger
37226
37491
  });
37227
37492
  const promptBody = rulesyncSubagent.getBody();
37228
37493
  if (!promptBody) return [agentFile];
@@ -37298,6 +37563,22 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37298
37563
  if (typeof promptId !== "string" || promptId === "" || /[\\/]/.test(promptId)) return;
37299
37564
  return await readFileContentOrNull((0, node_path.join)(outputRoot, VIBE_PROMPTS_DIR_PATH, `${promptId}.md`)) ?? void 0;
37300
37565
  }
37566
+ /**
37567
+ * A file in `.vibe/agents/` named after an approval policy is not an agent:
37568
+ * in `~/.vibe/agents/` it is the user's override of that policy (often a
37569
+ * narrower one), and in a project Vibe ignores it. It is therefore neither
37570
+ * imported as a subagent (with a warning) nor swept as an orphan, since
37571
+ * deleting a narrowing override would fall back to the broader builtin.
37572
+ */
37573
+ static async isFileOwned({ relativeFilePath, forDeletion = false, logger }) {
37574
+ if (!isVibeApprovalPolicyFileName(relativeFilePath)) return true;
37575
+ 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.`);
37576
+ return false;
37577
+ }
37578
+ /** Never delete an approval-policy override; see {@link VibeSubagent.isFileOwned}. */
37579
+ isDeletable() {
37580
+ return this.promptFile || !isVibeApprovalPolicyFileName(this.getRelativeFilePath());
37581
+ }
37301
37582
  static forDeletion({ outputRoot = process.cwd(), relativeDirPath, relativeFilePath, global = false }) {
37302
37583
  return new VibeSubagent({
37303
37584
  outputRoot,
@@ -38471,7 +38752,9 @@ var SubagentsProcessor = class extends FeatureProcessor {
38471
38752
  const ownership = await Promise.all(subagentFilePaths.map((path) => factory.class.isFileOwned({
38472
38753
  outputRoot: rootOutputRoot,
38473
38754
  relativeDirPath: dirPath,
38474
- relativeFilePath: toRelativeFilePath(path)
38755
+ relativeFilePath: toRelativeFilePath(path),
38756
+ forDeletion,
38757
+ logger: this.logger
38475
38758
  })));
38476
38759
  ownedFilePaths = subagentFilePaths.filter((_, index) => ownership[index]);
38477
38760
  }
@@ -46500,10 +46783,18 @@ var MimocodeRule = class extends OpenCodeRule {
46500
46783
  * from the working directory to the `.git` boundary and loads one instruction
46501
46784
  * file per directory level, preferring `AGENTS.md` over `CLAUDE.md` when both
46502
46785
  * 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)
46786
+ * the agentsmd/codexcli targets write). Muse Code also loads machine-wide user
46787
+ * rules; since 1.4.23 its changelog names `~/.claude/CLAUDE.md` as that file
46788
+ * (the filename of the alternative under Muse's own config directory is not
46789
+ * published). `~/.claude/CLAUDE.md` is exactly what the `claudecode` target
46790
+ * writes in global mode, so no global scope is supported here: emitting the
46791
+ * same file from two targets would make the result depend on target order.
46792
+ * `rulesync generate --targets claudecode --global` feeds Muse Code's user
46793
+ * rules instead, but only for the root rule (global non-root rules go to
46794
+ * `~/.claude/rules/*.md`, which Muse Code is not documented to read) and only
46795
+ * for rules that target `claudecode`. (Verified against the official docs:
46796
+ * https://dev.meta.ai/docs/muse-code/configuration and
46797
+ * https://dev.meta.ai/docs/muse-code/changelog)
46507
46798
  *
46508
46799
  * rulesync's topic-based non-root rules have no project subdirectory to map
46509
46800
  * onto, so their bodies are folded into the single root `AGENTS.md` by the
@@ -50918,9 +51209,10 @@ const AmpCheckFrontmatterSchema = zod_mini.z.looseObject({
50918
51209
  * Amp reads code review checks as Markdown files with YAML frontmatter,
50919
51210
  * scoped to the project (`.agents/checks/`) and user-wide (`~/.config/amp/checks/`;
50920
51211
  * 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.
51212
+ * Amp has since removed `amp review` and deprecated project-defined checks
51213
+ * in `.agents/checks/`, together with the `@amp/review-checks` plugin that runs
51214
+ * them. rulesync keeps writing this format because Goose discovers the same
51215
+ * `.agents/checks/` directory and existing setups may still load the plugin.
50924
51216
  * @see https://ampcode.com/docs/review
50925
51217
  */
50926
51218
  var AmpCheck = class extends ToolCheck {
@@ -56499,9 +56791,12 @@ var SettingsJsonHooks = class extends ToolHooks {
56499
56791
  const config = rulesyncHooks.getJson();
56500
56792
  const generatedHooks = canonicalToToolHooks({
56501
56793
  config,
56502
- toolOverrideHooks: overrideHooksOf({
56503
- config,
56504
- overrideKey: this.getSpec().overrideKey
56794
+ toolOverrideHooks: knownOverrideHooks({
56795
+ hooks: overrideHooksOf({
56796
+ config,
56797
+ overrideKey: this.getSpec().overrideKey
56798
+ }),
56799
+ spec: this.getSpec()
56505
56800
  }),
56506
56801
  converterConfig: this.getConverterConfig(),
56507
56802
  logger
@@ -56564,6 +56859,16 @@ var SettingsJsonHooks = class extends ToolHooks {
56564
56859
  }
56565
56860
  };
56566
56861
  /**
56862
+ * The override hooks the tool can take: all of them, unless the spec lists
56863
+ * {@link SettingsJsonHooksSpec.knownOverrideEvents}, in which case only those
56864
+ * native names and the canonical supported events are kept.
56865
+ */
56866
+ function knownOverrideHooks({ hooks, spec }) {
56867
+ if (hooks === void 0 || spec.knownOverrideEvents === void 0) return hooks;
56868
+ const known = /* @__PURE__ */ new Set([...spec.converterConfig.supportedEvents, ...spec.knownOverrideEvents]);
56869
+ return Object.fromEntries(Object.entries(hooks).filter(([event]) => known.has(event)));
56870
+ }
56871
+ /**
56567
56872
  * The `hooks` map of a tool's override block (`config.<overrideKey>.hooks`),
56568
56873
  * or `undefined` when the block states none. The schema keeps every override
56569
56874
  * block loose, so the lookup goes through the record form.
@@ -56577,7 +56882,6 @@ function overrideHooksOf({ config, overrideKey }) {
56577
56882
  const hooks = override.hooks;
56578
56883
  return isPlainObject(hooks) ? hooks : void 0;
56579
56884
  }
56580
- // src/features/hooks/bob-hooks.ts
56581
56885
  const BOB_SPEC = {
56582
56886
  displayName: "Bob",
56583
56887
  overrideKey: "bob",
@@ -56586,11 +56890,12 @@ const BOB_SPEC = {
56586
56890
  canonicalToToolEventNames: CANONICAL_TO_BOB_EVENT_NAMES,
56587
56891
  toolToCanonicalEventNames: BOB_TO_CANONICAL_EVENT_NAMES,
56588
56892
  projectDirVar: "",
56589
- noMatcherEvents: /* @__PURE__ */ new Set(["beforeSubmitPrompt", "stop"]),
56893
+ noMatcherEvents: new Set(BOB_HOOK_EVENTS.filter((event) => !BOB_MATCHER_HOOK_EVENTS.includes(event))),
56590
56894
  supportedHookTypes: /* @__PURE__ */ new Set(["command", "http"]),
56591
56895
  importedHookTypeAliases: { https: "http" },
56592
56896
  wildcardMatcherMeansAll: true
56593
- }
56897
+ },
56898
+ knownOverrideEvents: BOB_NATIVE_HOOK_EVENTS
56594
56899
  };
56595
56900
  /**
56596
56901
  * IBM Bob lifecycle hooks.
@@ -60005,7 +60310,7 @@ function canonicalToHermesHooks({ config, toolOverrideHooks, logger }) {
60005
60310
  for (const [nativeEvent, definitions] of Object.entries(toolOverrideHooks ?? {})) {
60006
60311
  if (HERMESAGENT_CANONICAL_EVENTS.has(nativeEvent)) continue;
60007
60312
  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.`);
60313
+ 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
60314
  setHermesHookEntries({
60010
60315
  result,
60011
60316
  event: nativeEvent,
@@ -60682,7 +60987,9 @@ function buildRunHelperLinesFor(cwdExpression) {
60682
60987
  * hook denies it:
60683
60988
  * - exit code 2 → deny, with the command's stderr as the reason;
60684
60989
  * - exit code 0 with JSON stdout whose `hookSpecificOutput.permissionDecision`
60685
- * is `"deny"` → deny, with `permissionDecisionReason` as the reason;
60990
+ * is `"deny"` → deny, with `permissionDecisionReason` as the reason; when it
60991
+ * sets no `permissionDecision`, the deprecated top-level `decision: "block"`
60992
+ * that Claude Code still honors denies too, with `reason` as the reason;
60686
60993
  * - exit code 0 otherwise → allow;
60687
60994
  * - any other non-zero exit → deny too, with stderr or the exit code;
60688
60995
  * - more than 1 MiB of stdout → deny, without parsing it;
@@ -60717,12 +61024,13 @@ const PRE_TOOL_USE_RESULT_HELPER_LINES = [
60717
61024
  " } catch {",
60718
61025
  " return;",
60719
61026
  " }",
60720
- " const specific = parsed && typeof parsed === \"object\" ? parsed.hookSpecificOutput : undefined;",
60721
- " if (specific && typeof specific === \"object\" && specific.permissionDecision === \"deny\") {",
61027
+ " if (!parsed || typeof parsed !== \"object\") return;",
61028
+ " const specific = parsed.hookSpecificOutput;",
61029
+ " const hasDecision = typeof specific === \"object\" && specific !== null && specific.permissionDecision !== undefined;",
61030
+ " const reason = hasDecision ? specific.permissionDecisionReason : parsed.reason;",
61031
+ " if (hasDecision ? specific.permissionDecision === \"deny\" : parsed.decision === \"block\") {",
60722
61032
  " throw new Error(",
60723
- " (typeof specific.permissionDecisionReason === \"string\" &&",
60724
- " sanitizeBlockReason(specific.permissionDecisionReason)) ||",
60725
- " \"Blocked by a preToolUse hook.\",",
61033
+ " (typeof reason === \"string\" && sanitizeBlockReason(reason)) || \"Blocked by a preToolUse hook.\",",
60726
61034
  " );",
60727
61035
  " }",
60728
61036
  " return;",
@@ -62498,11 +62806,123 @@ const PI_SETTLE_BLOCKING_EVENT = "agent_before_settle";
62498
62806
  * @see https://github.com/can1357/oh-my-pi/blob/fa5ff4a3a977a28b93d025f4cf50f046e019f18c/packages/coding-agent/src/session/agent-session.ts
62499
62807
  */
62500
62808
  const OMP_SESSION_STOP_BLOCKING_EVENT = "session_stop";
62809
+ /**
62810
+ * Pi's `resolveToCwd` (`core/tools/path-utils.ts`), which calls
62811
+ * `resolvePath(path, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true })`
62812
+ * from `utils/paths.ts`: Unicode spaces become plain spaces, a leading `@` is
62813
+ * dropped, on Windows Git Bash / WSL drive paths are converted, `~` is
62814
+ * expanded, a `file://` URL is converted, and the result is resolved against
62815
+ * cwd. Pi has no URL passthrough, so any other `scheme://` text is a relative
62816
+ * path too.
62817
+ *
62818
+ * @see https://github.com/earendil-works/pi/blob/v1.6.0/packages/coding-agent/src/utils/paths.ts
62819
+ */
62820
+ const PI_PATH_RESOLVER_LINES = [
62821
+ "function absoluteToolPath(path: unknown, cwd: string): unknown {",
62822
+ " if (typeof path !== \"string\") return path;",
62823
+ " let normalized = path.replace(/[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g, \" \");",
62824
+ " if (normalized.startsWith(\"@\")) normalized = normalized.slice(1);",
62825
+ " if (process.platform === \"win32\" && normalized.startsWith(\"/\") && !normalized.startsWith(\"//\") && !normalized.includes(\"\\\\\")) {",
62826
+ " const drive = normalized.match(/^\\/(?:mnt\\/|cygdrive\\/)?([a-z])(?:\\/(.*))?$/i);",
62827
+ " if (drive?.[1]) normalized = `${drive[1].toUpperCase()}:\\\\${drive[2]?.replaceAll(\"/\", \"\\\\\") ?? \"\"}`;",
62828
+ " }",
62829
+ " if (normalized === \"~\") normalized = homedir();",
62830
+ " else if (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {",
62831
+ " normalized = joinPath(homedir(), normalized.slice(2));",
62832
+ " } else if (/^file:\\/\\//.test(normalized)) {",
62833
+ " try {",
62834
+ " normalized = fileURLToPath(normalized);",
62835
+ " } catch {",
62836
+ " return path;",
62837
+ " }",
62838
+ " }",
62839
+ " return resolvePath(cwd, normalized);",
62840
+ "}"
62841
+ ];
62842
+ /**
62843
+ * oh-my-pi's `resolveToCwd` (`tools/path-utils.ts`): `expandPath` strips a
62844
+ * stray leading `:` before a path shape, strips a leading `@` only before an
62845
+ * absolute path, `~` or an internal URL, turns Unicode spaces into plain
62846
+ * spaces, converts a `file://` URL and expands `~`; an internal URL is not a
62847
+ * filesystem path, a bare root (`/`) is the workspace root, and anything else
62848
+ * is resolved against cwd. Windows drive-alias handling is not mirrored.
62849
+ *
62850
+ * @see https://github.com/can1357/oh-my-pi/blob/76b7d843d59bc83cc40cd5decadc89dc808a14e6/packages/coding-agent/src/tools/path-utils.ts
62851
+ */
62852
+ const OMP_PATH_RESOLVER_LINES = [
62853
+ `const INTERNAL_URL_SCHEME = /^(?:${[
62854
+ "skill",
62855
+ "rule",
62856
+ "memory",
62857
+ "out",
62858
+ "agent",
62859
+ "history",
62860
+ "local",
62861
+ "proc",
62862
+ "cfg",
62863
+ "ssh",
62864
+ "security",
62865
+ "vault",
62866
+ "issue",
62867
+ "pr",
62868
+ "mr",
62869
+ "mcp",
62870
+ "omp",
62871
+ "help",
62872
+ "attachment",
62873
+ "conflict"
62874
+ ].join("|")}):\\/\\/?/i;`,
62875
+ "",
62876
+ "function absoluteToolPath(path: unknown, cwd: string): unknown {",
62877
+ " if (typeof path !== \"string\") return path;",
62878
+ " let normalized = /^:(?=[/\\\\~]|\\.\\.?[/\\\\]|[A-Za-z]:)/.test(path) ? path.slice(1) : path;",
62879
+ " if (normalized.startsWith(\"@\")) {",
62880
+ " const rest = normalized.slice(1);",
62881
+ " if (rest.startsWith(\"/\") || rest === \"~\" || rest.startsWith(\"~/\") || win32Path.isAbsolute(rest) || INTERNAL_URL_SCHEME.test(rest)) {",
62882
+ " normalized = rest;",
62883
+ " }",
62884
+ " }",
62885
+ " normalized = normalized.replace(/[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g, \" \");",
62886
+ " if (normalized.toLowerCase().startsWith(\"file://\")) {",
62887
+ " try {",
62888
+ " normalized = fileURLToPath(normalized);",
62889
+ " } catch {",
62890
+ " // oh-my-pi keeps an unconvertible `file://` text as written.",
62891
+ " }",
62892
+ " }",
62893
+ " if (normalized === \"~\") normalized = homedir();",
62894
+ " else if (normalized.startsWith(\"~/\")) normalized = joinPath(homedir(), normalized.slice(2));",
62895
+ " if (INTERNAL_URL_SCHEME.test(normalized)) return normalized;",
62896
+ " if (/^\\/+$/.test(normalized)) return resolvePath(cwd);",
62897
+ " return resolvePath(cwd, normalized);",
62898
+ "}"
62899
+ ];
62900
+ /**
62901
+ * Tool names both Pi and oh-my-pi share with a canonical counterpart. Pi's
62902
+ * `powershell` tool is deliberately left out: Rulesync has no canonical name
62903
+ * for it, so it keeps its own.
62904
+ */
62905
+ const SHARED_CANONICAL_TOOL_NAMES = {
62906
+ bash: "Bash",
62907
+ read: "Read",
62908
+ write: "Write",
62909
+ edit: "Edit",
62910
+ grep: "Grep"
62911
+ };
62501
62912
  const PI_EXTENSION_DIALECT = {
62502
62913
  overrideKey: "pi",
62503
62914
  typesPackage: "@earendil-works/pi-coding-agent",
62504
62915
  promptPassLine: "return { action: \"continue\" };",
62505
- promptCancelLine: "return { action: \"handled\" };"
62916
+ promptCancelLine: "return { action: \"handled\" };",
62917
+ toolNames: {
62918
+ ...SHARED_CANONICAL_TOOL_NAMES,
62919
+ find: "Glob"
62920
+ },
62921
+ editTextKeys: {
62922
+ old: "oldText",
62923
+ new: "newText"
62924
+ },
62925
+ pathResolverLines: PI_PATH_RESOLVER_LINES
62506
62926
  };
62507
62927
  /**
62508
62928
  * oh-my-pi's `emitInput` stops at the first result with `handled` set and
@@ -62514,7 +62934,16 @@ const OMP_EXTENSION_DIALECT = {
62514
62934
  overrideKey: "omp",
62515
62935
  typesPackage: "@oh-my-pi/pi-coding-agent",
62516
62936
  promptPassLine: "return {};",
62517
- promptCancelLine: "return { handled: true };"
62937
+ promptCancelLine: "return { handled: true };",
62938
+ toolNames: {
62939
+ ...SHARED_CANONICAL_TOOL_NAMES,
62940
+ glob: "Glob"
62941
+ },
62942
+ editTextKeys: {
62943
+ old: "old_string",
62944
+ new: "new_string"
62945
+ },
62946
+ pathResolverLines: OMP_PATH_RESOLVER_LINES
62518
62947
  };
62519
62948
  const PI_BLOCKING_MODE_BY_EVENT = {
62520
62949
  [PI_BLOCKING_EVENT]: "tool",
@@ -62538,7 +62967,284 @@ function failureLinesByMode(dialect) {
62538
62967
  };
62539
62968
  }
62540
62969
  /**
62541
- * Helper emitted alongside blocking handlers. `promisify(exec)` rejects on a
62970
+ * Canonical events whose command receives Claude Code's JSON input for the
62971
+ * event on stdin, mapped to its `hook_event_name`; every other command gets an
62972
+ * empty stdin, as in the OpenCode-style plugin (`STDIN_PAYLOADS` in
62973
+ * `opencode-style-generator.ts`). All three ride on Pi's tool events, whose
62974
+ * `event.toolName`, `event.toolCallId` and `event.input` the payload is built
62975
+ * from. A payload is serialized lazily, once per invocation, by the first
62976
+ * handler that runs.
62977
+ *
62978
+ * @see https://github.com/earendil-works/pi/blob/v1.6.0/packages/coding-agent/docs/extensions.md#tool_call
62979
+ * @see https://code.claude.com/docs/en/hooks
62980
+ */
62981
+ const STDIN_PAYLOAD_EVENTS = {
62982
+ preToolUse: "PreToolUse",
62983
+ postToolUse: "PostToolUse",
62984
+ postToolUseFailure: "PostToolUseFailure"
62985
+ };
62986
+ /**
62987
+ * The fields each payload adds to the tool call's own (`session_id`, `cwd`,
62988
+ * `hook_event_name`, `tool_name`, `tool_input`, `tool_use_id`), as TypeScript
62989
+ * object entries evaluated against the `tool_result` event.
62990
+ */
62991
+ const STDIN_PAYLOAD_EXTRA_FIELDS = {
62992
+ PreToolUse: "",
62993
+ PostToolUse: "tool_response: { content: event.content, details: event.details }",
62994
+ PostToolUseFailure: "error: toolResultText(event.content)"
62995
+ };
62996
+ /**
62997
+ * Helpers emitted when a handler receives a stdin payload or tests a matcher.
62998
+ *
62999
+ * `claudeToolName` maps the dialect's built-in tool names to the canonical
63000
+ * Claude Code names Rulesync uses elsewhere (`bash` → `Bash`, ...). MCP tools
63001
+ * are already named `mcp__<server>__<tool>` by Pi, and other tools keep their
63002
+ * own name.
63003
+ *
63004
+ * `claudeToolInput` passes the tool's arguments through, except for the file
63005
+ * tools: `path` becomes Claude Code's absolute `file_path`, resolved against
63006
+ * the session cwd the way Pi's `resolveToCwd` does, and on Pi each `edits`
63007
+ * entry's `oldText` / `newText` becomes `old_string` / `new_string` (oh-my-pi
63008
+ * already uses those, see `editTextKeys`). When the call has no top-level
63009
+ * `old_string` / `new_string`, every edit's text is joined into them, as
63010
+ * Claude Code's `Edit` input carries, so a guard reading those sees every
63011
+ * change. The mapped keys are written last and any same-named key the model
63012
+ * added is dropped, so an extra argument (Pi's schemas allow them) cannot make
63013
+ * a guard check a different file or text than the one the tool acts on.
63014
+ */
63015
+ function buildToolPayloadHelperLines(dialect) {
63016
+ return [
63017
+ `const CLAUDE_TOOL_NAMES: Record<string, string> = ${JSON.stringify(dialect.toolNames)};`,
63018
+ "",
63019
+ "function claudeToolName(toolName: string): string {",
63020
+ " return Object.hasOwn(CLAUDE_TOOL_NAMES, toolName) ? (CLAUDE_TOOL_NAMES[toolName] ?? toolName) : toolName;",
63021
+ "}",
63022
+ "",
63023
+ "function matchesTool(matcher: RegExp, toolName: string): boolean {",
63024
+ " return matcher.test(toolName) || matcher.test(claudeToolName(toolName));",
63025
+ "}",
63026
+ "",
63027
+ ...dialect.pathResolverLines,
63028
+ "",
63029
+ `const EDIT_TEXT_KEYS = ${JSON.stringify(dialect.editTextKeys)};`,
63030
+ "const CLAUDE_EDIT_TEXT_KEYS = EDIT_TEXT_KEYS.old === \"old_string\";",
63031
+ "",
63032
+ "function claudeEditEntry(edit: unknown): unknown {",
63033
+ " if (CLAUDE_EDIT_TEXT_KEYS || !edit || typeof edit !== \"object\") return edit;",
63034
+ " const {",
63035
+ " [EDIT_TEXT_KEYS.old]: oldText,",
63036
+ " [EDIT_TEXT_KEYS.new]: newText,",
63037
+ " old_string: _old,",
63038
+ " new_string: _new,",
63039
+ " ...others",
63040
+ " } = edit as Record<string, unknown>;",
63041
+ " return { ...others, old_string: oldText, new_string: newText };",
63042
+ "}",
63043
+ "",
63044
+ "function joinedEditText(edits: unknown[], key: string): string | undefined {",
63045
+ " const texts = edits",
63046
+ " .map((edit: unknown) => (edit as Record<string, unknown> | null)?.[key])",
63047
+ " .filter((text): text is string => typeof text === \"string\");",
63048
+ " return texts.length > 0 ? texts.join(\"\\n\") : undefined;",
63049
+ "}",
63050
+ "",
63051
+ "function claudeToolInput(toolName: string, input: unknown, cwd: string): unknown {",
63052
+ " if (![\"read\", \"write\", \"edit\"].includes(toolName)) return input;",
63053
+ " if (!input || typeof input !== \"object\" || Array.isArray(input)) return input;",
63054
+ " const { path, file_path: _filePath, ...rest } = input as Record<string, unknown>;",
63055
+ " if (!CLAUDE_EDIT_TEXT_KEYS) {",
63056
+ " delete rest.old_string;",
63057
+ " delete rest.new_string;",
63058
+ " }",
63059
+ " // The raw `path` stays, so a guard can check what the model wrote too.",
63060
+ " const claudeInput: Record<string, unknown> = { ...rest, path, file_path: absoluteToolPath(path, cwd) };",
63061
+ " if (!Array.isArray(rest.edits)) return claudeInput;",
63062
+ " const edits = rest.edits.map(claudeEditEntry);",
63063
+ " return {",
63064
+ " ...claudeInput,",
63065
+ " edits,",
63066
+ " old_string: claudeInput.old_string ?? joinedEditText(edits, \"old_string\"),",
63067
+ " new_string: claudeInput.new_string ?? joinedEditText(edits, \"new_string\"),",
63068
+ " };",
63069
+ "}",
63070
+ "",
63071
+ "function toolResultText(content: unknown): string {",
63072
+ " if (!Array.isArray(content)) return \"\";",
63073
+ " return content",
63074
+ " .map((block: unknown) => {",
63075
+ " const part = block as { type?: unknown; text?: unknown } | null;",
63076
+ " return part?.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\";",
63077
+ " })",
63078
+ " .filter(Boolean)",
63079
+ " .join(\"\\n\");",
63080
+ "}",
63081
+ "",
63082
+ "type ToolHookEvent = { toolName: string; toolCallId?: string; input?: unknown };",
63083
+ "",
63084
+ "function toolHookInput(",
63085
+ " hookEventName: string,",
63086
+ " event: ToolHookEvent,",
63087
+ " ctx: ExtensionContext | undefined,",
63088
+ " extra: Record<string, unknown> = {},",
63089
+ "): string {",
63090
+ " const cwd = ctx?.cwd ?? process.cwd();",
63091
+ " return JSON.stringify({",
63092
+ " session_id: ctx?.sessionManager?.getSessionId?.(),",
63093
+ " cwd,",
63094
+ " hook_event_name: hookEventName,",
63095
+ " tool_name: claudeToolName(event.toolName),",
63096
+ " tool_input: claudeToolInput(event.toolName, event.input, cwd),",
63097
+ " tool_use_id: event.toolCallId,",
63098
+ " ...extra,",
63099
+ " });",
63100
+ "}"
63101
+ ];
63102
+ }
63103
+ /**
63104
+ * Helpers emitted alongside `tool_call` handlers. A command that exits 0 may
63105
+ * still decide the call the way Claude Code reads a `PreToolUse` hook's JSON
63106
+ * stdout: `hookSpecificOutput.permissionDecision` `"deny"` or `"ask"` (with
63107
+ * `permissionDecisionReason`) or, when no `permissionDecision` is given, the
63108
+ * deprecated top-level `decision: "block"` (with `reason`). Output that is not
63109
+ * such JSON allows the call, so hooks that print plain text keep working. The
63110
+ * deny side is the OpenCode-style plugin's `__rulesyncEnforcePreToolUseResult`
63111
+ * contract, plus the deprecated form Claude Code still honors.
63112
+ *
63113
+ * Pi has no permission prompt of its own, so `"ask"` is put to the user with
63114
+ * `ctx.ui.confirm` when a UI is attached, and denies the call when none is (print
63115
+ * and JSON modes) or the dialog fails: a hook asking for a human must not pass
63116
+ * silently.
63117
+ */
63118
+ const TOOL_DECISION_HELPER_LINES = [
63119
+ "type ToolHookDecision = { kind: \"deny\" | \"ask\"; reason: string };",
63120
+ "",
63121
+ "function toolHookDecision(stdout: string): ToolHookDecision | undefined {",
63122
+ " let parsed: unknown;",
63123
+ " try {",
63124
+ " parsed = JSON.parse(stdout);",
63125
+ " } catch {",
63126
+ " return undefined;",
63127
+ " }",
63128
+ " if (!parsed || typeof parsed !== \"object\") return undefined;",
63129
+ " const output = parsed as { decision?: unknown; reason?: unknown; hookSpecificOutput?: unknown };",
63130
+ " const specific = output.hookSpecificOutput as",
63131
+ " | { permissionDecision?: unknown; permissionDecisionReason?: unknown }",
63132
+ " | null",
63133
+ " | undefined;",
63134
+ " const hasDecision = typeof specific === \"object\" && specific !== null && specific.permissionDecision !== undefined;",
63135
+ " const decision = hasDecision ? specific?.permissionDecision : output.decision === \"block\" ? \"deny\" : undefined;",
63136
+ " if (decision !== \"deny\" && decision !== \"ask\") return undefined;",
63137
+ " const reason = hasDecision ? specific?.permissionDecisionReason : output.reason;",
63138
+ " return {",
63139
+ " kind: decision,",
63140
+ " reason:",
63141
+ " (typeof reason === \"string\" && sanitizeBlockReason(reason)) ||",
63142
+ " (decision === \"ask\" ? \"A preToolUse hook asked for confirmation.\" : \"Blocked by a preToolUse hook.\"),",
63143
+ " };",
63144
+ "}",
63145
+ "",
63146
+ "async function allowsToolCall(",
63147
+ " decision: ToolHookDecision,",
63148
+ " ctx: ExtensionContext | undefined,",
63149
+ "): Promise<boolean> {",
63150
+ " if (decision.kind !== \"ask\" || !ctx?.hasUI) return false;",
63151
+ " try {",
63152
+ " return await ctx.ui.confirm(\"Allow this tool call?\", decision.reason);",
63153
+ " } catch {",
63154
+ " return false;",
63155
+ " }",
63156
+ "}"
63157
+ ];
63158
+ /**
63159
+ * Runs a hook command through the platform shell with `input` as its stdin
63160
+ * (empty when the event has no payload, so a command that reads stdin never
63161
+ * waits on Pi's own), bounded by the hook's `timeout` in seconds (Claude
63162
+ * Code's default of 600 when unset, as in the OpenCode-style plugin). A stdin
63163
+ * the command never reads is not an error.
63164
+ *
63165
+ * The command runs in its own process group (except on Windows), so a command
63166
+ * past its timeout is killed together with everything it started, and the
63167
+ * call rejects with a `HookTimeoutError` right away rather than waiting for a
63168
+ * descendant still holding its output open. Like `promisify(exec)`, which
63169
+ * earlier versions used, a non-zero exit rejects with an error carrying
63170
+ * `code`, `stdout` and `stderr`, and more than 1 MiB on either stream rejects
63171
+ * and kills the command.
63172
+ *
63173
+ * A detached group does not get the terminal's Ctrl+C, so the extension
63174
+ * kills every command still running on `session_shutdown`, after the other
63175
+ * handlers (including a `sessionEnd` hook's) have run: Pi awaits them in
63176
+ * registration order. A Pi process killed outright never fires it, and since
63177
+ * the timeout timer lives in that process too, its commands then keep running
63178
+ * with no deadline until they exit on their own.
63179
+ */
63180
+ const RUN_HELPER_LINES = [
63181
+ "const MAX_HOOK_OUTPUT_LENGTH = 1024 * 1024;",
63182
+ "",
63183
+ "class HookTimeoutError extends Error {}",
63184
+ "",
63185
+ "// Kills of the commands still running, for `session_shutdown`.",
63186
+ "const runningHookCommands = new Set<() => void>();",
63187
+ "",
63188
+ "function run(",
63189
+ " command: string,",
63190
+ " { input = \"\", seconds }: { input?: string; seconds: number },",
63191
+ "): Promise<{ stdout: string; stderr: string }> {",
63192
+ " return new Promise((resolve, reject) => {",
63193
+ " const detached = process.platform !== \"win32\";",
63194
+ " const child = spawn(command, { shell: true, detached, windowsHide: true });",
63195
+ " const output = { stdout: \"\", stderr: \"\" };",
63196
+ " let settled = false;",
63197
+ " const finish = (error?: Error) => {",
63198
+ " if (settled) return;",
63199
+ " settled = true;",
63200
+ " clearTimeout(timer);",
63201
+ " runningHookCommands.delete(killTree);",
63202
+ " if (error) reject(error);",
63203
+ " else resolve(output);",
63204
+ " };",
63205
+ " const killTree = () => {",
63206
+ " try {",
63207
+ " if (detached && child.pid !== undefined) process.kill(-child.pid, \"SIGKILL\");",
63208
+ " else child.kill(\"SIGKILL\");",
63209
+ " } catch {",
63210
+ " // Already gone.",
63211
+ " }",
63212
+ " child.stdout?.destroy();",
63213
+ " child.stderr?.destroy();",
63214
+ " };",
63215
+ " runningHookCommands.add(killTree);",
63216
+ " const timer = setTimeout(() => {",
63217
+ " killTree();",
63218
+ " finish(new HookTimeoutError(`Hook command timed out after ${seconds} seconds.`));",
63219
+ " }, seconds * 1000);",
63220
+ " for (const stream of [\"stdout\", \"stderr\"] as const) {",
63221
+ " child[stream]?.setEncoding(\"utf8\");",
63222
+ " child[stream]?.on(\"data\", (chunk: string) => {",
63223
+ " output[stream] += chunk;",
63224
+ " if (output[stream].length <= MAX_HOOK_OUTPUT_LENGTH) return;",
63225
+ " killTree();",
63226
+ " finish(new Error(`Hook command wrote more than 1 MiB to ${stream}.`));",
63227
+ " });",
63228
+ " }",
63229
+ " child.on(\"error\", (error) => finish(error));",
63230
+ " child.on(\"close\", (code, signal) => {",
63231
+ " if (code === 0) return finish();",
63232
+ " finish(",
63233
+ " Object.assign(new Error(`Command failed: ${command}`), {",
63234
+ " code,",
63235
+ " signal,",
63236
+ " stdout: output.stdout,",
63237
+ " stderr: output.stderr,",
63238
+ " }),",
63239
+ " );",
63240
+ " });",
63241
+ " child.stdin?.on(\"error\", () => {});",
63242
+ " child.stdin?.end(input);",
63243
+ " });",
63244
+ "}"
63245
+ ];
63246
+ /**
63247
+ * Helper emitted alongside blocking handlers. `run` rejects on a
62542
63248
  * non-zero exit with an error carrying `stdout` / `stderr` / `code`, so the
62543
63249
  * reason is derived from the rejection rather than from a resolved exit code.
62544
63250
  * A command that could not be run at all (spawn failure, `maxBuffer` overflow)
@@ -62642,7 +63348,9 @@ function collectPiHandlers({ effectiveHooks, eventMap }) {
62642
63348
  handlers.push({
62643
63349
  command: def.command,
62644
63350
  matcher: def.matcher ? def.matcher : void 0,
62645
- onlyOnError: PI_ERROR_GATED_CANONICAL_EVENTS.has(canonicalEvent)
63351
+ onlyOnError: PI_ERROR_GATED_CANONICAL_EVENTS.has(canonicalEvent),
63352
+ ...hookTimingOf(def),
63353
+ ...PI_TOOL_EVENTS.has(piEvent) && STDIN_PAYLOAD_EVENTS[canonicalEvent] ? { payload: STDIN_PAYLOAD_EVENTS[canonicalEvent] } : {}
62646
63354
  });
62647
63355
  }
62648
63356
  if (handlers.length > 0) {
@@ -62657,22 +63365,63 @@ function buildCommandLines({ handler, usesToolName, blocking, dialect }) {
62657
63365
  const lines = [];
62658
63366
  const conditions = [];
62659
63367
  if (handler.onlyOnError) conditions.push("event.isError");
62660
- if (usesToolName && handler.matcher) conditions.push(`new RegExp(${matcherToEmbeddedLiteral(handler.matcher)}).test(event.toolName)`);
63368
+ if (usesToolName && handler.matcher) conditions.push(`matchesTool(new RegExp(${matcherToEmbeddedLiteral(handler.matcher)}), event.toolName)`);
62661
63369
  const gated = conditions.length > 0;
62662
63370
  const indent = gated ? " " : " ";
62663
- const embeddedCommand = JSON.stringify(handler.command);
63371
+ const options = [...handler.payload ? [`input: ${payloadAccessorName(handler.payload)}()`] : [], `seconds: ${handler.timeout}`];
63372
+ const runCall = `run(${JSON.stringify(handler.command)}, { ${options.join(", ")} })`;
62664
63373
  if (gated) lines.push(` if (${conditions.join(" && ")}) {`);
62665
63374
  const onFailure = failureLinesByMode(dialect)[blocking];
62666
- if (onFailure.length > 0) {
63375
+ if (blocking === "tool") {
63376
+ lines.push(`${indent}try {`);
63377
+ lines.push(`${indent} const decision = toolHookDecision((await ${runCall}).stdout);`);
63378
+ lines.push(`${indent} if (decision && !(await allowsToolCall(decision, ctx))) return { block: true, reason: decision.reason };`);
63379
+ lines.push(`${indent}} catch (error) {`);
63380
+ if (handler.failClosed === false) {
63381
+ lines.push(`${indent} if (error instanceof HookTimeoutError) {`);
63382
+ lines.push(`${indent} console.error("[rulesync-hooks] preToolUse hook timed out");`);
63383
+ lines.push(`${indent} } else {`);
63384
+ for (const line of onFailure) lines.push(`${indent} ${line}`);
63385
+ lines.push(`${indent} }`);
63386
+ } else for (const line of onFailure) lines.push(`${indent} ${line}`);
63387
+ lines.push(`${indent}}`);
63388
+ } else if (onFailure.length > 0) {
62667
63389
  lines.push(`${indent}try {`);
62668
- lines.push(`${indent} await run(${embeddedCommand});`);
63390
+ lines.push(`${indent} await ${runCall};`);
62669
63391
  lines.push(`${indent}} catch (error) {`);
62670
63392
  for (const line of onFailure) lines.push(`${indent} ${line}`);
62671
63393
  lines.push(`${indent}}`);
62672
- } else lines.push(`${indent}await run(${embeddedCommand});`);
63394
+ } else lines.push(`${indent}await ${runCall};`);
62673
63395
  if (gated) lines.push(" }");
62674
63396
  return lines;
62675
63397
  }
63398
+ /** The per-invocation closure a handler calls for its serialized payload. */
63399
+ function payloadAccessorName(hookEventName) {
63400
+ return `${hookEventName.charAt(0).toLowerCase()}${hookEventName.slice(1)}Input`;
63401
+ }
63402
+ /** Lazily serialized payloads the handlers of one subscription use. */
63403
+ function buildPayloadLines(handlers) {
63404
+ const payloads = [...new Set(handlers.flatMap((h) => h.payload ? [h.payload] : []))];
63405
+ const lines = [];
63406
+ for (const payload of payloads) {
63407
+ const accessor = payloadAccessorName(payload);
63408
+ const extra = STDIN_PAYLOAD_EXTRA_FIELDS[payload] ?? "";
63409
+ const extraArgument = extra ? `, { ${extra} }` : "";
63410
+ lines.push(` let ${accessor}Cache: string | undefined;`);
63411
+ lines.push(` const ${accessor} = () => (${accessor}Cache ??= toolHookInput(${JSON.stringify(payload)}, event, ctx${extraArgument}));`);
63412
+ }
63413
+ return lines;
63414
+ }
63415
+ /**
63416
+ * The handler's parameter list. `ctx` is the second handler argument, so the
63417
+ * prompt gate and the payload builders (which read the session id and cwd)
63418
+ * name both.
63419
+ */
63420
+ function handlerParams({ handlers, readsEvent, isPromptGate }) {
63421
+ const usesPayload = handlers.some((h) => h.payload);
63422
+ if (isPromptGate || usesPayload) return "event, ctx";
63423
+ return readsEvent || handlers.some((h) => h.onlyOnError) ? "event" : "";
63424
+ }
62676
63425
  function buildSubscriptionLines(handlerGroups, dialect) {
62677
63426
  const lines = [];
62678
63427
  for (const [piEvent, handlers] of Object.entries(handlerGroups)) {
@@ -62682,13 +63431,17 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62682
63431
  const isSessionStopGate = blocking === "sessionStop";
62683
63432
  const collectsStopFailures = isSettleGate || isSessionStopGate;
62684
63433
  const usesToolName = PI_TOOL_EVENTS.has(piEvent) && handlers.some((h) => h.matcher);
62685
- const usesErrorFlag = handlers.some((h) => h.onlyOnError);
62686
63434
  const gatesOnAssistant = PI_ASSISTANT_MESSAGE_EVENTS.has(piEvent);
62687
- const params = isPromptGate ? "event, ctx" : usesToolName || usesErrorFlag || gatesOnAssistant || isPromptGate || collectsStopFailures ? "event" : "";
63435
+ const params = handlerParams({
63436
+ handlers,
63437
+ readsEvent: usesToolName || gatesOnAssistant || collectsStopFailures,
63438
+ isPromptGate
63439
+ });
62688
63440
  lines.push(` pi.on(${JSON.stringify(piEvent)}, async (${params}) => {`);
62689
63441
  if (gatesOnAssistant) lines.push(` if (event.message.role !== "assistant") return;`);
62690
63442
  if (isPromptGate) lines.push(` if (event.source === "extension") ${dialect.promptPassLine}`);
62691
63443
  if (collectsStopFailures) lines.push(" const stopHookFailures: unknown[] = [];");
63444
+ lines.push(...buildPayloadLines(handlers));
62692
63445
  for (const handler of handlers) lines.push(...buildCommandLines({
62693
63446
  handler,
62694
63447
  usesToolName,
@@ -62724,6 +63477,10 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62724
63477
  }
62725
63478
  return lines;
62726
63479
  }
63480
+ /** Whether a handler belongs to a tool event, where its matcher is tested. */
63481
+ function handlerGroupHasToolEvent(handlerGroups, handler) {
63482
+ return Object.entries(handlerGroups).some(([piEvent, handlers]) => PI_TOOL_EVENTS.has(piEvent) && handlers.includes(handler));
63483
+ }
62727
63484
  /**
62728
63485
  * Generate the rulesync-owned Pi extension (a TypeScript module with a
62729
63486
  * default-export factory receiving Pi's ExtensionAPI) that subscribes to the
@@ -62738,6 +63495,12 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62738
63495
  * command's output as feedback.
62739
63496
  * `postToolUse` and `postToolUseFailure` share Pi's `tool_result` event; the
62740
63497
  * latter's commands run only when `event.isError` is set.
63498
+ * Commands on the tool events receive Claude Code's hook input on stdin (see
63499
+ * `STDIN_PAYLOAD_EVENTS`), and a tool matcher is tested against both Pi's tool
63500
+ * name and its canonical Claude Code name. On `tool_call`, a command that exits
63501
+ * 0 with a JSON deny decision also denies the call, and one past its `timeout`
63502
+ * denies it unless the hook sets `failClosed: false`, mirroring the
63503
+ * OpenCode-style plugin.
62741
63504
  *
62742
63505
  * @see https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md
62743
63506
  */
@@ -62757,7 +63520,9 @@ function generatePiExtensionCode({ config, supportedEvents, eventMap, dialect =
62757
63520
  const hasPromptGate = Boolean(handlerGroups[PI_PROMPT_BLOCKING_EVENT]);
62758
63521
  const hasSettleGate = Boolean(handlerGroups[PI_SETTLE_BLOCKING_EVENT]);
62759
63522
  const hasSessionStopGate = Boolean(handlerGroups[OMP_SESSION_STOP_BLOCKING_EVENT]);
62760
- const needsBlockReasonHelper = Boolean(handlerGroups[PI_BLOCKING_EVENT]) || hasPromptGate || hasSettleGate || hasSessionStopGate;
63523
+ const needsToolHelpers = Object.values(handlerGroups).flat().some((h) => h.payload || h.matcher && handlerGroupHasToolEvent(handlerGroups, h));
63524
+ const hasToolGate = Boolean(handlerGroups[PI_BLOCKING_EVENT]);
63525
+ const needsBlockReasonHelper = hasToolGate || hasPromptGate || hasSettleGate || hasSessionStopGate;
62761
63526
  const lines = ["// Generated by rulesync. Do not edit manually."];
62762
63527
  if (subscriptionLines.length === 0) {
62763
63528
  lines.push("export default function () {}");
@@ -62767,34 +63532,33 @@ function generatePiExtensionCode({ config, supportedEvents, eventMap, dialect =
62767
63532
  const importedTypes = [
62768
63533
  ...hasSettleGate ? ["AgentBeforeSettleEvent", "AgentBeforeSettleEventResult"] : [],
62769
63534
  "ExtensionAPI",
62770
- ...hasPromptGate ? ["ExtensionContext"] : []
63535
+ ...hasPromptGate || needsToolHelpers ? ["ExtensionContext"] : []
62771
63536
  ].join(", ");
62772
- lines.push("import { exec } from \"node:child_process\";");
62773
- lines.push("import { promisify } from \"node:util\";");
63537
+ lines.push("import { spawn } from \"node:child_process\";");
63538
+ if (needsToolHelpers) {
63539
+ lines.push("import { homedir } from \"node:os\";");
63540
+ 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\";");
63541
+ lines.push("import { fileURLToPath } from \"node:url\";");
63542
+ }
62774
63543
  lines.push("");
62775
63544
  lines.push(`import type { ${importedTypes} } from ${JSON.stringify(dialect.typesPackage)};`);
62776
63545
  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
- }
63546
+ const helperBlocks = [
63547
+ [true, RUN_HELPER_LINES],
63548
+ [needsBlockReasonHelper, BLOCK_REASON_HELPER_LINES],
63549
+ [hasToolGate, TOOL_DECISION_HELPER_LINES],
63550
+ [needsToolHelpers, needsToolHelpers ? buildToolPayloadHelperLines(dialect) : []],
63551
+ [hasPromptGate, PROMPT_GATE_HELPER_LINES],
63552
+ [hasSettleGate || hasSessionStopGate, STOP_HOOK_BLOCK_HELPER_LINES],
63553
+ [hasSettleGate, STOP_HOOK_HELPER_LINES]
63554
+ ];
63555
+ for (const [included, block] of helperBlocks) if (included) lines.push(...block, "");
62795
63556
  lines.push("export default function (pi: ExtensionAPI) {");
62796
63557
  if (hasSettleGate) lines.push(" let stopHookContinued = false;");
62797
63558
  lines.push(...subscriptionLines);
63559
+ lines.push(" pi.on(\"session_shutdown\", async () => {");
63560
+ lines.push(" for (const kill of [...runningHookCommands]) kill();");
63561
+ lines.push(" });");
62798
63562
  lines.push("}");
62799
63563
  lines.push("");
62800
63564
  return lines.join("\n");
@@ -65219,7 +65983,13 @@ const toolHooksFactories = /* @__PURE__ */ new Map([
65219
65983
  },
65220
65984
  ...converterCapabilities(BobHooks.getConverterConfig()),
65221
65985
  supportsMatcher: true,
65222
- matcherEvents: ["preToolUse", "postToolUse"]
65986
+ matcherEvents: BOB_MATCHER_HOOK_EVENTS,
65987
+ dropsUnknownOverrideEvents: true,
65988
+ overrideOnlyEvents: BOB_NATIVE_HOOK_EVENTS,
65989
+ overrideOptIn: {
65990
+ events: BOB_OPT_IN_HOOK_EVENTS,
65991
+ 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."
65992
+ }
65223
65993
  }],
65224
65994
  ["continue", {
65225
65995
  class: ContinueHooks,
@@ -65545,12 +66315,26 @@ var HooksProcessor = class extends FeatureProcessor {
65545
66315
  ...overrideHooks
65546
66316
  };
65547
66317
  {
65548
- const skipped = unsupportedEventNames({
66318
+ const optInEvents = factory.overrideOptIn?.events ?? {};
66319
+ const isOptIn = (e) => Object.hasOwn(optInEvents, e);
66320
+ const overrideKeys = new Set(Object.keys(overrideHooks));
66321
+ const skippedEvents = unsupportedEventNames({
65549
66322
  factory,
65550
66323
  sharedHooks,
65551
66324
  effectiveHooks
65552
66325
  });
66326
+ const skipped = skippedEvents.filter((e) => !isOptIn(e));
66327
+ const optIn = skippedEvents.filter(isOptIn).filter((e) => Object.hasOwn(sharedHooks, e) && !overrideKeys.has(optInEvents[e] ?? ""));
66328
+ const misnamed = skippedEvents.filter(isOptIn).filter((e) => overrideKeys.has(e));
65553
66329
  if (skipped.length > 0) this.logger.warn(`Skipped hook event(s) for ${this.toolTarget} (not supported): ${skipped.join(", ")}`);
66330
+ if (optIn.length > 0) {
66331
+ const nativeNames = optIn.map((e) => optInEvents[e]).join(", ");
66332
+ 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}.`);
66333
+ }
66334
+ if (misnamed.length > 0) {
66335
+ const nativeNames = misnamed.map((e) => optInEvents[e]).join(", ");
66336
+ this.logger.warn(`Skipped "${overrideKey}.hooks" key(s) for ${this.toolTarget}: ${misnamed.join(", ")}. Use the native name(s) ${nativeNames} instead.`);
66337
+ }
65554
66338
  }
65555
66339
  {
65556
66340
  const supportedHookTypes = new Set(factory.supportedHookTypes);
@@ -73510,7 +74294,8 @@ const HERMES_OPAQUE_MAPPING_KEYS = [
73510
74294
  * alias — `auth` (`oauth` for OAuth 2.1/PKCE), mTLS `client_cert` (string PEM
73511
74295
  * path, or `[cert, key]`/`[cert, key, password]` list) and `client_key`,
73512
74296
  * `connect_timeout` (seconds), `supports_parallel_tool_calls`, `protocol`,
73513
- * `lazy`, `events` (see {@link copyHermesBoolLikeFields}), `keepalive_interval`,
74297
+ * `lazy`, `events` (see {@link copyHermesBoolLikeFields}), `single_instance`,
74298
+ * `keepalive_interval`,
73514
74299
  * `elicitation`, `trust`, `identity_header`, and
73515
74300
  * the cost keys (see {@link copyHermesCostFields}) —
73516
74301
  * verbatim from `source` to `target`. Field names are identical on both sides
@@ -73561,6 +74346,10 @@ function copyHermesAdvancedFields(source, target, logger) {
73561
74346
  target.skip_preflight = source.skip_preflight;
73562
74347
  copied = true;
73563
74348
  }
74349
+ if (typeof source.single_instance === "boolean") {
74350
+ target.single_instance = source.single_instance;
74351
+ copied = true;
74352
+ }
73564
74353
  if (typeof source.keepalive_interval === "number") {
73565
74354
  target.keepalive_interval = source.keepalive_interval;
73566
74355
  copied = true;
@@ -84152,7 +84941,7 @@ function buildVscodeCommandLists({ rules, toolLabel, logger, prefixSemantics = "
84152
84941
  };
84153
84942
  }
84154
84943
  // src/features/permissions/bob-permissions.ts
84155
- const TOOL_LABEL = "IBM Bob";
84944
+ const TOOL_LABEL$1 = "IBM Bob";
84156
84945
  /** The top-level settings key holding Bob's auto-approval configuration. */
84157
84946
  const APPROVAL_KEY$1 = "approval";
84158
84947
  /** The top-level settings key holding Bob's per-feature auto-approve toggles. */
@@ -84234,7 +85023,7 @@ function warnAboutSkippedCategories({ permission, bashStated, authorsGroupSwitch
84234
85023
  if (skipped.length === 0) return;
84235
85024
  const names = skipped.map((category) => `'${category}'`).join(", ");
84236
85025
  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}`);
85026
+ 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
85027
  }
84239
85028
  /**
84240
85029
  * Warn about what the `bob` override writes that Bob does not document: an
@@ -84254,7 +85043,7 @@ function warnAboutUndocumentedSettings({ override, logger }) {
84254
85043
  ...outsideWorkspace.length > 0 ? [`'enableOutsideWorkspace' for group(s) ${quoteAll(outsideWorkspace)}`] : []
84255
85044
  ];
84256
85045
  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.`);
85046
+ 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
85047
  }
84259
85048
  /**
84260
85049
  * Name what the `bob` override newly auto-approves. The settings file is Bob's
@@ -84273,7 +85062,7 @@ function warnAboutNewAutoApprovals({ settings, override, filePath, logger }) {
84273
85062
  ...Object.entries(override?.autoApprove ?? {}).filter(([key, value]) => value === true && existingAutoApprove[key] !== true).map(([key]) => quoteValueForWarning(`${AUTO_APPROVE_KEY}.${key}`))
84274
85063
  ]);
84275
85064
  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.`);
85065
+ 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
85066
  }
84278
85067
  /**
84279
85068
  * Split the canonical `bash` rules — plus the restricting rules of the
@@ -84290,7 +85079,7 @@ function buildBobCommandLists({ permission, logger }) {
84290
85079
  normalizePattern: widenToPrefixGlob$1
84291
85080
  });
84292
85081
  warnAboutUnwrittenCommandRules({
84293
- toolLabel: TOOL_LABEL,
85082
+ toolLabel: TOOL_LABEL$1,
84294
85083
  surfaceLabel: SURFACE_LABEL,
84295
85084
  foreignRestrictingCategories,
84296
85085
  shadowedAllowPatterns,
@@ -84305,7 +85094,7 @@ function buildBobCommandLists({ permission, logger }) {
84305
85094
  for (const pattern of deny) lists[pattern] = "deny";
84306
85095
  return buildVscodeCommandLists({
84307
85096
  rules: lists,
84308
- toolLabel: TOOL_LABEL,
85097
+ toolLabel: TOOL_LABEL$1,
84309
85098
  logger,
84310
85099
  prefixSemantics: "documented-prefix"
84311
85100
  });
@@ -84477,7 +85266,7 @@ var BobPermissions = class BobPermissions extends ToolPermissions {
84477
85266
  const rules = importVscodeCommandLists({
84478
85267
  allowed: toStringArray$1(entry?.approvedCommands),
84479
85268
  denied: toStringArray$1(entry?.deniedCommands),
84480
- toolLabel: TOOL_LABEL,
85269
+ toolLabel: TOOL_LABEL$1,
84481
85270
  logger,
84482
85271
  prefixSemantics: "documented-prefix"
84483
85272
  });
@@ -85274,6 +86063,7 @@ const CLAUDECODE_UNHONORED_KEY_SOURCES = {
85274
86063
  disableMobileSimulatorTools: "managed settings",
85275
86064
  disableRemotePreviewScripts: "managed settings",
85276
86065
  disableSideloadFlags: "managed settings",
86066
+ enforceAnthropicSignIn: "managed settings",
85277
86067
  externalEditorContext: "~/.claude.json",
85278
86068
  forceRemoteSettingsRefresh: "managed settings",
85279
86069
  gatewayInternalNetworks: "managed settings",
@@ -85426,12 +86216,14 @@ const CLAUDECODE_ENV_IGNORED_IN_EVERY_FILE = /* @__PURE__ */ new Set([
85426
86216
  "CLAUDE_CODE_DISABLE_MOUNTED_DRIVE_RM_PROMPT",
85427
86217
  "CLAUDE_CODE_DISABLE_POWERSHELL_CMD_RM_DENY",
85428
86218
  "CLAUDE_CODE_DISABLE_SUBSTITUTION_RM_PROMPT",
86219
+ "CLAUDE_CODE_DISABLE_ULTRAREVIEW_TRUST_CHECK",
85429
86220
  "CLAUDE_CODE_EVEN_MORE_DANGEROUSLY_SKIP_PERMISSIONS",
85430
86221
  "CLAUDE_CODE_MESSAGING_SOCKET",
85431
86222
  "CLAUDE_CODE_MESSAGING_TOKEN",
85432
86223
  "CLAUDE_CODE_PROJECT_DIR_NAME",
85433
86224
  "CLAUDE_CODE_REMOTE",
85434
86225
  "CLAUDE_CODE_RESTRICTED",
86226
+ "CLAUDE_CODE_STRICT_INLINE_SHELL_RM_PROMPT",
85435
86227
  "CLAUDE_CODE_WARN_DISK_FREE_GIB",
85436
86228
  "CLAUDE_CODE_WARN_MEMORY_FREE_GIB"
85437
86229
  ]);
@@ -85443,6 +86235,13 @@ const CLAUDECODE_ENV_IGNORED_IN_EVERY_FILE = /* @__PURE__ */ new Set([
85443
86235
  * dialog, and whether it processes attachments or expands `@` file mentions,
85444
86236
  * 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
86237
  *
86238
+ * `OTEL_RESOURCE_INCLUDE_HOST` (Claude Code v2.1.326+) adds the machine's name
86239
+ * and ID to telemetry, so it sits with the telemetry group. The reference lists
86240
+ * `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE` separately: Code Mode follows it only
86241
+ * from the shell, user settings or a `--settings` file, and a project `0` does
86242
+ * not keep Code Mode off either, so any project value is skipped while user
86243
+ * settings (`--global`) still honor it.
86244
+ *
85446
86245
  * Only the names the settings reference lists are covered; its directory,
85447
86246
  * Windows and sign-in groups are introduced with "such as", so an unlisted member of those
85448
86247
  * families is still written. Windows variable names are case-insensitive, so
@@ -85461,6 +86260,7 @@ const CLAUDECODE_ENV_PROJECT_IGNORED_NAMES = /* @__PURE__ */ new Set([
85461
86260
  "CLAUDE_CODE_DISABLE_FILE_MENTIONS",
85462
86261
  "CLAUDE_CODE_ENABLE_TELEMETRY",
85463
86262
  "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
86263
+ "CLAUDE_CODE_EXPERIMENTAL_CODE_MODE",
85464
86264
  "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
85465
86265
  "CLAUDE_CODE_OAUTH_SCOPES",
85466
86266
  "CLAUDE_CODE_OAUTH_TOKEN",
@@ -85479,6 +86279,7 @@ const CLAUDECODE_ENV_PROJECT_IGNORED_NAMES = /* @__PURE__ */ new Set([
85479
86279
  "OTEL_EXPORTER_PROMETHEUS_PORT",
85480
86280
  "OTEL_LOG_ASSISTANT_RESPONSES",
85481
86281
  "OTEL_LOG_RAW_API_BODIES",
86282
+ "OTEL_RESOURCE_INCLUDE_HOST",
85482
86283
  "TEMP",
85483
86284
  "TMP",
85484
86285
  "TMPDIR"
@@ -90675,9 +91476,9 @@ function createSafeCommandShadowTest(permission) {
90675
91476
  });
90676
91477
  const withSeparator = (spellings) => spellings.flatMap((spelling) => [spelling, `${spelling} --*`]);
90677
91478
  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))]);
91479
+ 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
91480
  }
90680
- function uniq$11(values) {
91481
+ function uniq$12(values) {
90681
91482
  return [...new Set(values)];
90682
91483
  }
90683
91484
  function stringList(value) {
@@ -90812,8 +91613,8 @@ var CrushPermissions = class CrushPermissions extends ToolPermissions {
90812
91613
  });
90813
91614
  const preservedAllowed = (isStringArray(existingPermissions?.["allowed_tools"]) ? existingPermissions[CRUSH_ALLOWED_TOOLS_KEY] : []).filter((entry) => entry.includes(":") || !managedToolNames.has(entry));
90814
91615
  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]);
91616
+ const allowedList = uniq$12([...preservedAllowed, ...generated.allowed]);
91617
+ const disabledList = uniq$12([...preservedDisabled, ...generated.disabled]);
90817
91618
  const permissionsHasContent = allowedList.length > 0 || commands.safe.length > 0 || commands.blocked.length > 0;
90818
91619
  const patch = {};
90819
91620
  if (permissionsHasContent || existingPermissions !== void 0) patch[CRUSH_PERMISSIONS_KEY] = {
@@ -90867,7 +91668,7 @@ function rebuildCrushCommandLists({ config, existingPermissions, logger }) {
90867
91668
  shadowTest,
90868
91669
  logger
90869
91670
  });
90870
- const safe = uniq$11([...preserveSafeCommands({
91671
+ const safe = uniq$12([...preserveSafeCommands({
90871
91672
  existing: stringList(existingPermissions?.[CRUSH_SAFE_COMMANDS_KEY]),
90872
91673
  bashRules,
90873
91674
  shadowTest,
@@ -90889,7 +91690,7 @@ function rebuildCrushCommandLists({ config, existingPermissions, logger }) {
90889
91690
  }
90890
91691
  return {
90891
91692
  safe,
90892
- blocked: uniq$11([...existingBlocked, ...blocked])
91693
+ blocked: uniq$12([...existingBlocked, ...blocked])
90893
91694
  };
90894
91695
  }
90895
91696
  /**
@@ -91004,8 +91805,8 @@ function convertRulesyncToCrushLists({ config, logger }) {
91004
91805
  else if (catchAllAction === "deny") lists.disabled.push(toolName);
91005
91806
  }
91006
91807
  return {
91007
- allowed: uniq$11(lists.allowed),
91008
- disabled: uniq$11(lists.disabled)
91808
+ allowed: uniq$12(lists.allowed),
91809
+ disabled: uniq$12(lists.disabled)
91009
91810
  };
91010
91811
  }
91011
91812
  /**
@@ -91064,8 +91865,8 @@ function convertBashCommandRules({ bashRules, shadowTest, logger }) {
91064
91865
  lists.blocked.push(name);
91065
91866
  }
91066
91867
  return {
91067
- safe: uniq$11(lists.safe),
91068
- blocked: uniq$11(lists.blocked)
91868
+ safe: uniq$12(lists.safe),
91869
+ blocked: uniq$12(lists.blocked)
91069
91870
  };
91070
91871
  }
91071
91872
  /**
@@ -92990,6 +93791,263 @@ function convertFactorydroidToRulesyncPermissions({ allow, deny }) {
92990
93791
  for (const pattern of deny) bash[pattern] = "deny";
92991
93792
  return { permission: Object.keys(bash).length > 0 ? { bash } : {} };
92992
93793
  }
93794
+ // src/features/permissions/gitlabduo-permissions.ts
93795
+ 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";
93796
+ const TOOL_LABEL = "GitLab Duo CLI";
93797
+ const PERMISSIONS_KEY = "permissions";
93798
+ /** The Duo tool that runs a shell command; the only one rulesync writes statements for. */
93799
+ const COMMAND_TOOL_NAME = "run_command";
93800
+ /** The server refuses a pattern longer than this (`MAX_PATTERN_LENGTH`). */
93801
+ const MAX_PATTERN_LENGTH = 256;
93802
+ /**
93803
+ * Characters a written pattern must not hold:
93804
+ * - `; & | < > $ \` ( ) { }` and line breaks are shell metacharacters the
93805
+ * server refuses in a command-tool pattern.
93806
+ * - Quotes and the backslash are taken off by the shell-style word split the
93807
+ * server reads a pattern through, so the pattern would be matched as
93808
+ * something other than what it says.
93809
+ * - `[` and `]` start an `fnmatch` character class inside a token, which the
93810
+ * canonical glob does not read the same way.
93811
+ */
93812
+ const UNSUPPORTED_PATTERN_CHARACTERS = /[;&|<>$`(){}\n\r'"\\[\]]/;
93813
+ /** Quotes and the backslash escape, which a shell-style word split takes off. */
93814
+ const SHELL_QUOTING_CHARACTERS = /['"\\]/g;
93815
+ /** A canonical pattern may spell "any arguments" as a trailing `:*` (`git:*`). */
93816
+ const TRAILING_ARGUMENT_WILDCARD = /:\*$/;
93817
+ /** Glob characters that make a Duo pattern match more than its literal spelling. */
93818
+ const GLOB_CHARACTERS = /[*?[\]]/;
93819
+ /**
93820
+ * Permissions adapter for GitLab Duo CLI.
93821
+ *
93822
+ * Duo CLI 10.5.0 reads a `permissions` array of
93823
+ * `{ action, resource, effect }` statements from the managed settings file and
93824
+ * the user's `~/.gitlab/duo/settings.json`. The project files
93825
+ * (`.gitlab/duo/settings.json`, `.gitlab/duo/settings.local.json`) are
93826
+ * deliberately not read for it, so this surface is **global only**.
93827
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/definitions.ts
93828
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/tool_permissions.ts
93829
+ *
93830
+ * Only `allow` is enforced: each allow statement is submitted to the GitLab
93831
+ * instance as a session pattern approval when a session starts. `ask` and
93832
+ * `deny` statements are accepted but only logged. rulesync therefore writes
93833
+ * allow statements only, and never one that could auto-approve something the
93834
+ * canonical file restricts:
93835
+ *
93836
+ * - Only canonical `bash` `allow` rules are written, as
93837
+ * `{ action: "run_command", resource: <pattern>, effect: "allow" }`. Other
93838
+ * categories have no Duo spelling that is known to match no wider than the
93839
+ * canonical rule (the server matches other tools' patterns against their raw
93840
+ * JSON arguments), so their allow rules are skipped with a warning.
93841
+ * - Every `deny` and `ask` rule under `bash` or the all-tools `*` category
93842
+ * withholds the allow rules that could match the same command, because Duo
93843
+ * cannot enforce the restriction itself. A deny is also reported: the command
93844
+ * is asked about, not blocked.
93845
+ * - The GitLab server matches a command-tool pattern token by token
93846
+ * (`CommandPatternMatcher`): a literal token must match exactly, `*` is one
93847
+ * token that does not start with `-`, and a token holding a glob is matched
93848
+ * on its own. That is never wider than the canonical glob, where `*` spans
93849
+ * any characters. A trailing `:*` is written as ` *`. A pattern the server
93850
+ * refuses (a lone `*`, `**`, shell metacharacters, more than 256 characters)
93851
+ * or would read differently (quotes, escapes, character classes) is skipped
93852
+ * with a warning.
93853
+ * @see https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/models/ai/duo_workflows/command_pattern_matcher.rb
93854
+ *
93855
+ * On generate, the statements rulesync owns — those for `run_command` — are
93856
+ * replaced, and every other statement and key of the file is kept, with the
93857
+ * comments outside the `permissions` array (the array is rewritten whole).
93858
+ * On import, `run_command` statements come back under `bash`. An allow is
93859
+ * skipped when its resource holds a glob, which the canonical glob would read
93860
+ * more widely than Duo does, or when the server would refuse it, since it
93861
+ * approves nothing in Duo but would approve the command for other tools.
93862
+ */
93863
+ var GitlabduoPermissions = class GitlabduoPermissions extends ToolPermissions {
93864
+ constructor(params) {
93865
+ super({
93866
+ ...params,
93867
+ fileContent: params.fileContent ?? "{}"
93868
+ });
93869
+ }
93870
+ /**
93871
+ * `settings.json` holds every Duo CLI setting, so rulesync never brings it
93872
+ * into existence just to hold nothing.
93873
+ */
93874
+ shouldSkipCreationWhenPayloadEmpty() {
93875
+ return true;
93876
+ }
93877
+ static getSettablePaths(_options = {}) {
93878
+ return {
93879
+ relativeDirPath: GITLABDUO_DIR,
93880
+ relativeFilePath: GITLABDUO_SETTINGS_FILE_NAME
93881
+ };
93882
+ }
93883
+ static async fromFile({ outputRoot = process.cwd(), validate = true, global = false }) {
93884
+ if (!global) throw new Error(GITLABDUO_GLOBAL_ONLY_MESSAGE);
93885
+ const paths = GitlabduoPermissions.getSettablePaths({ global });
93886
+ const fileContent = await readFileContentOrNull((0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath)) ?? "{}";
93887
+ return new GitlabduoPermissions({
93888
+ outputRoot,
93889
+ relativeDirPath: paths.relativeDirPath,
93890
+ relativeFilePath: paths.relativeFilePath,
93891
+ fileContent,
93892
+ validate,
93893
+ global: true
93894
+ });
93895
+ }
93896
+ static async fromRulesyncPermissions({ outputRoot = process.cwd(), rulesyncPermissions, logger, global = false }) {
93897
+ if (!global) throw new Error(GITLABDUO_GLOBAL_ONLY_MESSAGE);
93898
+ const paths = GitlabduoPermissions.getSettablePaths({ global });
93899
+ const filePath = (0, node_path.join)(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
93900
+ const existingContent = await readFileContentOrNull(filePath) ?? "";
93901
+ const baseContent = existingContent.trim() === "" ? "{}" : existingContent;
93902
+ const existing = parseSettings({
93903
+ content: baseContent,
93904
+ filePath
93905
+ })[PERMISSIONS_KEY];
93906
+ const generated = convertRulesyncToGitlabduoStatements({
93907
+ config: rulesyncPermissions.getJson(),
93908
+ logger
93909
+ });
93910
+ let fileContent = baseContent;
93911
+ 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.`);
93912
+ else {
93913
+ const statements = [...(existing ?? []).filter((statement) => !(isPlainObject(statement) && statement.action === COMMAND_TOOL_NAME)), ...generated];
93914
+ if (statements.length > 0 || existing !== void 0) {
93915
+ const edits = (0, jsonc_parser.modify)(baseContent, [PERMISSIONS_KEY], statements.length > 0 ? statements : void 0, { formattingOptions: {
93916
+ insertSpaces: true,
93917
+ tabSize: 2
93918
+ } });
93919
+ fileContent = (0, jsonc_parser.applyEdits)(baseContent, edits);
93920
+ }
93921
+ }
93922
+ return new GitlabduoPermissions({
93923
+ outputRoot,
93924
+ relativeDirPath: paths.relativeDirPath,
93925
+ relativeFilePath: paths.relativeFilePath,
93926
+ fileContent,
93927
+ validate: true,
93928
+ global: true
93929
+ });
93930
+ }
93931
+ toRulesyncPermissions() {
93932
+ const selfPath = (0, node_path.join)(this.getRelativeDirPath(), this.getRelativeFilePath());
93933
+ const raw = parseSettings({
93934
+ content: this.getFileContent() || "{}",
93935
+ filePath: selfPath
93936
+ })[PERMISSIONS_KEY];
93937
+ const statements = Array.isArray(raw) ? raw : [];
93938
+ 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}.`);
93939
+ const bash = {};
93940
+ const skippedAllows = [];
93941
+ for (const statement of statements) {
93942
+ if (!isDuoPermissionStatement(statement) || statement.action !== COMMAND_TOOL_NAME) continue;
93943
+ const { resource, effect } = statement;
93944
+ if (effect === "allow" && (GLOB_CHARACTERS.test(resource) || toGitlabduoCommandResource(resource) !== resource)) {
93945
+ skippedAllows.push(resource);
93946
+ continue;
93947
+ }
93948
+ const previous = bash[resource];
93949
+ if (previous === void 0 || rank(effect) > rank(previous)) bash[resource] = effect;
93950
+ }
93951
+ 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.`);
93952
+ const config = { permission: Object.keys(bash).length > 0 ? { [SHELL_PERMISSION_CATEGORY]: bash } : {} };
93953
+ return RulesyncPermissions.fromImportedFileContent({
93954
+ outputRoot: this.outputRoot,
93955
+ sourcePath: this.getRelativePathFromCwd(),
93956
+ fileContent: JSON.stringify(config, null, 2)
93957
+ });
93958
+ }
93959
+ };
93960
+ function rank(effect) {
93961
+ return effect === "deny" ? 2 : effect === "ask" ? 1 : 0;
93962
+ }
93963
+ function isDuoPermissionStatement(value) {
93964
+ return isPlainObject(value) && typeof value.action === "string" && value.action.length > 0 && typeof value.resource === "string" && (value.effect === "allow" || value.effect === "ask" || value.effect === "deny");
93965
+ }
93966
+ function parseSettings({ content, filePath }) {
93967
+ let parsed;
93968
+ try {
93969
+ parsed = parseJsonc$6(content);
93970
+ } catch (error) {
93971
+ throw new Error(`Failed to parse GitLab Duo CLI settings at ${filePath}: ${formatError(error)}`, { cause: error });
93972
+ }
93973
+ if (!isPlainObject(parsed)) throw new Error(`GitLab Duo CLI settings at ${filePath} must contain a JSON object.`);
93974
+ return parsed;
93975
+ }
93976
+ /**
93977
+ * A canonical command pattern as Duo's token matcher reads it: trimmed, runs
93978
+ * of whitespace collapsed to one space (Duo splits a command into words, so
93979
+ * `git push` and `git push` are one command), and a trailing `:*` ("any
93980
+ * arguments") spelled ` *`.
93981
+ */
93982
+ function normalizeGitlabduoCommandPattern(pattern) {
93983
+ let normalized = pattern.trim();
93984
+ if (TRAILING_ARGUMENT_WILDCARD.test(normalized)) normalized = `${normalized.slice(0, -2)} *`;
93985
+ return normalized.trim().split(/\s+/).join(" ");
93986
+ }
93987
+ /**
93988
+ * The Duo `resource` for a canonical `bash` allow pattern, or `null` when the
93989
+ * server would refuse it or read it differently from what it says. The result
93990
+ * never matches a command the canonical pattern does not match.
93991
+ */
93992
+ function toGitlabduoCommandResource(pattern) {
93993
+ const resource = normalizeGitlabduoCommandPattern(pattern);
93994
+ if (resource === "" || resource === "*" || resource.length > MAX_PATTERN_LENGTH) return null;
93995
+ if (UNSUPPORTED_PATTERN_CHARACTERS.test(resource)) return null;
93996
+ if (resource.includes("**")) return null;
93997
+ return resource;
93998
+ }
93999
+ /**
94000
+ * Convert the canonical config into the `run_command` allow statements Duo CLI
94001
+ * enforces, reporting every rule that could not be carried.
94002
+ */
94003
+ function convertRulesyncToGitlabduoStatements({ config, logger }) {
94004
+ const { rules, foreignRestrictingCategories, ignoredAllToolsAllowPatterns } = collectShellCommandRules(config.permission);
94005
+ const restrictions = (0, es_toolkit.uniq)(rules.filter(({ action }) => action !== "allow").flatMap(({ pattern }) => [
94006
+ pattern,
94007
+ normalizeGitlabduoCommandPattern(pattern),
94008
+ normalizeGitlabduoCommandPattern(pattern.replaceAll(SHELL_QUOTING_CHARACTERS, ""))
94009
+ ]).filter((pattern) => pattern !== "")).map((pattern) => ({
94010
+ pattern,
94011
+ fromAllToolsCategory: false
94012
+ }));
94013
+ const budget = createIntersectionBudget();
94014
+ const shadowingRestrictions = createShadowingRestrictionsTest(restrictions, { budget });
94015
+ const resources = [];
94016
+ const shadowedAllowPatterns = [];
94017
+ const unsupportedPatterns = [];
94018
+ for (const { pattern, action } of rules) {
94019
+ if (action !== "allow") continue;
94020
+ const resource = toGitlabduoCommandResource(pattern);
94021
+ if (resource === null) {
94022
+ unsupportedPatterns.push(pattern);
94023
+ continue;
94024
+ }
94025
+ if (shadowingRestrictions(resource).length > 0) {
94026
+ shadowedAllowPatterns.push(pattern);
94027
+ continue;
94028
+ }
94029
+ resources.push(resource);
94030
+ }
94031
+ warnAboutUnwrittenCommandRules({
94032
+ toolLabel: TOOL_LABEL,
94033
+ surfaceLabel: `${PERMISSIONS_KEY} statements for ${COMMAND_TOOL_NAME}`,
94034
+ foreignRestrictingCategories,
94035
+ shadowedAllowPatterns: (0, es_toolkit.uniq)(shadowedAllowPatterns),
94036
+ ignoredAllToolsAllowPatterns,
94037
+ intersectionBudgetExhausted: budget.remaining === 0,
94038
+ logger
94039
+ });
94040
+ const denyPatterns = (0, es_toolkit.uniq)(rules.filter(({ action }) => action === "deny").map(({ pattern }) => pattern));
94041
+ 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.`);
94042
+ const foreignAllowCategories = Object.entries(config.permission).filter(([category, categoryRules]) => category !== "bash" && category !== "*" && Object.values(categoryRules).includes("allow")).map(([category]) => category);
94043
+ 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.`);
94044
+ 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.`);
94045
+ return (0, es_toolkit.uniq)(resources).map((resource) => ({
94046
+ action: COMMAND_TOOL_NAME,
94047
+ resource,
94048
+ effect: "allow"
94049
+ }));
94050
+ }
92993
94051
  // src/features/permissions/goose-permissions.ts
92994
94052
  const GOOSE_GLOBAL_ONLY_MESSAGE = "Goose permissions are global-only; use --global to sync ~/.config/goose/permission.yaml";
92995
94053
  const GOOSE_USER_KEY = "user";
@@ -105308,6 +106366,13 @@ const toolPermissionsFactories = /* @__PURE__ */ new Map([
105308
106366
  supportsGlobal: true
105309
106367
  }
105310
106368
  }],
106369
+ ["gitlabduo", {
106370
+ class: GitlabduoPermissions,
106371
+ meta: {
106372
+ supportsProject: false,
106373
+ supportsGlobal: true
106374
+ }
106375
+ }],
105311
106376
  ["goose", {
105312
106377
  class: GoosePermissions,
105313
106378
  meta: {