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.
@@ -904,6 +904,7 @@ const permissionsProcessorToolTargetTuple = [
904
904
  "deepagents",
905
905
  "devin",
906
906
  "factorydroid",
907
+ "gitlabduo",
907
908
  "goose",
908
909
  "grokcli",
909
910
  "hermesagent",
@@ -5563,20 +5564,57 @@ const CANONICAL_TO_BOB_EVENT_NAMES = {
5563
5564
  stop: "Stop"
5564
5565
  };
5565
5566
  /**
5566
- * Hook events supported by IBM Bob's lifecycle hooks.
5567
+ * Hook events rulesync emits for IBM Bob from the shared `hooks` block.
5567
5568
  *
5568
5569
  * Bob reads `hooks` from `.bob/settings.json` (project) and
5569
5570
  * `~/.bob/settings/settings.json` (user) in the Claude-Code shape and fires
5570
- * seven events: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse,
5571
- * PreCompact, PostCompact and Stop (Bob IDE and Bob Shell list the same
5572
- * seven). Handlers are `command` or `http` hooks. `matcher` is a regex matched
5573
- * against the tool name on PreToolUse / PostToolUse, `source` on SessionStart
5574
- * and `trigger` on PreCompact / PostCompact; the other events ignore it.
5571
+ * seven documented events: SessionStart, UserPromptSubmit, PreToolUse,
5572
+ * PostToolUse, PreCompact, PostCompact and Stop (Bob IDE and Bob Shell list
5573
+ * the same seven). Handlers are `command` or `http` hooks. Bob Shell 2.1.0
5574
+ * adds more events; see {@link BOB_OPT_IN_HOOK_EVENTS} for why they are not
5575
+ * emitted from the shared block.
5575
5576
  *
5576
5577
  * @see https://bob.ibm.com/docs/shell/configuration/lifecycle-hooks
5577
5578
  * @see https://bob.ibm.com/docs/ide/configuration/lifecycle-hooks
5578
5579
  */
5579
5580
  const BOB_HOOK_EVENTS = eventsOf(CANONICAL_TO_BOB_EVENT_NAMES);
5581
+ /**
5582
+ * The {@link BOB_HOOK_EVENTS} whose `matcher` regex Bob applies: the tool name
5583
+ * on PreToolUse / PostToolUse, `source` on SessionStart and `trigger` on
5584
+ * PreCompact / PostCompact. UserPromptSubmit and Stop have no matchable value.
5585
+ */
5586
+ const BOB_MATCHER_HOOK_EVENTS = BOB_HOOK_EVENTS.filter((event) => event !== "beforeSubmitPrompt" && event !== "stop");
5587
+ /**
5588
+ * Canonical events that Bob Shell 2.1.0 (`@ibm/bob` on npm, 2026-11-09) can
5589
+ * fire under the native name given here, next to the override-only
5590
+ * `PermissionResolved`. They are not on the lifecycle-hooks pages yet.
5591
+ *
5592
+ * They are deliberately not emitted from the shared `hooks` block: Bob Shell
5593
+ * before 2.1.0 validates the `hooks` object strictly against the seven
5594
+ * documented keys, and on any unknown key it ignores that settings file's
5595
+ * whole `hooks` block (PreToolUse guards included). Writing them must
5596
+ * therefore be an explicit opt-in under the `bob.hooks` override block, by
5597
+ * their native name, which is emitted verbatim and imported back there.
5598
+ *
5599
+ * @see https://registry.npmjs.org/@ibm/bob/-/bob-2.1.0.tgz
5600
+ */
5601
+ const BOB_OPT_IN_HOOK_EVENTS = {
5602
+ sessionEnd: "SessionEnd",
5603
+ permissionRequest: "PermissionRequest",
5604
+ notification: "Notification"
5605
+ };
5606
+ /**
5607
+ * Every native event key Bob Shell 2.1.0's strict hooks schema accepts: the
5608
+ * seven documented events, the three opt-in ones and `PermissionResolved`,
5609
+ * which has no canonical counterpart. Any other key under `bob.hooks` is
5610
+ * dropped on generate, because one unknown key makes Bob ignore the file's
5611
+ * whole hooks block.
5612
+ */
5613
+ const BOB_NATIVE_HOOK_EVENTS = [
5614
+ ...Object.values(CANONICAL_TO_BOB_EVENT_NAMES),
5615
+ ...Object.values(BOB_OPT_IN_HOOK_EVENTS),
5616
+ "PermissionResolved"
5617
+ ];
5580
5618
  const BOB_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_BOB_EVENT_NAMES);
5581
5619
  const CANONICAL_TO_TABNINE_EVENT_NAMES = {
5582
5620
  sessionStart: "SessionStart",
@@ -5859,17 +5897,18 @@ const CONTINUE_TO_CANONICAL_EVENT_NAMES = invertRecord(CANONICAL_TO_CONTINUE_EVE
5859
5897
  * observers, `gateway_platform_event` and `transform_api_error_classification`.
5860
5898
  * Shell hooks are gated on the same set.
5861
5899
  *
5862
- * Verified against the tag `v0.23.2`: `VALID_HOOKS` holds 48 entries, grown
5900
+ * Verified against the tag `v0.23.4`: `VALID_HOOKS` holds 50 entries, grown
5863
5901
  * from 23 at `v2026.8.3` (v0.20.0) and 37 at `v2026.8.16` (v0.20.2) — v0.21
5864
5902
  * added `agent_loop_stopped` and `on_room_member_activity`, v0.21.5 added
5865
5903
  * `pre_auxiliary_call` and `post_auxiliary_call`, v0.21.6 added
5866
5904
  * `post_gateway_admission`, `on_human_input_request` and
5867
5905
  * `on_human_input_resolved`, v0.22.3 added `on_session_delete` and
5868
- * `post_compaction`, and v0.23.1 added `on_session_open` and
5869
- * `post_curator_run`. This list holds 47 of them — see
5906
+ * `post_compaction`, v0.23.1 added `on_session_open` and
5907
+ * `post_curator_run`, and v0.23.4 added `on_session_prompt` and
5908
+ * `on_session_prompt_settled`. This list holds 49 of them — see
5870
5909
  * {@link HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS} for the exclusion.
5871
5910
  *
5872
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py
5911
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/hermes_cli/plugins.py
5873
5912
  */
5874
5913
  const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5875
5914
  "pre_tool_call",
@@ -5895,6 +5934,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5895
5934
  "on_session_reset",
5896
5935
  "on_session_delete",
5897
5936
  "on_session_open",
5937
+ "on_session_prompt",
5938
+ "on_session_prompt_settled",
5898
5939
  "on_skill_lifecycle",
5899
5940
  "subagent_start",
5900
5941
  "subagent_stop",
@@ -5930,8 +5971,8 @@ const HERMESAGENT_NATIVE_HOOK_EVENTS = [
5930
5971
  * rulesync only ever writes shell hooks, so these are excluded from
5931
5972
  * {@link HERMESAGENT_NATIVE_HOOK_EVENTS} and warned about with their own message.
5932
5973
  *
5933
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5934
- * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.2/agent/shell_hooks.py — `_parse_hooks_block`
5974
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/hermes_cli/plugins.py — `SHELL_UNSUPPORTED_HOOKS`
5975
+ * @see https://github.com/NousResearch/hermes-agent/blob/v0.23.4/agent/shell_hooks.py — `_parse_hooks_block`
5935
5976
  */
5936
5977
  const HERMESAGENT_SHELL_UNSUPPORTED_HOOK_EVENTS = ["transform_api_error_classification"];
5937
5978
  /**
@@ -5951,8 +5992,8 @@ const CANONICAL_TO_HERMESAGENT_EVENT_NAMES = {
5951
5992
  /**
5952
5993
  * Hook events supported by Hermes Agent's native Shell Hooks system.
5953
5994
  *
5954
- * Hermes validates hook events against a fixed `VALID_HOOKS` set — 48 entries as
5955
- * of v0.23.2 (tag `v0.23.2`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
5995
+ * Hermes validates hook events against a fixed `VALID_HOOKS` set — 50 entries as
5996
+ * of v0.23.4 (tag `v0.23.4`); see {@link HERMESAGENT_NATIVE_HOOK_EVENTS} for the
5956
5997
  * full list. Only the events with a clean 1:1 canonical equivalent are mapped
5957
5998
  * here. All other native events round-trip through `hermesagent.hooks`.
5958
5999
  * @see https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/hooks.md
@@ -9769,6 +9810,7 @@ const PermissionsConfigSchema = z.looseObject({
9769
9810
  commandcode: z.optional(CommandcodePermissionsOverrideSchema),
9770
9811
  lettacode: z.optional(CanonicalPermissionsOverrideSchema),
9771
9812
  crush: z.optional(CanonicalPermissionsOverrideSchema),
9813
+ gitlabduo: z.optional(CanonicalPermissionsOverrideSchema),
9772
9814
  goose: z.optional(CanonicalPermissionsOverrideSchema),
9773
9815
  omp: z.optional(OmpPermissionsOverrideSchema),
9774
9816
  pool: z.optional(CanonicalPermissionsOverrideSchema),
@@ -18278,6 +18320,14 @@ const GITLABDUO_DIR = join(".gitlab", "duo");
18278
18320
  const GITLABDUO_RULE_FILE_NAME = "chat-rules.md";
18279
18321
  /** MCP servers. @see https://docs.gitlab.com/user/gitlab_duo/model_context_protocol/mcp_clients/ */
18280
18322
  const GITLABDUO_MCP_FILE_NAME = "mcp.json";
18323
+ /**
18324
+ * Settings. Only the user file `~/.gitlab/duo/settings.json` carries the
18325
+ * `permissions` setting rulesync writes; the project files are deliberately not
18326
+ * read for it.
18327
+ *
18328
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/definitions.ts
18329
+ */
18330
+ const GITLABDUO_SETTINGS_FILE_NAME = "settings.json";
18281
18331
  /** Lifecycle hooks (experiment). @see https://docs.gitlab.com/user/gitlab_duo_cli/customize/ */
18282
18332
  const GITLABDUO_HOOKS_FILE_NAME = "hooks.json";
18283
18333
  /** Merge request review instructions. @see https://docs.gitlab.com/user/project/merge_requests/duo_in_merge_requests/ */
@@ -37068,8 +37118,208 @@ const VIBE_PROMPTS_DIR_PATH = join(".vibe", "prompts");
37068
37118
  * @see https://github.com/mistralai/mistral-vibe/blob/v3.0.3/vibe/core/agents/models.py
37069
37119
  */
37070
37120
  const VIBE_RESERVED_AGENT_NAME = "main";
37121
+ /**
37122
+ * The approval policies Vibe ships since v3.1.4. `AgentRegistry._discover`
37123
+ * never loads an agents-directory file named after one as an agent, whatever
37124
+ * its `agent_type`: from a project's `.vibe/agents/` the file is ignored with
37125
+ * an `approval_policy.project_override_ignored` config issue, and from
37126
+ * `~/.vibe/agents/` it redefines that approval policy for every session. Vibe
37127
+ * compares the file stem exactly (`agent.name in BUILTIN_APPROVAL_POLICIES`).
37128
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/registry.py
37129
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/models.py
37130
+ */
37131
+ const VIBE_APPROVAL_POLICY_NAMES = /* @__PURE__ */ new Set([
37132
+ "ask",
37133
+ "accept-edits",
37134
+ "smart-approve",
37135
+ "auto-approve"
37136
+ ]);
37137
+ function vibeAgentFileStem(relativeFilePath) {
37138
+ return basename(relativeFilePath).replace(/\.(md|toml)$/, "");
37139
+ }
37071
37140
  function isReservedVibeAgentFileName(relativeFilePath) {
37072
- return basename(relativeFilePath).replace(/\.(md|toml)$/, "").toLowerCase() === VIBE_RESERVED_AGENT_NAME;
37141
+ return vibeAgentFileStem(relativeFilePath).toLowerCase() === VIBE_RESERVED_AGENT_NAME;
37142
+ }
37143
+ function isVibeApprovalPolicyFileName(relativeFilePath) {
37144
+ return VIBE_APPROVAL_POLICY_NAMES.has(vibeAgentFileStem(relativeFilePath));
37145
+ }
37146
+ /**
37147
+ * The keys Vibe ignores on a custom `agent_type = "agent"` profile since
37148
+ * v3.1.4, listing each as a config issue: `_agent_settings` drops every
37149
+ * `VibeConfigSchema` field outside its `_AGENT_KEYS`, plus `safety` and
37150
+ * `approval_policy`, because what runs without asking belongs to the approval
37151
+ * policy, not to the agent. A key outside this list is kept, as Vibe keeps it:
37152
+ * an agent key passes, and an unknown key (a typo such as `disabled_tool`)
37153
+ * stays so Vibe can report it — or refuse it under `strict_config`.
37154
+ * Generated from the `VibeConfigSchema` fields of v3.1.5 minus `_AGENT_KEYS`.
37155
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/models.py
37156
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/config/vibe_schema.py
37157
+ */
37158
+ const VIBE_AGENT_IGNORED_KEYS = /* @__PURE__ */ new Set([
37159
+ "safety",
37160
+ "approval_policy",
37161
+ "catalog_model_aliases",
37162
+ "catalog_recommended_model",
37163
+ "catalog_default_model",
37164
+ "utility_models",
37165
+ "active_transcribe_model",
37166
+ "transcribe_providers",
37167
+ "transcribe_models",
37168
+ "active_tts_model",
37169
+ "tts_providers",
37170
+ "tts_models",
37171
+ "outside_workdir",
37172
+ "mcp_servers",
37173
+ "enable_connectors",
37174
+ "enable_mcp",
37175
+ "experimental_enable_document_library_connector",
37176
+ "experimental_enable_mistral_mcp_connector",
37177
+ "connectors",
37178
+ "agent_paths",
37179
+ "enabled_agents",
37180
+ "disabled_agents",
37181
+ "installed_agents",
37182
+ "default_agent",
37183
+ "default_approval_policy",
37184
+ "vibe_bot_max_approval_policy",
37185
+ "vibe_bot_local_tools",
37186
+ "vibe_bot_local_tool_max_bytes",
37187
+ "smart_approve_available",
37188
+ "enable_auto_approve",
37189
+ "enabled_plugins",
37190
+ "disabled_plugins",
37191
+ "experimental_enable_remote_plugins",
37192
+ "experimental_enable_registry_skills",
37193
+ "enable_model_catalog",
37194
+ "enable_builtin_models",
37195
+ "experimental_enable_storage_usage",
37196
+ "enable_pr_monitoring",
37197
+ "experimental_local_runtime_session_api",
37198
+ "experimental_target_runtime",
37199
+ "enable_otel",
37200
+ "otel_endpoint",
37201
+ "otel_redaction",
37202
+ "console_base_url",
37203
+ "theme",
37204
+ "applied_migrations",
37205
+ "disable_welcome_banner_animation",
37206
+ "disable_selection_animation",
37207
+ "cursor_blink",
37208
+ "vim_keybindings",
37209
+ "show_dangerous_directory_warning",
37210
+ "autocopy_to_clipboard",
37211
+ "enable_mouse_capture",
37212
+ "enable_sticky_prompt",
37213
+ "collapse_turn_details",
37214
+ "enable_file_autocomplete",
37215
+ "file_watcher_for_autocomplete",
37216
+ "ask_confirmation_on_exit",
37217
+ "displayed_workdir",
37218
+ "context_warnings",
37219
+ "voice_mode_enabled",
37220
+ "narrator_enabled",
37221
+ "show_thinking_nodes",
37222
+ "show_subagent_status_list",
37223
+ "worktree_limit",
37224
+ "auto_worktree",
37225
+ "worktree_copy_on_write",
37226
+ "bypass_tool_permissions",
37227
+ "raise_on_compaction_failure",
37228
+ "enable_telemetry",
37229
+ "managed_shell_tools_enabled",
37230
+ "enable_background_processes",
37231
+ "enable_subagents",
37232
+ "max_subagents",
37233
+ "max_concurrent_subagents",
37234
+ "compaction_prompt_id",
37235
+ "title_prompt_id",
37236
+ "include_commit_signature",
37237
+ "include_model_info",
37238
+ "include_project_context",
37239
+ "include_prompt_detail",
37240
+ "strict_config",
37241
+ "enable_update_checks",
37242
+ "enable_auto_update",
37243
+ "enable_notifications",
37244
+ "keep_awake",
37245
+ "experimental_enable_tab_status",
37246
+ "enable_system_trust_store",
37247
+ "api_timeout",
37248
+ "api_retry_max_elapsed_time",
37249
+ "max_goal_token_budget",
37250
+ "api_stream_idle_timeout",
37251
+ "agent_max_output_tokens",
37252
+ "compaction_max_output_tokens",
37253
+ "compaction_reasoning_limit_tokens",
37254
+ "output_limit_retries",
37255
+ "api_connect_timeout",
37256
+ "api_write_timeout",
37257
+ "api_pool_timeout",
37258
+ "vibe_base_url",
37259
+ "vibe_code_sessions_base_url",
37260
+ "log_level",
37261
+ "project_context",
37262
+ "session_logging",
37263
+ "experiments"
37264
+ ]);
37265
+ /**
37266
+ * The legacy key Vibe folds into `disabled_tools` before it filters an agent
37267
+ * profile (`migrate_agent_profile_config`).
37268
+ * @see https://github.com/mistralai/mistral-vibe/blob/v3.1.5/vibe/core/agents/_migration.py
37269
+ */
37270
+ const VIBE_LEGACY_BASE_DISABLED_KEY = "base_disabled";
37271
+ /** Per tool, an agent keeps only the shell timeouts and a narrowing `permission`. */
37272
+ const VIBE_AGENT_TOOL_KEYS = /* @__PURE__ */ new Set(["default_timeout", "max_timeout_seconds"]);
37273
+ const VIBE_AGENT_NARROWING_PERMISSIONS = /* @__PURE__ */ new Set(["ask", "never"]);
37274
+ /**
37275
+ * Fold a legacy `base_disabled` list into `disabled_tools` the way Vibe's
37276
+ * `migrate_agent_profile_config` does, so the restriction it carries is kept.
37277
+ */
37278
+ function migrateVibeBaseDisabled(tomlObj) {
37279
+ const legacyDisabled = tomlObj[VIBE_LEGACY_BASE_DISABLED_KEY];
37280
+ if (!Array.isArray(legacyDisabled)) return tomlObj;
37281
+ const rest = Object.fromEntries(Object.entries(tomlObj).filter(([key]) => key !== VIBE_LEGACY_BASE_DISABLED_KEY));
37282
+ const disabledTools = rest.disabled_tools;
37283
+ return {
37284
+ ...rest,
37285
+ disabled_tools: Array.isArray(disabledTools) ? [.../* @__PURE__ */ new Set([...disabledTools, ...legacyDisabled])] : legacyDisabled
37286
+ };
37287
+ }
37288
+ /**
37289
+ * Drop the settings Vibe ignores on an `agent_type = "agent"` profile, so the
37290
+ * generated file does not pretend to grant what Vibe refuses. Mirrors Vibe's
37291
+ * `_agent_settings`; returns the kept TOML object and the dotted keys that
37292
+ * were dropped.
37293
+ */
37294
+ function stripVibeAgentIgnoredSettings(tomlObj) {
37295
+ const kept = {};
37296
+ const dropped = [];
37297
+ for (const [key, value] of Object.entries(migrateVibeBaseDisabled(tomlObj))) {
37298
+ if (VIBE_AGENT_IGNORED_KEYS.has(key)) {
37299
+ dropped.push(key);
37300
+ continue;
37301
+ }
37302
+ if (key !== "tools" || typeof value !== "object" || value === null || Array.isArray(value)) {
37303
+ kept[key] = value;
37304
+ continue;
37305
+ }
37306
+ const tools = {};
37307
+ for (const [tool, settings] of Object.entries(value)) {
37308
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) {
37309
+ dropped.push(`tools.${tool}`);
37310
+ continue;
37311
+ }
37312
+ const own = {};
37313
+ 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;
37314
+ else dropped.push(`tools.${tool}.${setting}`);
37315
+ if (Object.keys(own).length > 0) tools[tool] = own;
37316
+ }
37317
+ if (Object.keys(tools).length > 0) kept.tools = tools;
37318
+ }
37319
+ return {
37320
+ kept,
37321
+ dropped: dropped.toSorted()
37322
+ };
37073
37323
  }
37074
37324
  /**
37075
37325
  * Vibe resolves a `system_prompt_id` by file name, and
@@ -37149,7 +37399,7 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37149
37399
  validate: true
37150
37400
  });
37151
37401
  }
37152
- static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false }) {
37402
+ static fromRulesyncSubagent({ outputRoot = process.cwd(), rulesyncSubagent, validate = true, global = false, logger }) {
37153
37403
  const frontmatter = rulesyncSubagent.getFrontmatter();
37154
37404
  const rawSection = frontmatter.vibe ?? {};
37155
37405
  const vibeSection = this.filterToolSpecificSection(rawSection, [
@@ -37167,7 +37417,13 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37167
37417
  ...vibeSection,
37168
37418
  ...promptBody ? { system_prompt_id: slug } : {}
37169
37419
  };
37170
- const body = smolToml.stringify(tomlObj);
37420
+ let finalToml = tomlObj;
37421
+ if (tomlObj.agent_type === "agent") {
37422
+ const { kept, dropped } = stripVibeAgentIgnoredSettings(tomlObj);
37423
+ 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".`);
37424
+ finalToml = kept;
37425
+ }
37426
+ const body = smolToml.stringify(finalToml);
37171
37427
  const paths = this.getSettablePaths({ global });
37172
37428
  const relativeFilePath = rulesyncSubagent.getRelativeFilePath().replace(/\.md$/, ".toml");
37173
37429
  return new VibeSubagent({
@@ -37188,7 +37444,10 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37188
37444
  * with a warning.
37189
37445
  *
37190
37446
  * A subagent named `main` is skipped with a warning: Vibe reserves that name
37191
- * for hook matching and does not load an agent file called `main.toml`.
37447
+ * for hook matching and does not load an agent file called `main.toml`. So is
37448
+ * one named after an approval policy (`ask`, `accept-edits`, `smart-approve`,
37449
+ * `auto-approve`): Vibe ignores such a file in a project and treats it as a
37450
+ * redefinition of that policy in `~/.vibe/agents/`, never as an agent.
37192
37451
  */
37193
37452
  static fromRulesyncSubagents({ rulesyncSubagents, outputRoot = process.cwd(), global = false, logger }) {
37194
37453
  return rulesyncSubagents.flatMap((rulesyncSubagent) => {
@@ -37197,11 +37456,17 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37197
37456
  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.`);
37198
37457
  return [];
37199
37458
  }
37459
+ if (isVibeApprovalPolicyFileName(sourcePath)) {
37460
+ const policy = vibeAgentFileStem(sourcePath);
37461
+ 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.`);
37462
+ return [];
37463
+ }
37200
37464
  const agentFile = VibeSubagent.fromRulesyncSubagent({
37201
37465
  outputRoot,
37202
37466
  relativeDirPath: VibeSubagent.getSettablePaths({ global }).relativeDirPath,
37203
37467
  rulesyncSubagent,
37204
- global
37468
+ global,
37469
+ logger
37205
37470
  });
37206
37471
  const promptBody = rulesyncSubagent.getBody();
37207
37472
  if (!promptBody) return [agentFile];
@@ -37277,6 +37542,22 @@ var VibeSubagent = class VibeSubagent extends ToolSubagent {
37277
37542
  if (typeof promptId !== "string" || promptId === "" || /[\\/]/.test(promptId)) return;
37278
37543
  return await readFileContentOrNull(join(outputRoot, VIBE_PROMPTS_DIR_PATH, `${promptId}.md`)) ?? void 0;
37279
37544
  }
37545
+ /**
37546
+ * A file in `.vibe/agents/` named after an approval policy is not an agent:
37547
+ * in `~/.vibe/agents/` it is the user's override of that policy (often a
37548
+ * narrower one), and in a project Vibe ignores it. It is therefore neither
37549
+ * imported as a subagent (with a warning) nor swept as an orphan, since
37550
+ * deleting a narrowing override would fall back to the broader builtin.
37551
+ */
37552
+ static async isFileOwned({ relativeFilePath, forDeletion = false, logger }) {
37553
+ if (!isVibeApprovalPolicyFileName(relativeFilePath)) return true;
37554
+ 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.`);
37555
+ return false;
37556
+ }
37557
+ /** Never delete an approval-policy override; see {@link VibeSubagent.isFileOwned}. */
37558
+ isDeletable() {
37559
+ return this.promptFile || !isVibeApprovalPolicyFileName(this.getRelativeFilePath());
37560
+ }
37280
37561
  static forDeletion({ outputRoot = process.cwd(), relativeDirPath, relativeFilePath, global = false }) {
37281
37562
  return new VibeSubagent({
37282
37563
  outputRoot,
@@ -38450,7 +38731,9 @@ var SubagentsProcessor = class extends FeatureProcessor {
38450
38731
  const ownership = await Promise.all(subagentFilePaths.map((path) => factory.class.isFileOwned({
38451
38732
  outputRoot: rootOutputRoot,
38452
38733
  relativeDirPath: dirPath,
38453
- relativeFilePath: toRelativeFilePath(path)
38734
+ relativeFilePath: toRelativeFilePath(path),
38735
+ forDeletion,
38736
+ logger: this.logger
38454
38737
  })));
38455
38738
  ownedFilePaths = subagentFilePaths.filter((_, index) => ownership[index]);
38456
38739
  }
@@ -46479,10 +46762,18 @@ var MimocodeRule = class extends OpenCodeRule {
46479
46762
  * from the working directory to the `.git` boundary and loads one instruction
46480
46763
  * file per directory level, preferring `AGENTS.md` over `CLAUDE.md` when both
46481
46764
  * exist. rulesync emits the project-root `AGENTS.md` (the same shared root file
46482
- * the agentsmd/codexcli targets write). Muse Code has user/global rules, but
46483
- * their path is not documented, so no global scope is supported here.
46484
- * (Verified against the official docs:
46485
- * https://dev.meta.ai/docs/muse-code/configuration.md)
46765
+ * the agentsmd/codexcli targets write). Muse Code also loads machine-wide user
46766
+ * rules; since 1.4.23 its changelog names `~/.claude/CLAUDE.md` as that file
46767
+ * (the filename of the alternative under Muse's own config directory is not
46768
+ * published). `~/.claude/CLAUDE.md` is exactly what the `claudecode` target
46769
+ * writes in global mode, so no global scope is supported here: emitting the
46770
+ * same file from two targets would make the result depend on target order.
46771
+ * `rulesync generate --targets claudecode --global` feeds Muse Code's user
46772
+ * rules instead, but only for the root rule (global non-root rules go to
46773
+ * `~/.claude/rules/*.md`, which Muse Code is not documented to read) and only
46774
+ * for rules that target `claudecode`. (Verified against the official docs:
46775
+ * https://dev.meta.ai/docs/muse-code/configuration and
46776
+ * https://dev.meta.ai/docs/muse-code/changelog)
46486
46777
  *
46487
46778
  * rulesync's topic-based non-root rules have no project subdirectory to map
46488
46779
  * onto, so their bodies are folded into the single root `AGENTS.md` by the
@@ -50897,9 +51188,10 @@ const AmpCheckFrontmatterSchema = z.looseObject({
50897
51188
  * Amp reads code review checks as Markdown files with YAML frontmatter,
50898
51189
  * scoped to the project (`.agents/checks/`) and user-wide (`~/.config/amp/checks/`;
50899
51190
  * Amp also reads `~/.config/agents/checks/`, which rulesync does not write).
50900
- * Since the docs rebuild the supported runner is the official
50901
- * `@amp/review-checks` plugin (`amp review` is deprecated); existing checks in
50902
- * this format continue to apply.
51191
+ * Amp has since removed `amp review` and deprecated project-defined checks
51192
+ * in `.agents/checks/`, together with the `@amp/review-checks` plugin that runs
51193
+ * them. rulesync keeps writing this format because Goose discovers the same
51194
+ * `.agents/checks/` directory and existing setups may still load the plugin.
50903
51195
  * @see https://ampcode.com/docs/review
50904
51196
  */
50905
51197
  var AmpCheck = class extends ToolCheck {
@@ -56478,9 +56770,12 @@ var SettingsJsonHooks = class extends ToolHooks {
56478
56770
  const config = rulesyncHooks.getJson();
56479
56771
  const generatedHooks = canonicalToToolHooks({
56480
56772
  config,
56481
- toolOverrideHooks: overrideHooksOf({
56482
- config,
56483
- overrideKey: this.getSpec().overrideKey
56773
+ toolOverrideHooks: knownOverrideHooks({
56774
+ hooks: overrideHooksOf({
56775
+ config,
56776
+ overrideKey: this.getSpec().overrideKey
56777
+ }),
56778
+ spec: this.getSpec()
56484
56779
  }),
56485
56780
  converterConfig: this.getConverterConfig(),
56486
56781
  logger
@@ -56543,6 +56838,16 @@ var SettingsJsonHooks = class extends ToolHooks {
56543
56838
  }
56544
56839
  };
56545
56840
  /**
56841
+ * The override hooks the tool can take: all of them, unless the spec lists
56842
+ * {@link SettingsJsonHooksSpec.knownOverrideEvents}, in which case only those
56843
+ * native names and the canonical supported events are kept.
56844
+ */
56845
+ function knownOverrideHooks({ hooks, spec }) {
56846
+ if (hooks === void 0 || spec.knownOverrideEvents === void 0) return hooks;
56847
+ const known = /* @__PURE__ */ new Set([...spec.converterConfig.supportedEvents, ...spec.knownOverrideEvents]);
56848
+ return Object.fromEntries(Object.entries(hooks).filter(([event]) => known.has(event)));
56849
+ }
56850
+ /**
56546
56851
  * The `hooks` map of a tool's override block (`config.<overrideKey>.hooks`),
56547
56852
  * or `undefined` when the block states none. The schema keeps every override
56548
56853
  * block loose, so the lookup goes through the record form.
@@ -56556,7 +56861,6 @@ function overrideHooksOf({ config, overrideKey }) {
56556
56861
  const hooks = override.hooks;
56557
56862
  return isPlainObject(hooks) ? hooks : void 0;
56558
56863
  }
56559
- // src/features/hooks/bob-hooks.ts
56560
56864
  const BOB_SPEC = {
56561
56865
  displayName: "Bob",
56562
56866
  overrideKey: "bob",
@@ -56565,11 +56869,12 @@ const BOB_SPEC = {
56565
56869
  canonicalToToolEventNames: CANONICAL_TO_BOB_EVENT_NAMES,
56566
56870
  toolToCanonicalEventNames: BOB_TO_CANONICAL_EVENT_NAMES,
56567
56871
  projectDirVar: "",
56568
- noMatcherEvents: /* @__PURE__ */ new Set(["beforeSubmitPrompt", "stop"]),
56872
+ noMatcherEvents: new Set(BOB_HOOK_EVENTS.filter((event) => !BOB_MATCHER_HOOK_EVENTS.includes(event))),
56569
56873
  supportedHookTypes: /* @__PURE__ */ new Set(["command", "http"]),
56570
56874
  importedHookTypeAliases: { https: "http" },
56571
56875
  wildcardMatcherMeansAll: true
56572
- }
56876
+ },
56877
+ knownOverrideEvents: BOB_NATIVE_HOOK_EVENTS
56573
56878
  };
56574
56879
  /**
56575
56880
  * IBM Bob lifecycle hooks.
@@ -59984,7 +60289,7 @@ function canonicalToHermesHooks({ config, toolOverrideHooks, logger }) {
59984
60289
  for (const [nativeEvent, definitions] of Object.entries(toolOverrideHooks ?? {})) {
59985
60290
  if (HERMESAGENT_CANONICAL_EVENTS.has(nativeEvent)) continue;
59986
60291
  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.`);
59987
- 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.`);
60292
+ 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.`);
59988
60293
  setHermesHookEntries({
59989
60294
  result,
59990
60295
  event: nativeEvent,
@@ -60661,7 +60966,9 @@ function buildRunHelperLinesFor(cwdExpression) {
60661
60966
  * hook denies it:
60662
60967
  * - exit code 2 → deny, with the command's stderr as the reason;
60663
60968
  * - exit code 0 with JSON stdout whose `hookSpecificOutput.permissionDecision`
60664
- * is `"deny"` → deny, with `permissionDecisionReason` as the reason;
60969
+ * is `"deny"` → deny, with `permissionDecisionReason` as the reason; when it
60970
+ * sets no `permissionDecision`, the deprecated top-level `decision: "block"`
60971
+ * that Claude Code still honors denies too, with `reason` as the reason;
60665
60972
  * - exit code 0 otherwise → allow;
60666
60973
  * - any other non-zero exit → deny too, with stderr or the exit code;
60667
60974
  * - more than 1 MiB of stdout → deny, without parsing it;
@@ -60696,12 +61003,13 @@ const PRE_TOOL_USE_RESULT_HELPER_LINES = [
60696
61003
  " } catch {",
60697
61004
  " return;",
60698
61005
  " }",
60699
- " const specific = parsed && typeof parsed === \"object\" ? parsed.hookSpecificOutput : undefined;",
60700
- " if (specific && typeof specific === \"object\" && specific.permissionDecision === \"deny\") {",
61006
+ " if (!parsed || typeof parsed !== \"object\") return;",
61007
+ " const specific = parsed.hookSpecificOutput;",
61008
+ " const hasDecision = typeof specific === \"object\" && specific !== null && specific.permissionDecision !== undefined;",
61009
+ " const reason = hasDecision ? specific.permissionDecisionReason : parsed.reason;",
61010
+ " if (hasDecision ? specific.permissionDecision === \"deny\" : parsed.decision === \"block\") {",
60701
61011
  " throw new Error(",
60702
- " (typeof specific.permissionDecisionReason === \"string\" &&",
60703
- " sanitizeBlockReason(specific.permissionDecisionReason)) ||",
60704
- " \"Blocked by a preToolUse hook.\",",
61012
+ " (typeof reason === \"string\" && sanitizeBlockReason(reason)) || \"Blocked by a preToolUse hook.\",",
60705
61013
  " );",
60706
61014
  " }",
60707
61015
  " return;",
@@ -62477,11 +62785,123 @@ const PI_SETTLE_BLOCKING_EVENT = "agent_before_settle";
62477
62785
  * @see https://github.com/can1357/oh-my-pi/blob/fa5ff4a3a977a28b93d025f4cf50f046e019f18c/packages/coding-agent/src/session/agent-session.ts
62478
62786
  */
62479
62787
  const OMP_SESSION_STOP_BLOCKING_EVENT = "session_stop";
62788
+ /**
62789
+ * Pi's `resolveToCwd` (`core/tools/path-utils.ts`), which calls
62790
+ * `resolvePath(path, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true })`
62791
+ * from `utils/paths.ts`: Unicode spaces become plain spaces, a leading `@` is
62792
+ * dropped, on Windows Git Bash / WSL drive paths are converted, `~` is
62793
+ * expanded, a `file://` URL is converted, and the result is resolved against
62794
+ * cwd. Pi has no URL passthrough, so any other `scheme://` text is a relative
62795
+ * path too.
62796
+ *
62797
+ * @see https://github.com/earendil-works/pi/blob/v1.6.0/packages/coding-agent/src/utils/paths.ts
62798
+ */
62799
+ const PI_PATH_RESOLVER_LINES = [
62800
+ "function absoluteToolPath(path: unknown, cwd: string): unknown {",
62801
+ " if (typeof path !== \"string\") return path;",
62802
+ " let normalized = path.replace(/[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g, \" \");",
62803
+ " if (normalized.startsWith(\"@\")) normalized = normalized.slice(1);",
62804
+ " if (process.platform === \"win32\" && normalized.startsWith(\"/\") && !normalized.startsWith(\"//\") && !normalized.includes(\"\\\\\")) {",
62805
+ " const drive = normalized.match(/^\\/(?:mnt\\/|cygdrive\\/)?([a-z])(?:\\/(.*))?$/i);",
62806
+ " if (drive?.[1]) normalized = `${drive[1].toUpperCase()}:\\\\${drive[2]?.replaceAll(\"/\", \"\\\\\") ?? \"\"}`;",
62807
+ " }",
62808
+ " if (normalized === \"~\") normalized = homedir();",
62809
+ " else if (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {",
62810
+ " normalized = joinPath(homedir(), normalized.slice(2));",
62811
+ " } else if (/^file:\\/\\//.test(normalized)) {",
62812
+ " try {",
62813
+ " normalized = fileURLToPath(normalized);",
62814
+ " } catch {",
62815
+ " return path;",
62816
+ " }",
62817
+ " }",
62818
+ " return resolvePath(cwd, normalized);",
62819
+ "}"
62820
+ ];
62821
+ /**
62822
+ * oh-my-pi's `resolveToCwd` (`tools/path-utils.ts`): `expandPath` strips a
62823
+ * stray leading `:` before a path shape, strips a leading `@` only before an
62824
+ * absolute path, `~` or an internal URL, turns Unicode spaces into plain
62825
+ * spaces, converts a `file://` URL and expands `~`; an internal URL is not a
62826
+ * filesystem path, a bare root (`/`) is the workspace root, and anything else
62827
+ * is resolved against cwd. Windows drive-alias handling is not mirrored.
62828
+ *
62829
+ * @see https://github.com/can1357/oh-my-pi/blob/76b7d843d59bc83cc40cd5decadc89dc808a14e6/packages/coding-agent/src/tools/path-utils.ts
62830
+ */
62831
+ const OMP_PATH_RESOLVER_LINES = [
62832
+ `const INTERNAL_URL_SCHEME = /^(?:${[
62833
+ "skill",
62834
+ "rule",
62835
+ "memory",
62836
+ "out",
62837
+ "agent",
62838
+ "history",
62839
+ "local",
62840
+ "proc",
62841
+ "cfg",
62842
+ "ssh",
62843
+ "security",
62844
+ "vault",
62845
+ "issue",
62846
+ "pr",
62847
+ "mr",
62848
+ "mcp",
62849
+ "omp",
62850
+ "help",
62851
+ "attachment",
62852
+ "conflict"
62853
+ ].join("|")}):\\/\\/?/i;`,
62854
+ "",
62855
+ "function absoluteToolPath(path: unknown, cwd: string): unknown {",
62856
+ " if (typeof path !== \"string\") return path;",
62857
+ " let normalized = /^:(?=[/\\\\~]|\\.\\.?[/\\\\]|[A-Za-z]:)/.test(path) ? path.slice(1) : path;",
62858
+ " if (normalized.startsWith(\"@\")) {",
62859
+ " const rest = normalized.slice(1);",
62860
+ " if (rest.startsWith(\"/\") || rest === \"~\" || rest.startsWith(\"~/\") || win32Path.isAbsolute(rest) || INTERNAL_URL_SCHEME.test(rest)) {",
62861
+ " normalized = rest;",
62862
+ " }",
62863
+ " }",
62864
+ " normalized = normalized.replace(/[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g, \" \");",
62865
+ " if (normalized.toLowerCase().startsWith(\"file://\")) {",
62866
+ " try {",
62867
+ " normalized = fileURLToPath(normalized);",
62868
+ " } catch {",
62869
+ " // oh-my-pi keeps an unconvertible `file://` text as written.",
62870
+ " }",
62871
+ " }",
62872
+ " if (normalized === \"~\") normalized = homedir();",
62873
+ " else if (normalized.startsWith(\"~/\")) normalized = joinPath(homedir(), normalized.slice(2));",
62874
+ " if (INTERNAL_URL_SCHEME.test(normalized)) return normalized;",
62875
+ " if (/^\\/+$/.test(normalized)) return resolvePath(cwd);",
62876
+ " return resolvePath(cwd, normalized);",
62877
+ "}"
62878
+ ];
62879
+ /**
62880
+ * Tool names both Pi and oh-my-pi share with a canonical counterpart. Pi's
62881
+ * `powershell` tool is deliberately left out: Rulesync has no canonical name
62882
+ * for it, so it keeps its own.
62883
+ */
62884
+ const SHARED_CANONICAL_TOOL_NAMES = {
62885
+ bash: "Bash",
62886
+ read: "Read",
62887
+ write: "Write",
62888
+ edit: "Edit",
62889
+ grep: "Grep"
62890
+ };
62480
62891
  const PI_EXTENSION_DIALECT = {
62481
62892
  overrideKey: "pi",
62482
62893
  typesPackage: "@earendil-works/pi-coding-agent",
62483
62894
  promptPassLine: "return { action: \"continue\" };",
62484
- promptCancelLine: "return { action: \"handled\" };"
62895
+ promptCancelLine: "return { action: \"handled\" };",
62896
+ toolNames: {
62897
+ ...SHARED_CANONICAL_TOOL_NAMES,
62898
+ find: "Glob"
62899
+ },
62900
+ editTextKeys: {
62901
+ old: "oldText",
62902
+ new: "newText"
62903
+ },
62904
+ pathResolverLines: PI_PATH_RESOLVER_LINES
62485
62905
  };
62486
62906
  /**
62487
62907
  * oh-my-pi's `emitInput` stops at the first result with `handled` set and
@@ -62493,7 +62913,16 @@ const OMP_EXTENSION_DIALECT = {
62493
62913
  overrideKey: "omp",
62494
62914
  typesPackage: "@oh-my-pi/pi-coding-agent",
62495
62915
  promptPassLine: "return {};",
62496
- promptCancelLine: "return { handled: true };"
62916
+ promptCancelLine: "return { handled: true };",
62917
+ toolNames: {
62918
+ ...SHARED_CANONICAL_TOOL_NAMES,
62919
+ glob: "Glob"
62920
+ },
62921
+ editTextKeys: {
62922
+ old: "old_string",
62923
+ new: "new_string"
62924
+ },
62925
+ pathResolverLines: OMP_PATH_RESOLVER_LINES
62497
62926
  };
62498
62927
  const PI_BLOCKING_MODE_BY_EVENT = {
62499
62928
  [PI_BLOCKING_EVENT]: "tool",
@@ -62517,7 +62946,284 @@ function failureLinesByMode(dialect) {
62517
62946
  };
62518
62947
  }
62519
62948
  /**
62520
- * Helper emitted alongside blocking handlers. `promisify(exec)` rejects on a
62949
+ * Canonical events whose command receives Claude Code's JSON input for the
62950
+ * event on stdin, mapped to its `hook_event_name`; every other command gets an
62951
+ * empty stdin, as in the OpenCode-style plugin (`STDIN_PAYLOADS` in
62952
+ * `opencode-style-generator.ts`). All three ride on Pi's tool events, whose
62953
+ * `event.toolName`, `event.toolCallId` and `event.input` the payload is built
62954
+ * from. A payload is serialized lazily, once per invocation, by the first
62955
+ * handler that runs.
62956
+ *
62957
+ * @see https://github.com/earendil-works/pi/blob/v1.6.0/packages/coding-agent/docs/extensions.md#tool_call
62958
+ * @see https://code.claude.com/docs/en/hooks
62959
+ */
62960
+ const STDIN_PAYLOAD_EVENTS = {
62961
+ preToolUse: "PreToolUse",
62962
+ postToolUse: "PostToolUse",
62963
+ postToolUseFailure: "PostToolUseFailure"
62964
+ };
62965
+ /**
62966
+ * The fields each payload adds to the tool call's own (`session_id`, `cwd`,
62967
+ * `hook_event_name`, `tool_name`, `tool_input`, `tool_use_id`), as TypeScript
62968
+ * object entries evaluated against the `tool_result` event.
62969
+ */
62970
+ const STDIN_PAYLOAD_EXTRA_FIELDS = {
62971
+ PreToolUse: "",
62972
+ PostToolUse: "tool_response: { content: event.content, details: event.details }",
62973
+ PostToolUseFailure: "error: toolResultText(event.content)"
62974
+ };
62975
+ /**
62976
+ * Helpers emitted when a handler receives a stdin payload or tests a matcher.
62977
+ *
62978
+ * `claudeToolName` maps the dialect's built-in tool names to the canonical
62979
+ * Claude Code names Rulesync uses elsewhere (`bash` → `Bash`, ...). MCP tools
62980
+ * are already named `mcp__<server>__<tool>` by Pi, and other tools keep their
62981
+ * own name.
62982
+ *
62983
+ * `claudeToolInput` passes the tool's arguments through, except for the file
62984
+ * tools: `path` becomes Claude Code's absolute `file_path`, resolved against
62985
+ * the session cwd the way Pi's `resolveToCwd` does, and on Pi each `edits`
62986
+ * entry's `oldText` / `newText` becomes `old_string` / `new_string` (oh-my-pi
62987
+ * already uses those, see `editTextKeys`). When the call has no top-level
62988
+ * `old_string` / `new_string`, every edit's text is joined into them, as
62989
+ * Claude Code's `Edit` input carries, so a guard reading those sees every
62990
+ * change. The mapped keys are written last and any same-named key the model
62991
+ * added is dropped, so an extra argument (Pi's schemas allow them) cannot make
62992
+ * a guard check a different file or text than the one the tool acts on.
62993
+ */
62994
+ function buildToolPayloadHelperLines(dialect) {
62995
+ return [
62996
+ `const CLAUDE_TOOL_NAMES: Record<string, string> = ${JSON.stringify(dialect.toolNames)};`,
62997
+ "",
62998
+ "function claudeToolName(toolName: string): string {",
62999
+ " return Object.hasOwn(CLAUDE_TOOL_NAMES, toolName) ? (CLAUDE_TOOL_NAMES[toolName] ?? toolName) : toolName;",
63000
+ "}",
63001
+ "",
63002
+ "function matchesTool(matcher: RegExp, toolName: string): boolean {",
63003
+ " return matcher.test(toolName) || matcher.test(claudeToolName(toolName));",
63004
+ "}",
63005
+ "",
63006
+ ...dialect.pathResolverLines,
63007
+ "",
63008
+ `const EDIT_TEXT_KEYS = ${JSON.stringify(dialect.editTextKeys)};`,
63009
+ "const CLAUDE_EDIT_TEXT_KEYS = EDIT_TEXT_KEYS.old === \"old_string\";",
63010
+ "",
63011
+ "function claudeEditEntry(edit: unknown): unknown {",
63012
+ " if (CLAUDE_EDIT_TEXT_KEYS || !edit || typeof edit !== \"object\") return edit;",
63013
+ " const {",
63014
+ " [EDIT_TEXT_KEYS.old]: oldText,",
63015
+ " [EDIT_TEXT_KEYS.new]: newText,",
63016
+ " old_string: _old,",
63017
+ " new_string: _new,",
63018
+ " ...others",
63019
+ " } = edit as Record<string, unknown>;",
63020
+ " return { ...others, old_string: oldText, new_string: newText };",
63021
+ "}",
63022
+ "",
63023
+ "function joinedEditText(edits: unknown[], key: string): string | undefined {",
63024
+ " const texts = edits",
63025
+ " .map((edit: unknown) => (edit as Record<string, unknown> | null)?.[key])",
63026
+ " .filter((text): text is string => typeof text === \"string\");",
63027
+ " return texts.length > 0 ? texts.join(\"\\n\") : undefined;",
63028
+ "}",
63029
+ "",
63030
+ "function claudeToolInput(toolName: string, input: unknown, cwd: string): unknown {",
63031
+ " if (![\"read\", \"write\", \"edit\"].includes(toolName)) return input;",
63032
+ " if (!input || typeof input !== \"object\" || Array.isArray(input)) return input;",
63033
+ " const { path, file_path: _filePath, ...rest } = input as Record<string, unknown>;",
63034
+ " if (!CLAUDE_EDIT_TEXT_KEYS) {",
63035
+ " delete rest.old_string;",
63036
+ " delete rest.new_string;",
63037
+ " }",
63038
+ " // The raw `path` stays, so a guard can check what the model wrote too.",
63039
+ " const claudeInput: Record<string, unknown> = { ...rest, path, file_path: absoluteToolPath(path, cwd) };",
63040
+ " if (!Array.isArray(rest.edits)) return claudeInput;",
63041
+ " const edits = rest.edits.map(claudeEditEntry);",
63042
+ " return {",
63043
+ " ...claudeInput,",
63044
+ " edits,",
63045
+ " old_string: claudeInput.old_string ?? joinedEditText(edits, \"old_string\"),",
63046
+ " new_string: claudeInput.new_string ?? joinedEditText(edits, \"new_string\"),",
63047
+ " };",
63048
+ "}",
63049
+ "",
63050
+ "function toolResultText(content: unknown): string {",
63051
+ " if (!Array.isArray(content)) return \"\";",
63052
+ " return content",
63053
+ " .map((block: unknown) => {",
63054
+ " const part = block as { type?: unknown; text?: unknown } | null;",
63055
+ " return part?.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\";",
63056
+ " })",
63057
+ " .filter(Boolean)",
63058
+ " .join(\"\\n\");",
63059
+ "}",
63060
+ "",
63061
+ "type ToolHookEvent = { toolName: string; toolCallId?: string; input?: unknown };",
63062
+ "",
63063
+ "function toolHookInput(",
63064
+ " hookEventName: string,",
63065
+ " event: ToolHookEvent,",
63066
+ " ctx: ExtensionContext | undefined,",
63067
+ " extra: Record<string, unknown> = {},",
63068
+ "): string {",
63069
+ " const cwd = ctx?.cwd ?? process.cwd();",
63070
+ " return JSON.stringify({",
63071
+ " session_id: ctx?.sessionManager?.getSessionId?.(),",
63072
+ " cwd,",
63073
+ " hook_event_name: hookEventName,",
63074
+ " tool_name: claudeToolName(event.toolName),",
63075
+ " tool_input: claudeToolInput(event.toolName, event.input, cwd),",
63076
+ " tool_use_id: event.toolCallId,",
63077
+ " ...extra,",
63078
+ " });",
63079
+ "}"
63080
+ ];
63081
+ }
63082
+ /**
63083
+ * Helpers emitted alongside `tool_call` handlers. A command that exits 0 may
63084
+ * still decide the call the way Claude Code reads a `PreToolUse` hook's JSON
63085
+ * stdout: `hookSpecificOutput.permissionDecision` `"deny"` or `"ask"` (with
63086
+ * `permissionDecisionReason`) or, when no `permissionDecision` is given, the
63087
+ * deprecated top-level `decision: "block"` (with `reason`). Output that is not
63088
+ * such JSON allows the call, so hooks that print plain text keep working. The
63089
+ * deny side is the OpenCode-style plugin's `__rulesyncEnforcePreToolUseResult`
63090
+ * contract, plus the deprecated form Claude Code still honors.
63091
+ *
63092
+ * Pi has no permission prompt of its own, so `"ask"` is put to the user with
63093
+ * `ctx.ui.confirm` when a UI is attached, and denies the call when none is (print
63094
+ * and JSON modes) or the dialog fails: a hook asking for a human must not pass
63095
+ * silently.
63096
+ */
63097
+ const TOOL_DECISION_HELPER_LINES = [
63098
+ "type ToolHookDecision = { kind: \"deny\" | \"ask\"; reason: string };",
63099
+ "",
63100
+ "function toolHookDecision(stdout: string): ToolHookDecision | undefined {",
63101
+ " let parsed: unknown;",
63102
+ " try {",
63103
+ " parsed = JSON.parse(stdout);",
63104
+ " } catch {",
63105
+ " return undefined;",
63106
+ " }",
63107
+ " if (!parsed || typeof parsed !== \"object\") return undefined;",
63108
+ " const output = parsed as { decision?: unknown; reason?: unknown; hookSpecificOutput?: unknown };",
63109
+ " const specific = output.hookSpecificOutput as",
63110
+ " | { permissionDecision?: unknown; permissionDecisionReason?: unknown }",
63111
+ " | null",
63112
+ " | undefined;",
63113
+ " const hasDecision = typeof specific === \"object\" && specific !== null && specific.permissionDecision !== undefined;",
63114
+ " const decision = hasDecision ? specific?.permissionDecision : output.decision === \"block\" ? \"deny\" : undefined;",
63115
+ " if (decision !== \"deny\" && decision !== \"ask\") return undefined;",
63116
+ " const reason = hasDecision ? specific?.permissionDecisionReason : output.reason;",
63117
+ " return {",
63118
+ " kind: decision,",
63119
+ " reason:",
63120
+ " (typeof reason === \"string\" && sanitizeBlockReason(reason)) ||",
63121
+ " (decision === \"ask\" ? \"A preToolUse hook asked for confirmation.\" : \"Blocked by a preToolUse hook.\"),",
63122
+ " };",
63123
+ "}",
63124
+ "",
63125
+ "async function allowsToolCall(",
63126
+ " decision: ToolHookDecision,",
63127
+ " ctx: ExtensionContext | undefined,",
63128
+ "): Promise<boolean> {",
63129
+ " if (decision.kind !== \"ask\" || !ctx?.hasUI) return false;",
63130
+ " try {",
63131
+ " return await ctx.ui.confirm(\"Allow this tool call?\", decision.reason);",
63132
+ " } catch {",
63133
+ " return false;",
63134
+ " }",
63135
+ "}"
63136
+ ];
63137
+ /**
63138
+ * Runs a hook command through the platform shell with `input` as its stdin
63139
+ * (empty when the event has no payload, so a command that reads stdin never
63140
+ * waits on Pi's own), bounded by the hook's `timeout` in seconds (Claude
63141
+ * Code's default of 600 when unset, as in the OpenCode-style plugin). A stdin
63142
+ * the command never reads is not an error.
63143
+ *
63144
+ * The command runs in its own process group (except on Windows), so a command
63145
+ * past its timeout is killed together with everything it started, and the
63146
+ * call rejects with a `HookTimeoutError` right away rather than waiting for a
63147
+ * descendant still holding its output open. Like `promisify(exec)`, which
63148
+ * earlier versions used, a non-zero exit rejects with an error carrying
63149
+ * `code`, `stdout` and `stderr`, and more than 1 MiB on either stream rejects
63150
+ * and kills the command.
63151
+ *
63152
+ * A detached group does not get the terminal's Ctrl+C, so the extension
63153
+ * kills every command still running on `session_shutdown`, after the other
63154
+ * handlers (including a `sessionEnd` hook's) have run: Pi awaits them in
63155
+ * registration order. A Pi process killed outright never fires it, and since
63156
+ * the timeout timer lives in that process too, its commands then keep running
63157
+ * with no deadline until they exit on their own.
63158
+ */
63159
+ const RUN_HELPER_LINES = [
63160
+ "const MAX_HOOK_OUTPUT_LENGTH = 1024 * 1024;",
63161
+ "",
63162
+ "class HookTimeoutError extends Error {}",
63163
+ "",
63164
+ "// Kills of the commands still running, for `session_shutdown`.",
63165
+ "const runningHookCommands = new Set<() => void>();",
63166
+ "",
63167
+ "function run(",
63168
+ " command: string,",
63169
+ " { input = \"\", seconds }: { input?: string; seconds: number },",
63170
+ "): Promise<{ stdout: string; stderr: string }> {",
63171
+ " return new Promise((resolve, reject) => {",
63172
+ " const detached = process.platform !== \"win32\";",
63173
+ " const child = spawn(command, { shell: true, detached, windowsHide: true });",
63174
+ " const output = { stdout: \"\", stderr: \"\" };",
63175
+ " let settled = false;",
63176
+ " const finish = (error?: Error) => {",
63177
+ " if (settled) return;",
63178
+ " settled = true;",
63179
+ " clearTimeout(timer);",
63180
+ " runningHookCommands.delete(killTree);",
63181
+ " if (error) reject(error);",
63182
+ " else resolve(output);",
63183
+ " };",
63184
+ " const killTree = () => {",
63185
+ " try {",
63186
+ " if (detached && child.pid !== undefined) process.kill(-child.pid, \"SIGKILL\");",
63187
+ " else child.kill(\"SIGKILL\");",
63188
+ " } catch {",
63189
+ " // Already gone.",
63190
+ " }",
63191
+ " child.stdout?.destroy();",
63192
+ " child.stderr?.destroy();",
63193
+ " };",
63194
+ " runningHookCommands.add(killTree);",
63195
+ " const timer = setTimeout(() => {",
63196
+ " killTree();",
63197
+ " finish(new HookTimeoutError(`Hook command timed out after ${seconds} seconds.`));",
63198
+ " }, seconds * 1000);",
63199
+ " for (const stream of [\"stdout\", \"stderr\"] as const) {",
63200
+ " child[stream]?.setEncoding(\"utf8\");",
63201
+ " child[stream]?.on(\"data\", (chunk: string) => {",
63202
+ " output[stream] += chunk;",
63203
+ " if (output[stream].length <= MAX_HOOK_OUTPUT_LENGTH) return;",
63204
+ " killTree();",
63205
+ " finish(new Error(`Hook command wrote more than 1 MiB to ${stream}.`));",
63206
+ " });",
63207
+ " }",
63208
+ " child.on(\"error\", (error) => finish(error));",
63209
+ " child.on(\"close\", (code, signal) => {",
63210
+ " if (code === 0) return finish();",
63211
+ " finish(",
63212
+ " Object.assign(new Error(`Command failed: ${command}`), {",
63213
+ " code,",
63214
+ " signal,",
63215
+ " stdout: output.stdout,",
63216
+ " stderr: output.stderr,",
63217
+ " }),",
63218
+ " );",
63219
+ " });",
63220
+ " child.stdin?.on(\"error\", () => {});",
63221
+ " child.stdin?.end(input);",
63222
+ " });",
63223
+ "}"
63224
+ ];
63225
+ /**
63226
+ * Helper emitted alongside blocking handlers. `run` rejects on a
62521
63227
  * non-zero exit with an error carrying `stdout` / `stderr` / `code`, so the
62522
63228
  * reason is derived from the rejection rather than from a resolved exit code.
62523
63229
  * A command that could not be run at all (spawn failure, `maxBuffer` overflow)
@@ -62621,7 +63327,9 @@ function collectPiHandlers({ effectiveHooks, eventMap }) {
62621
63327
  handlers.push({
62622
63328
  command: def.command,
62623
63329
  matcher: def.matcher ? def.matcher : void 0,
62624
- onlyOnError: PI_ERROR_GATED_CANONICAL_EVENTS.has(canonicalEvent)
63330
+ onlyOnError: PI_ERROR_GATED_CANONICAL_EVENTS.has(canonicalEvent),
63331
+ ...hookTimingOf(def),
63332
+ ...PI_TOOL_EVENTS.has(piEvent) && STDIN_PAYLOAD_EVENTS[canonicalEvent] ? { payload: STDIN_PAYLOAD_EVENTS[canonicalEvent] } : {}
62625
63333
  });
62626
63334
  }
62627
63335
  if (handlers.length > 0) {
@@ -62636,22 +63344,63 @@ function buildCommandLines({ handler, usesToolName, blocking, dialect }) {
62636
63344
  const lines = [];
62637
63345
  const conditions = [];
62638
63346
  if (handler.onlyOnError) conditions.push("event.isError");
62639
- if (usesToolName && handler.matcher) conditions.push(`new RegExp(${matcherToEmbeddedLiteral(handler.matcher)}).test(event.toolName)`);
63347
+ if (usesToolName && handler.matcher) conditions.push(`matchesTool(new RegExp(${matcherToEmbeddedLiteral(handler.matcher)}), event.toolName)`);
62640
63348
  const gated = conditions.length > 0;
62641
63349
  const indent = gated ? " " : " ";
62642
- const embeddedCommand = JSON.stringify(handler.command);
63350
+ const options = [...handler.payload ? [`input: ${payloadAccessorName(handler.payload)}()`] : [], `seconds: ${handler.timeout}`];
63351
+ const runCall = `run(${JSON.stringify(handler.command)}, { ${options.join(", ")} })`;
62643
63352
  if (gated) lines.push(` if (${conditions.join(" && ")}) {`);
62644
63353
  const onFailure = failureLinesByMode(dialect)[blocking];
62645
- if (onFailure.length > 0) {
63354
+ if (blocking === "tool") {
63355
+ lines.push(`${indent}try {`);
63356
+ lines.push(`${indent} const decision = toolHookDecision((await ${runCall}).stdout);`);
63357
+ lines.push(`${indent} if (decision && !(await allowsToolCall(decision, ctx))) return { block: true, reason: decision.reason };`);
63358
+ lines.push(`${indent}} catch (error) {`);
63359
+ if (handler.failClosed === false) {
63360
+ lines.push(`${indent} if (error instanceof HookTimeoutError) {`);
63361
+ lines.push(`${indent} console.error("[rulesync-hooks] preToolUse hook timed out");`);
63362
+ lines.push(`${indent} } else {`);
63363
+ for (const line of onFailure) lines.push(`${indent} ${line}`);
63364
+ lines.push(`${indent} }`);
63365
+ } else for (const line of onFailure) lines.push(`${indent} ${line}`);
63366
+ lines.push(`${indent}}`);
63367
+ } else if (onFailure.length > 0) {
62646
63368
  lines.push(`${indent}try {`);
62647
- lines.push(`${indent} await run(${embeddedCommand});`);
63369
+ lines.push(`${indent} await ${runCall};`);
62648
63370
  lines.push(`${indent}} catch (error) {`);
62649
63371
  for (const line of onFailure) lines.push(`${indent} ${line}`);
62650
63372
  lines.push(`${indent}}`);
62651
- } else lines.push(`${indent}await run(${embeddedCommand});`);
63373
+ } else lines.push(`${indent}await ${runCall};`);
62652
63374
  if (gated) lines.push(" }");
62653
63375
  return lines;
62654
63376
  }
63377
+ /** The per-invocation closure a handler calls for its serialized payload. */
63378
+ function payloadAccessorName(hookEventName) {
63379
+ return `${hookEventName.charAt(0).toLowerCase()}${hookEventName.slice(1)}Input`;
63380
+ }
63381
+ /** Lazily serialized payloads the handlers of one subscription use. */
63382
+ function buildPayloadLines(handlers) {
63383
+ const payloads = [...new Set(handlers.flatMap((h) => h.payload ? [h.payload] : []))];
63384
+ const lines = [];
63385
+ for (const payload of payloads) {
63386
+ const accessor = payloadAccessorName(payload);
63387
+ const extra = STDIN_PAYLOAD_EXTRA_FIELDS[payload] ?? "";
63388
+ const extraArgument = extra ? `, { ${extra} }` : "";
63389
+ lines.push(` let ${accessor}Cache: string | undefined;`);
63390
+ lines.push(` const ${accessor} = () => (${accessor}Cache ??= toolHookInput(${JSON.stringify(payload)}, event, ctx${extraArgument}));`);
63391
+ }
63392
+ return lines;
63393
+ }
63394
+ /**
63395
+ * The handler's parameter list. `ctx` is the second handler argument, so the
63396
+ * prompt gate and the payload builders (which read the session id and cwd)
63397
+ * name both.
63398
+ */
63399
+ function handlerParams({ handlers, readsEvent, isPromptGate }) {
63400
+ const usesPayload = handlers.some((h) => h.payload);
63401
+ if (isPromptGate || usesPayload) return "event, ctx";
63402
+ return readsEvent || handlers.some((h) => h.onlyOnError) ? "event" : "";
63403
+ }
62655
63404
  function buildSubscriptionLines(handlerGroups, dialect) {
62656
63405
  const lines = [];
62657
63406
  for (const [piEvent, handlers] of Object.entries(handlerGroups)) {
@@ -62661,13 +63410,17 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62661
63410
  const isSessionStopGate = blocking === "sessionStop";
62662
63411
  const collectsStopFailures = isSettleGate || isSessionStopGate;
62663
63412
  const usesToolName = PI_TOOL_EVENTS.has(piEvent) && handlers.some((h) => h.matcher);
62664
- const usesErrorFlag = handlers.some((h) => h.onlyOnError);
62665
63413
  const gatesOnAssistant = PI_ASSISTANT_MESSAGE_EVENTS.has(piEvent);
62666
- const params = isPromptGate ? "event, ctx" : usesToolName || usesErrorFlag || gatesOnAssistant || isPromptGate || collectsStopFailures ? "event" : "";
63414
+ const params = handlerParams({
63415
+ handlers,
63416
+ readsEvent: usesToolName || gatesOnAssistant || collectsStopFailures,
63417
+ isPromptGate
63418
+ });
62667
63419
  lines.push(` pi.on(${JSON.stringify(piEvent)}, async (${params}) => {`);
62668
63420
  if (gatesOnAssistant) lines.push(` if (event.message.role !== "assistant") return;`);
62669
63421
  if (isPromptGate) lines.push(` if (event.source === "extension") ${dialect.promptPassLine}`);
62670
63422
  if (collectsStopFailures) lines.push(" const stopHookFailures: unknown[] = [];");
63423
+ lines.push(...buildPayloadLines(handlers));
62671
63424
  for (const handler of handlers) lines.push(...buildCommandLines({
62672
63425
  handler,
62673
63426
  usesToolName,
@@ -62703,6 +63456,10 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62703
63456
  }
62704
63457
  return lines;
62705
63458
  }
63459
+ /** Whether a handler belongs to a tool event, where its matcher is tested. */
63460
+ function handlerGroupHasToolEvent(handlerGroups, handler) {
63461
+ return Object.entries(handlerGroups).some(([piEvent, handlers]) => PI_TOOL_EVENTS.has(piEvent) && handlers.includes(handler));
63462
+ }
62706
63463
  /**
62707
63464
  * Generate the rulesync-owned Pi extension (a TypeScript module with a
62708
63465
  * default-export factory receiving Pi's ExtensionAPI) that subscribes to the
@@ -62717,6 +63474,12 @@ function buildSubscriptionLines(handlerGroups, dialect) {
62717
63474
  * command's output as feedback.
62718
63475
  * `postToolUse` and `postToolUseFailure` share Pi's `tool_result` event; the
62719
63476
  * latter's commands run only when `event.isError` is set.
63477
+ * Commands on the tool events receive Claude Code's hook input on stdin (see
63478
+ * `STDIN_PAYLOAD_EVENTS`), and a tool matcher is tested against both Pi's tool
63479
+ * name and its canonical Claude Code name. On `tool_call`, a command that exits
63480
+ * 0 with a JSON deny decision also denies the call, and one past its `timeout`
63481
+ * denies it unless the hook sets `failClosed: false`, mirroring the
63482
+ * OpenCode-style plugin.
62720
63483
  *
62721
63484
  * @see https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md
62722
63485
  */
@@ -62736,7 +63499,9 @@ function generatePiExtensionCode({ config, supportedEvents, eventMap, dialect =
62736
63499
  const hasPromptGate = Boolean(handlerGroups[PI_PROMPT_BLOCKING_EVENT]);
62737
63500
  const hasSettleGate = Boolean(handlerGroups[PI_SETTLE_BLOCKING_EVENT]);
62738
63501
  const hasSessionStopGate = Boolean(handlerGroups[OMP_SESSION_STOP_BLOCKING_EVENT]);
62739
- const needsBlockReasonHelper = Boolean(handlerGroups[PI_BLOCKING_EVENT]) || hasPromptGate || hasSettleGate || hasSessionStopGate;
63502
+ const needsToolHelpers = Object.values(handlerGroups).flat().some((h) => h.payload || h.matcher && handlerGroupHasToolEvent(handlerGroups, h));
63503
+ const hasToolGate = Boolean(handlerGroups[PI_BLOCKING_EVENT]);
63504
+ const needsBlockReasonHelper = hasToolGate || hasPromptGate || hasSettleGate || hasSessionStopGate;
62740
63505
  const lines = ["// Generated by rulesync. Do not edit manually."];
62741
63506
  if (subscriptionLines.length === 0) {
62742
63507
  lines.push("export default function () {}");
@@ -62746,34 +63511,33 @@ function generatePiExtensionCode({ config, supportedEvents, eventMap, dialect =
62746
63511
  const importedTypes = [
62747
63512
  ...hasSettleGate ? ["AgentBeforeSettleEvent", "AgentBeforeSettleEventResult"] : [],
62748
63513
  "ExtensionAPI",
62749
- ...hasPromptGate ? ["ExtensionContext"] : []
63514
+ ...hasPromptGate || needsToolHelpers ? ["ExtensionContext"] : []
62750
63515
  ].join(", ");
62751
- lines.push("import { exec } from \"node:child_process\";");
62752
- lines.push("import { promisify } from \"node:util\";");
63516
+ lines.push("import { spawn } from \"node:child_process\";");
63517
+ if (needsToolHelpers) {
63518
+ lines.push("import { homedir } from \"node:os\";");
63519
+ 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\";");
63520
+ lines.push("import { fileURLToPath } from \"node:url\";");
63521
+ }
62753
63522
  lines.push("");
62754
63523
  lines.push(`import type { ${importedTypes} } from ${JSON.stringify(dialect.typesPackage)};`);
62755
63524
  lines.push("");
62756
- lines.push("const run = promisify(exec);");
62757
- lines.push("");
62758
- if (needsBlockReasonHelper) {
62759
- lines.push(...BLOCK_REASON_HELPER_LINES);
62760
- lines.push("");
62761
- }
62762
- if (hasPromptGate) {
62763
- lines.push(...PROMPT_GATE_HELPER_LINES);
62764
- lines.push("");
62765
- }
62766
- if (hasSettleGate || hasSessionStopGate) {
62767
- lines.push(...STOP_HOOK_BLOCK_HELPER_LINES);
62768
- lines.push("");
62769
- }
62770
- if (hasSettleGate) {
62771
- lines.push(...STOP_HOOK_HELPER_LINES);
62772
- lines.push("");
62773
- }
63525
+ const helperBlocks = [
63526
+ [true, RUN_HELPER_LINES],
63527
+ [needsBlockReasonHelper, BLOCK_REASON_HELPER_LINES],
63528
+ [hasToolGate, TOOL_DECISION_HELPER_LINES],
63529
+ [needsToolHelpers, needsToolHelpers ? buildToolPayloadHelperLines(dialect) : []],
63530
+ [hasPromptGate, PROMPT_GATE_HELPER_LINES],
63531
+ [hasSettleGate || hasSessionStopGate, STOP_HOOK_BLOCK_HELPER_LINES],
63532
+ [hasSettleGate, STOP_HOOK_HELPER_LINES]
63533
+ ];
63534
+ for (const [included, block] of helperBlocks) if (included) lines.push(...block, "");
62774
63535
  lines.push("export default function (pi: ExtensionAPI) {");
62775
63536
  if (hasSettleGate) lines.push(" let stopHookContinued = false;");
62776
63537
  lines.push(...subscriptionLines);
63538
+ lines.push(" pi.on(\"session_shutdown\", async () => {");
63539
+ lines.push(" for (const kill of [...runningHookCommands]) kill();");
63540
+ lines.push(" });");
62777
63541
  lines.push("}");
62778
63542
  lines.push("");
62779
63543
  return lines.join("\n");
@@ -65198,7 +65962,13 @@ const toolHooksFactories = /* @__PURE__ */ new Map([
65198
65962
  },
65199
65963
  ...converterCapabilities(BobHooks.getConverterConfig()),
65200
65964
  supportsMatcher: true,
65201
- matcherEvents: ["preToolUse", "postToolUse"]
65965
+ matcherEvents: BOB_MATCHER_HOOK_EVENTS,
65966
+ dropsUnknownOverrideEvents: true,
65967
+ overrideOnlyEvents: BOB_NATIVE_HOOK_EVENTS,
65968
+ overrideOptIn: {
65969
+ events: BOB_OPT_IN_HOOK_EVENTS,
65970
+ 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."
65971
+ }
65202
65972
  }],
65203
65973
  ["continue", {
65204
65974
  class: ContinueHooks,
@@ -65524,12 +66294,26 @@ var HooksProcessor = class extends FeatureProcessor {
65524
66294
  ...overrideHooks
65525
66295
  };
65526
66296
  {
65527
- const skipped = unsupportedEventNames({
66297
+ const optInEvents = factory.overrideOptIn?.events ?? {};
66298
+ const isOptIn = (e) => Object.hasOwn(optInEvents, e);
66299
+ const overrideKeys = new Set(Object.keys(overrideHooks));
66300
+ const skippedEvents = unsupportedEventNames({
65528
66301
  factory,
65529
66302
  sharedHooks,
65530
66303
  effectiveHooks
65531
66304
  });
66305
+ const skipped = skippedEvents.filter((e) => !isOptIn(e));
66306
+ const optIn = skippedEvents.filter(isOptIn).filter((e) => Object.hasOwn(sharedHooks, e) && !overrideKeys.has(optInEvents[e] ?? ""));
66307
+ const misnamed = skippedEvents.filter(isOptIn).filter((e) => overrideKeys.has(e));
65532
66308
  if (skipped.length > 0) this.logger.warn(`Skipped hook event(s) for ${this.toolTarget} (not supported): ${skipped.join(", ")}`);
66309
+ if (optIn.length > 0) {
66310
+ const nativeNames = optIn.map((e) => optInEvents[e]).join(", ");
66311
+ 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}.`);
66312
+ }
66313
+ if (misnamed.length > 0) {
66314
+ const nativeNames = misnamed.map((e) => optInEvents[e]).join(", ");
66315
+ this.logger.warn(`Skipped "${overrideKey}.hooks" key(s) for ${this.toolTarget}: ${misnamed.join(", ")}. Use the native name(s) ${nativeNames} instead.`);
66316
+ }
65533
66317
  }
65534
66318
  {
65535
66319
  const supportedHookTypes = new Set(factory.supportedHookTypes);
@@ -73489,7 +74273,8 @@ const HERMES_OPAQUE_MAPPING_KEYS = [
73489
74273
  * alias — `auth` (`oauth` for OAuth 2.1/PKCE), mTLS `client_cert` (string PEM
73490
74274
  * path, or `[cert, key]`/`[cert, key, password]` list) and `client_key`,
73491
74275
  * `connect_timeout` (seconds), `supports_parallel_tool_calls`, `protocol`,
73492
- * `lazy`, `events` (see {@link copyHermesBoolLikeFields}), `keepalive_interval`,
74276
+ * `lazy`, `events` (see {@link copyHermesBoolLikeFields}), `single_instance`,
74277
+ * `keepalive_interval`,
73493
74278
  * `elicitation`, `trust`, `identity_header`, and
73494
74279
  * the cost keys (see {@link copyHermesCostFields}) —
73495
74280
  * verbatim from `source` to `target`. Field names are identical on both sides
@@ -73540,6 +74325,10 @@ function copyHermesAdvancedFields(source, target, logger) {
73540
74325
  target.skip_preflight = source.skip_preflight;
73541
74326
  copied = true;
73542
74327
  }
74328
+ if (typeof source.single_instance === "boolean") {
74329
+ target.single_instance = source.single_instance;
74330
+ copied = true;
74331
+ }
73543
74332
  if (typeof source.keepalive_interval === "number") {
73544
74333
  target.keepalive_interval = source.keepalive_interval;
73545
74334
  copied = true;
@@ -84131,7 +84920,7 @@ function buildVscodeCommandLists({ rules, toolLabel, logger, prefixSemantics = "
84131
84920
  };
84132
84921
  }
84133
84922
  // src/features/permissions/bob-permissions.ts
84134
- const TOOL_LABEL = "IBM Bob";
84923
+ const TOOL_LABEL$1 = "IBM Bob";
84135
84924
  /** The top-level settings key holding Bob's auto-approval configuration. */
84136
84925
  const APPROVAL_KEY$1 = "approval";
84137
84926
  /** The top-level settings key holding Bob's per-feature auto-approve toggles. */
@@ -84213,7 +85002,7 @@ function warnAboutSkippedCategories({ permission, bashStated, authorsGroupSwitch
84213
85002
  if (skipped.length === 0) return;
84214
85003
  const names = skipped.map((category) => `'${category}'`).join(", ");
84215
85004
  const hint = authorsGroupSwitches ? "" : ` ${GROUP_SWITCH_HINT}`;
84216
- 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}`);
85005
+ 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}`);
84217
85006
  }
84218
85007
  /**
84219
85008
  * Warn about what the `bob` override writes that Bob does not document: an
@@ -84233,7 +85022,7 @@ function warnAboutUndocumentedSettings({ override, logger }) {
84233
85022
  ...outsideWorkspace.length > 0 ? [`'enableOutsideWorkspace' for group(s) ${quoteAll(outsideWorkspace)}`] : []
84234
85023
  ];
84235
85024
  if (parts.length === 0) return;
84236
- 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.`);
85025
+ 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.`);
84237
85026
  }
84238
85027
  /**
84239
85028
  * Name what the `bob` override newly auto-approves. The settings file is Bob's
@@ -84252,7 +85041,7 @@ function warnAboutNewAutoApprovals({ settings, override, filePath, logger }) {
84252
85041
  ...Object.entries(override?.autoApprove ?? {}).filter(([key, value]) => value === true && existingAutoApprove[key] !== true).map(([key]) => quoteValueForWarning(`${AUTO_APPROVE_KEY}.${key}`))
84253
85042
  ]);
84254
85043
  if (added.size === 0) return;
84255
- 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.`);
85044
+ 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.`);
84256
85045
  }
84257
85046
  /**
84258
85047
  * Split the canonical `bash` rules — plus the restricting rules of the
@@ -84269,7 +85058,7 @@ function buildBobCommandLists({ permission, logger }) {
84269
85058
  normalizePattern: widenToPrefixGlob$1
84270
85059
  });
84271
85060
  warnAboutUnwrittenCommandRules({
84272
- toolLabel: TOOL_LABEL,
85061
+ toolLabel: TOOL_LABEL$1,
84273
85062
  surfaceLabel: SURFACE_LABEL,
84274
85063
  foreignRestrictingCategories,
84275
85064
  shadowedAllowPatterns,
@@ -84284,7 +85073,7 @@ function buildBobCommandLists({ permission, logger }) {
84284
85073
  for (const pattern of deny) lists[pattern] = "deny";
84285
85074
  return buildVscodeCommandLists({
84286
85075
  rules: lists,
84287
- toolLabel: TOOL_LABEL,
85076
+ toolLabel: TOOL_LABEL$1,
84288
85077
  logger,
84289
85078
  prefixSemantics: "documented-prefix"
84290
85079
  });
@@ -84456,7 +85245,7 @@ var BobPermissions = class BobPermissions extends ToolPermissions {
84456
85245
  const rules = importVscodeCommandLists({
84457
85246
  allowed: toStringArray$1(entry?.approvedCommands),
84458
85247
  denied: toStringArray$1(entry?.deniedCommands),
84459
- toolLabel: TOOL_LABEL,
85248
+ toolLabel: TOOL_LABEL$1,
84460
85249
  logger,
84461
85250
  prefixSemantics: "documented-prefix"
84462
85251
  });
@@ -85253,6 +86042,7 @@ const CLAUDECODE_UNHONORED_KEY_SOURCES = {
85253
86042
  disableMobileSimulatorTools: "managed settings",
85254
86043
  disableRemotePreviewScripts: "managed settings",
85255
86044
  disableSideloadFlags: "managed settings",
86045
+ enforceAnthropicSignIn: "managed settings",
85256
86046
  externalEditorContext: "~/.claude.json",
85257
86047
  forceRemoteSettingsRefresh: "managed settings",
85258
86048
  gatewayInternalNetworks: "managed settings",
@@ -85405,12 +86195,14 @@ const CLAUDECODE_ENV_IGNORED_IN_EVERY_FILE = /* @__PURE__ */ new Set([
85405
86195
  "CLAUDE_CODE_DISABLE_MOUNTED_DRIVE_RM_PROMPT",
85406
86196
  "CLAUDE_CODE_DISABLE_POWERSHELL_CMD_RM_DENY",
85407
86197
  "CLAUDE_CODE_DISABLE_SUBSTITUTION_RM_PROMPT",
86198
+ "CLAUDE_CODE_DISABLE_ULTRAREVIEW_TRUST_CHECK",
85408
86199
  "CLAUDE_CODE_EVEN_MORE_DANGEROUSLY_SKIP_PERMISSIONS",
85409
86200
  "CLAUDE_CODE_MESSAGING_SOCKET",
85410
86201
  "CLAUDE_CODE_MESSAGING_TOKEN",
85411
86202
  "CLAUDE_CODE_PROJECT_DIR_NAME",
85412
86203
  "CLAUDE_CODE_REMOTE",
85413
86204
  "CLAUDE_CODE_RESTRICTED",
86205
+ "CLAUDE_CODE_STRICT_INLINE_SHELL_RM_PROMPT",
85414
86206
  "CLAUDE_CODE_WARN_DISK_FREE_GIB",
85415
86207
  "CLAUDE_CODE_WARN_MEMORY_FREE_GIB"
85416
86208
  ]);
@@ -85422,6 +86214,13 @@ const CLAUDECODE_ENV_IGNORED_IN_EVERY_FILE = /* @__PURE__ */ new Set([
85422
86214
  * dialog, and whether it processes attachments or expands `@` file mentions,
85423
86215
  * and the screen reader (`CLAUDE_AX_*`) variables. Claude Code drops them there, so they are skipped at project scope and emitted only under `--global`.
85424
86216
  *
86217
+ * `OTEL_RESOURCE_INCLUDE_HOST` (Claude Code v2.1.326+) adds the machine's name
86218
+ * and ID to telemetry, so it sits with the telemetry group. The reference lists
86219
+ * `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE` separately: Code Mode follows it only
86220
+ * from the shell, user settings or a `--settings` file, and a project `0` does
86221
+ * not keep Code Mode off either, so any project value is skipped while user
86222
+ * settings (`--global`) still honor it.
86223
+ *
85425
86224
  * Only the names the settings reference lists are covered; its directory,
85426
86225
  * Windows and sign-in groups are introduced with "such as", so an unlisted member of those
85427
86226
  * families is still written. Windows variable names are case-insensitive, so
@@ -85440,6 +86239,7 @@ const CLAUDECODE_ENV_PROJECT_IGNORED_NAMES = /* @__PURE__ */ new Set([
85440
86239
  "CLAUDE_CODE_DISABLE_FILE_MENTIONS",
85441
86240
  "CLAUDE_CODE_ENABLE_TELEMETRY",
85442
86241
  "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
86242
+ "CLAUDE_CODE_EXPERIMENTAL_CODE_MODE",
85443
86243
  "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
85444
86244
  "CLAUDE_CODE_OAUTH_SCOPES",
85445
86245
  "CLAUDE_CODE_OAUTH_TOKEN",
@@ -85458,6 +86258,7 @@ const CLAUDECODE_ENV_PROJECT_IGNORED_NAMES = /* @__PURE__ */ new Set([
85458
86258
  "OTEL_EXPORTER_PROMETHEUS_PORT",
85459
86259
  "OTEL_LOG_ASSISTANT_RESPONSES",
85460
86260
  "OTEL_LOG_RAW_API_BODIES",
86261
+ "OTEL_RESOURCE_INCLUDE_HOST",
85461
86262
  "TEMP",
85462
86263
  "TMP",
85463
86264
  "TMPDIR"
@@ -92969,6 +93770,263 @@ function convertFactorydroidToRulesyncPermissions({ allow, deny }) {
92969
93770
  for (const pattern of deny) bash[pattern] = "deny";
92970
93771
  return { permission: Object.keys(bash).length > 0 ? { bash } : {} };
92971
93772
  }
93773
+ // src/features/permissions/gitlabduo-permissions.ts
93774
+ 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";
93775
+ const TOOL_LABEL = "GitLab Duo CLI";
93776
+ const PERMISSIONS_KEY = "permissions";
93777
+ /** The Duo tool that runs a shell command; the only one rulesync writes statements for. */
93778
+ const COMMAND_TOOL_NAME = "run_command";
93779
+ /** The server refuses a pattern longer than this (`MAX_PATTERN_LENGTH`). */
93780
+ const MAX_PATTERN_LENGTH = 256;
93781
+ /**
93782
+ * Characters a written pattern must not hold:
93783
+ * - `; & | < > $ \` ( ) { }` and line breaks are shell metacharacters the
93784
+ * server refuses in a command-tool pattern.
93785
+ * - Quotes and the backslash are taken off by the shell-style word split the
93786
+ * server reads a pattern through, so the pattern would be matched as
93787
+ * something other than what it says.
93788
+ * - `[` and `]` start an `fnmatch` character class inside a token, which the
93789
+ * canonical glob does not read the same way.
93790
+ */
93791
+ const UNSUPPORTED_PATTERN_CHARACTERS = /[;&|<>$`(){}\n\r'"\\[\]]/;
93792
+ /** Quotes and the backslash escape, which a shell-style word split takes off. */
93793
+ const SHELL_QUOTING_CHARACTERS = /['"\\]/g;
93794
+ /** A canonical pattern may spell "any arguments" as a trailing `:*` (`git:*`). */
93795
+ const TRAILING_ARGUMENT_WILDCARD = /:\*$/;
93796
+ /** Glob characters that make a Duo pattern match more than its literal spelling. */
93797
+ const GLOB_CHARACTERS = /[*?[\]]/;
93798
+ /**
93799
+ * Permissions adapter for GitLab Duo CLI.
93800
+ *
93801
+ * Duo CLI 10.5.0 reads a `permissions` array of
93802
+ * `{ action, resource, effect }` statements from the managed settings file and
93803
+ * the user's `~/.gitlab/duo/settings.json`. The project files
93804
+ * (`.gitlab/duo/settings.json`, `.gitlab/duo/settings.local.json`) are
93805
+ * deliberately not read for it, so this surface is **global only**.
93806
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/definitions.ts
93807
+ * @see https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/v10.5.0/packages/core/settings/src/tool_permissions.ts
93808
+ *
93809
+ * Only `allow` is enforced: each allow statement is submitted to the GitLab
93810
+ * instance as a session pattern approval when a session starts. `ask` and
93811
+ * `deny` statements are accepted but only logged. rulesync therefore writes
93812
+ * allow statements only, and never one that could auto-approve something the
93813
+ * canonical file restricts:
93814
+ *
93815
+ * - Only canonical `bash` `allow` rules are written, as
93816
+ * `{ action: "run_command", resource: <pattern>, effect: "allow" }`. Other
93817
+ * categories have no Duo spelling that is known to match no wider than the
93818
+ * canonical rule (the server matches other tools' patterns against their raw
93819
+ * JSON arguments), so their allow rules are skipped with a warning.
93820
+ * - Every `deny` and `ask` rule under `bash` or the all-tools `*` category
93821
+ * withholds the allow rules that could match the same command, because Duo
93822
+ * cannot enforce the restriction itself. A deny is also reported: the command
93823
+ * is asked about, not blocked.
93824
+ * - The GitLab server matches a command-tool pattern token by token
93825
+ * (`CommandPatternMatcher`): a literal token must match exactly, `*` is one
93826
+ * token that does not start with `-`, and a token holding a glob is matched
93827
+ * on its own. That is never wider than the canonical glob, where `*` spans
93828
+ * any characters. A trailing `:*` is written as ` *`. A pattern the server
93829
+ * refuses (a lone `*`, `**`, shell metacharacters, more than 256 characters)
93830
+ * or would read differently (quotes, escapes, character classes) is skipped
93831
+ * with a warning.
93832
+ * @see https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/models/ai/duo_workflows/command_pattern_matcher.rb
93833
+ *
93834
+ * On generate, the statements rulesync owns — those for `run_command` — are
93835
+ * replaced, and every other statement and key of the file is kept, with the
93836
+ * comments outside the `permissions` array (the array is rewritten whole).
93837
+ * On import, `run_command` statements come back under `bash`. An allow is
93838
+ * skipped when its resource holds a glob, which the canonical glob would read
93839
+ * more widely than Duo does, or when the server would refuse it, since it
93840
+ * approves nothing in Duo but would approve the command for other tools.
93841
+ */
93842
+ var GitlabduoPermissions = class GitlabduoPermissions extends ToolPermissions {
93843
+ constructor(params) {
93844
+ super({
93845
+ ...params,
93846
+ fileContent: params.fileContent ?? "{}"
93847
+ });
93848
+ }
93849
+ /**
93850
+ * `settings.json` holds every Duo CLI setting, so rulesync never brings it
93851
+ * into existence just to hold nothing.
93852
+ */
93853
+ shouldSkipCreationWhenPayloadEmpty() {
93854
+ return true;
93855
+ }
93856
+ static getSettablePaths(_options = {}) {
93857
+ return {
93858
+ relativeDirPath: GITLABDUO_DIR,
93859
+ relativeFilePath: GITLABDUO_SETTINGS_FILE_NAME
93860
+ };
93861
+ }
93862
+ static async fromFile({ outputRoot = process.cwd(), validate = true, global = false }) {
93863
+ if (!global) throw new Error(GITLABDUO_GLOBAL_ONLY_MESSAGE);
93864
+ const paths = GitlabduoPermissions.getSettablePaths({ global });
93865
+ const fileContent = await readFileContentOrNull(join(outputRoot, paths.relativeDirPath, paths.relativeFilePath)) ?? "{}";
93866
+ return new GitlabduoPermissions({
93867
+ outputRoot,
93868
+ relativeDirPath: paths.relativeDirPath,
93869
+ relativeFilePath: paths.relativeFilePath,
93870
+ fileContent,
93871
+ validate,
93872
+ global: true
93873
+ });
93874
+ }
93875
+ static async fromRulesyncPermissions({ outputRoot = process.cwd(), rulesyncPermissions, logger, global = false }) {
93876
+ if (!global) throw new Error(GITLABDUO_GLOBAL_ONLY_MESSAGE);
93877
+ const paths = GitlabduoPermissions.getSettablePaths({ global });
93878
+ const filePath = join(outputRoot, paths.relativeDirPath, paths.relativeFilePath);
93879
+ const existingContent = await readFileContentOrNull(filePath) ?? "";
93880
+ const baseContent = existingContent.trim() === "" ? "{}" : existingContent;
93881
+ const existing = parseSettings({
93882
+ content: baseContent,
93883
+ filePath
93884
+ })[PERMISSIONS_KEY];
93885
+ const generated = convertRulesyncToGitlabduoStatements({
93886
+ config: rulesyncPermissions.getJson(),
93887
+ logger
93888
+ });
93889
+ let fileContent = baseContent;
93890
+ 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.`);
93891
+ else {
93892
+ const statements = [...(existing ?? []).filter((statement) => !(isPlainObject(statement) && statement.action === COMMAND_TOOL_NAME)), ...generated];
93893
+ if (statements.length > 0 || existing !== void 0) {
93894
+ const edits = modify(baseContent, [PERMISSIONS_KEY], statements.length > 0 ? statements : void 0, { formattingOptions: {
93895
+ insertSpaces: true,
93896
+ tabSize: 2
93897
+ } });
93898
+ fileContent = applyEdits(baseContent, edits);
93899
+ }
93900
+ }
93901
+ return new GitlabduoPermissions({
93902
+ outputRoot,
93903
+ relativeDirPath: paths.relativeDirPath,
93904
+ relativeFilePath: paths.relativeFilePath,
93905
+ fileContent,
93906
+ validate: true,
93907
+ global: true
93908
+ });
93909
+ }
93910
+ toRulesyncPermissions() {
93911
+ const selfPath = join(this.getRelativeDirPath(), this.getRelativeFilePath());
93912
+ const raw = parseSettings({
93913
+ content: this.getFileContent() || "{}",
93914
+ filePath: selfPath
93915
+ })[PERMISSIONS_KEY];
93916
+ const statements = Array.isArray(raw) ? raw : [];
93917
+ 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}.`);
93918
+ const bash = {};
93919
+ const skippedAllows = [];
93920
+ for (const statement of statements) {
93921
+ if (!isDuoPermissionStatement(statement) || statement.action !== COMMAND_TOOL_NAME) continue;
93922
+ const { resource, effect } = statement;
93923
+ if (effect === "allow" && (GLOB_CHARACTERS.test(resource) || toGitlabduoCommandResource(resource) !== resource)) {
93924
+ skippedAllows.push(resource);
93925
+ continue;
93926
+ }
93927
+ const previous = bash[resource];
93928
+ if (previous === void 0 || rank(effect) > rank(previous)) bash[resource] = effect;
93929
+ }
93930
+ if (skippedAllows.length > 0) warnWithFallback(void 0, `The run_command allow statement(s) for ${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.`);
93931
+ const config = { permission: Object.keys(bash).length > 0 ? { [SHELL_PERMISSION_CATEGORY]: bash } : {} };
93932
+ return RulesyncPermissions.fromImportedFileContent({
93933
+ outputRoot: this.outputRoot,
93934
+ sourcePath: this.getRelativePathFromCwd(),
93935
+ fileContent: JSON.stringify(config, null, 2)
93936
+ });
93937
+ }
93938
+ };
93939
+ function rank(effect) {
93940
+ return effect === "deny" ? 2 : effect === "ask" ? 1 : 0;
93941
+ }
93942
+ function isDuoPermissionStatement(value) {
93943
+ return isPlainObject(value) && typeof value.action === "string" && value.action.length > 0 && typeof value.resource === "string" && (value.effect === "allow" || value.effect === "ask" || value.effect === "deny");
93944
+ }
93945
+ function parseSettings({ content, filePath }) {
93946
+ let parsed;
93947
+ try {
93948
+ parsed = parseJsonc(content);
93949
+ } catch (error) {
93950
+ throw new Error(`Failed to parse GitLab Duo CLI settings at ${filePath}: ${formatError(error)}`, { cause: error });
93951
+ }
93952
+ if (!isPlainObject(parsed)) throw new Error(`GitLab Duo CLI settings at ${filePath} must contain a JSON object.`);
93953
+ return parsed;
93954
+ }
93955
+ /**
93956
+ * A canonical command pattern as Duo's token matcher reads it: trimmed, runs
93957
+ * of whitespace collapsed to one space (Duo splits a command into words, so
93958
+ * `git push` and `git push` are one command), and a trailing `:*` ("any
93959
+ * arguments") spelled ` *`.
93960
+ */
93961
+ function normalizeGitlabduoCommandPattern(pattern) {
93962
+ let normalized = pattern.trim();
93963
+ if (TRAILING_ARGUMENT_WILDCARD.test(normalized)) normalized = `${normalized.slice(0, -2)} *`;
93964
+ return normalized.trim().split(/\s+/).join(" ");
93965
+ }
93966
+ /**
93967
+ * The Duo `resource` for a canonical `bash` allow pattern, or `null` when the
93968
+ * server would refuse it or read it differently from what it says. The result
93969
+ * never matches a command the canonical pattern does not match.
93970
+ */
93971
+ function toGitlabduoCommandResource(pattern) {
93972
+ const resource = normalizeGitlabduoCommandPattern(pattern);
93973
+ if (resource === "" || resource === "*" || resource.length > MAX_PATTERN_LENGTH) return null;
93974
+ if (UNSUPPORTED_PATTERN_CHARACTERS.test(resource)) return null;
93975
+ if (resource.includes("**")) return null;
93976
+ return resource;
93977
+ }
93978
+ /**
93979
+ * Convert the canonical config into the `run_command` allow statements Duo CLI
93980
+ * enforces, reporting every rule that could not be carried.
93981
+ */
93982
+ function convertRulesyncToGitlabduoStatements({ config, logger }) {
93983
+ const { rules, foreignRestrictingCategories, ignoredAllToolsAllowPatterns } = collectShellCommandRules(config.permission);
93984
+ const restrictions = uniq(rules.filter(({ action }) => action !== "allow").flatMap(({ pattern }) => [
93985
+ pattern,
93986
+ normalizeGitlabduoCommandPattern(pattern),
93987
+ normalizeGitlabduoCommandPattern(pattern.replaceAll(SHELL_QUOTING_CHARACTERS, ""))
93988
+ ]).filter((pattern) => pattern !== "")).map((pattern) => ({
93989
+ pattern,
93990
+ fromAllToolsCategory: false
93991
+ }));
93992
+ const budget = createIntersectionBudget();
93993
+ const shadowingRestrictions = createShadowingRestrictionsTest(restrictions, { budget });
93994
+ const resources = [];
93995
+ const shadowedAllowPatterns = [];
93996
+ const unsupportedPatterns = [];
93997
+ for (const { pattern, action } of rules) {
93998
+ if (action !== "allow") continue;
93999
+ const resource = toGitlabduoCommandResource(pattern);
94000
+ if (resource === null) {
94001
+ unsupportedPatterns.push(pattern);
94002
+ continue;
94003
+ }
94004
+ if (shadowingRestrictions(resource).length > 0) {
94005
+ shadowedAllowPatterns.push(pattern);
94006
+ continue;
94007
+ }
94008
+ resources.push(resource);
94009
+ }
94010
+ warnAboutUnwrittenCommandRules({
94011
+ toolLabel: TOOL_LABEL,
94012
+ surfaceLabel: `${PERMISSIONS_KEY} statements for ${COMMAND_TOOL_NAME}`,
94013
+ foreignRestrictingCategories,
94014
+ shadowedAllowPatterns: uniq(shadowedAllowPatterns),
94015
+ ignoredAllToolsAllowPatterns,
94016
+ intersectionBudgetExhausted: budget.remaining === 0,
94017
+ logger
94018
+ });
94019
+ const denyPatterns = uniq(rules.filter(({ action }) => action === "deny").map(({ pattern }) => pattern));
94020
+ 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.`);
94021
+ const foreignAllowCategories = Object.entries(config.permission).filter(([category, categoryRules]) => category !== "bash" && category !== "*" && Object.values(categoryRules).includes("allow")).map(([category]) => category);
94022
+ 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.`);
94023
+ 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 ${uniq(unsupportedPatterns).join(", ")} were skipped.`);
94024
+ return uniq(resources).map((resource) => ({
94025
+ action: COMMAND_TOOL_NAME,
94026
+ resource,
94027
+ effect: "allow"
94028
+ }));
94029
+ }
92972
94030
  // src/features/permissions/goose-permissions.ts
92973
94031
  const GOOSE_GLOBAL_ONLY_MESSAGE = "Goose permissions are global-only; use --global to sync ~/.config/goose/permission.yaml";
92974
94032
  const GOOSE_USER_KEY = "user";
@@ -105287,6 +106345,13 @@ const toolPermissionsFactories = /* @__PURE__ */ new Map([
105287
106345
  supportsGlobal: true
105288
106346
  }
105289
106347
  }],
106348
+ ["gitlabduo", {
106349
+ class: GitlabduoPermissions,
106350
+ meta: {
106351
+ supportsProject: false,
106352
+ supportsGlobal: true
106353
+ }
106354
+ }],
105290
106355
  ["goose", {
105291
106356
  class: GoosePermissions,
105292
106357
  meta: {
@@ -108195,4 +109260,4 @@ const CHECKS_IMPORT_STRATEGY = {
108195
109260
  };
108196
109261
  export { RulesyncSkillFrontmatterSchema as $, RULESYNC_RULES_RELATIVE_DIR_PATH as $n, getFileSizeAndExecutableBit as $t, CODEBUDDY_LOCAL_RULE_FILE_NAME as A, ToolTargetSchema as An, fallbackLogger as At, CLAUDECODE_DIR as B, RULESYNC_CONFIG_RELATIVE_FILE_PATH as Bn, assertDirectoryIfExists as Bt, LETTACODE_DIR as C, toPosixPath as Cn, SourceEntrySchema as Ct, COMMANDCODE_DIR as D, ALL_TOOL_TARGETS as Dn, ConsoleLogger as Dt, FACTORYDROID_SETTINGS_LOCAL_FILE_NAME as E, mapWithConcurrency as En, findControlCharacter as Et, sweepRefusalReason as F, FEATURE_SOURCE_TREE_ENTRIES as Fn, CLIError as Ft, findProjectInstructionBudgetFindings as G, RULESYNC_IGNORE_RELATIVE_FILE_PATH as Gn, assertWritablePathInsideRoot as Gt, CLAUDECODE_MEMORIES_DIR_NAME as H, RULESYNC_CURATED_RULES_RELATIVE_DIR_PATH as Hn, assertNoSymlinkBelowRoot as Ht, loadYaml as I, MAX_FILE_SIZE as In, ErrorCodes as It, hasWindowsFoldableName as J, RULESYNC_MCP_SCHEMA_URL as Jn, directoryExists as Jt, toInstructionBudgetFile as K, RULESYNC_LOCAL_CONFIG_RELATIVE_FILE_PATH as Kn, checkPathTraversal as Kt, CODEXCLI_BASH_RULES_FILE_NAME as L, RULESYNC_AIIGNORE_RELATIVE_FILE_PATH as Ln, parseJsonc as Lt, AUGMENTCODE_SETTINGS_LOCAL_FILE_NAME as M, ALL_FEATURES_WITH_WILDCARD as Mn, withFallbackLoggerTarget as Mt, caseFoldIdentity as N, DEPRECATED_FEATURE_REPLACEMENTS as Nn, resetRunWarningState as Nt, COMMANDCODE_SETTINGS_LOCAL_FILE_NAME as O, ALL_TOOL_TARGETS_WITH_WILDCARD as On, JsonLogger as Ot, groupSpellingsByCaseFoldedIdentity as P, CURATED_RULES_FEATURE_SUBDIR as Pn, withWarnOnceScope as Pt, RulesyncSkill as Q, RULESYNC_RELATIVE_DIR_PATH as Qn, findFilesByGlobs as Qt, CODEXCLI_DIR as R, RULESYNC_CHECKS_RELATIVE_DIR_PATH as Rn, PathOutsideRootError as Rt, QWENCODE_LOCAL_RULE_FILE_NAME as S, splitPathSegments as Sn, GITIGNORE_DESTINATION_KEY as St, FACTORYDROID_DIR as T, writeFileContent as Tn, getSourceTransport as Tt, CLAUDECODE_SETTINGS_LOCAL_FILE_NAME as U, RULESYNC_CURATED_SKILLS_RELATIVE_DIR_PATH as Un, assertPathResolvesInsideRoot as Ut, CLAUDECODE_LOCAL_RULE_FILE_NAME as V, RULESYNC_CONFIG_SCHEMA_URL as Vn, assertLandingOutsideVcsMetadata as Vt, CLAUDECODE_SKILLS_DIR_PATH as W, RULESYNC_HOOKS_RELATIVE_FILE_PATH as Wn, assertTreeContainsNoSymlinks as Wt, RulesyncSubagent as X, RULESYNC_PERMISSIONS_RELATIVE_FILE_PATH as Xn, fileExists as Xt, getLocalSkillDirNames as Y, RULESYNC_NPM_SOURCES_LOCK_RELATIVE_FILE_PATH as Yn, ensureDir as Yt, RulesyncSubagentFrontmatterSchema as Z, RULESYNC_PERMISSIONS_SCHEMA_URL as Zn, fileExistsStrict as Zt, SkillsProcessor as _, removeFileWithoutFollowingSymlinks as _n, mergeInputRootConfigs as _t, convertFromTool as a, listDirectoryEntryNames as an, formatMegabytes as ar, RulesyncHooks as at, REASONIX_LOCAL_RULE_FILE_NAME as b, resolvedRelativePath as bn, CONFLICTING_TARGET_PAIRS as bt, ELLIPSIS_WIDTH as c, normalizePosixDirPath as cn, hasEnclosingMarkOutsideKeycap as cr, RulesyncCommand as ct, McpProcessor as d, readFileContent as dn, stripControlCharactersKeepingLineFeeds as dr, RulesyncCheckFrontmatterSchema as dt, getHomeDirectory as en, RULESYNC_SKILLS_RELATIVE_DIR_PATH as er, RulesyncRule as et, IgnoreProcessor as f, readFileContentOrNull as fn, stripControlCharactersKeepingLineFeedsAndTabs as fr, stringifyFrontmatter as ft, SubagentsProcessor as g, removeFileStrict as gn, ConfigResolver as gt, RulesProcessor as h, removeFile as hn, SKILL_FILE_NAME as ht, inspectInputRoots as i, isSymlink as in, RULESYNC_XDG_CONFIG_HOME_DEFAULT_DIR_NAME as ir, RulesyncIgnore as it, AUGMENTCODE_DIR as j, ALL_FEATURES as jn, warnOnConflictingFlags as jt, CODEBUDDY_DIR as k, PACKAGING_TOOL_TARGETS as kn, WarningCollectingLogger as kt, displayWidthOf as l, pathEscapesRoot as ln, quoteForLog as lr, RulesyncCommandFrontmatterSchema as lt, ChecksProcessor as m, removeDirectoryStrict as mn, SHARED_USER_MANAGED_CONFIG_PATHS as mt, formatSourceLoadFailure as n, isFileSystemError as nn, RULESYNC_SUBAGENTS_RELATIVE_DIR_PATH as nr, RulesyncPermissions as nt, getProcessorRegistryEntry as o, listFilePathsRecursively as on, formatError as or, getRulesyncSourceCandidates as ot, HooksProcessor as p, removeDirectory as pn, stripHiddenCharacters as pr, isRecord as pt, classifyRemoteName as q, RULESYNC_MCP_RELATIVE_FILE_PATH as qn, createTempDirectory as qt, generate as r, isRootDirPath as rn, RULESYNC_USER_CONFIG_DIR_NAME as rr, RulesyncMcp as rt, parseCommaSeparatedList as s, listSubdirectoryNames as sn, truncateText as sr, resolveRulesyncSourceWritePath as st, importFromTool as t, isFileNotFoundError as tn, RULESYNC_SOURCES_LOCK_RELATIVE_FILE_PATH as tr, RulesyncRuleFrontmatterSchema as tt, shortenToWidth as u, posixRelativePathEscapesRoot as un, stripControlCharacters as ur, RulesyncCheck as ut, CRUSH_LOCAL_RULE_FILE_NAME as v, removeTempDirectory as vn, parseConfigFileContent as vt, LETTACODE_SETTINGS_LOCAL_FILE_NAME as w, writeFileBuffer as wn, assertTargetsFeaturesExclusive as wt, QWENCODE_DIR as x, runWithDirectoryRollback as xn, ConfigFileSchema as xt, CommandsProcessor as y, resolvePath as yn, resolveEffectiveInputRoots as yt, CLAUDECODE_AGENT_MEMORY_LOCAL_DIR_NAME as z, RULESYNC_COMMANDS_RELATIVE_DIR_PATH as zn, applyFileMode as zt };
108197
109262
 
108198
- //# sourceMappingURL=import-9NB0tQm3.js.map
109263
+ //# sourceMappingURL=import-yOMJuum5.js.map