@ashx-j/lunr 0.2.9 → 0.2.11
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.
- package/dist/builtin-extensions/ashxj-spinners.d.ts +1 -4
- package/dist/builtin-extensions/ashxj-spinners.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-spinners.js +3 -29
- package/dist/builtin-extensions/ashxj-spinners.js.map +1 -1
- package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-tui.js +5 -4
- package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
- package/dist/builtin-extensions/lunr-cron.d.ts.map +1 -1
- package/dist/builtin-extensions/lunr-cron.js +6 -1
- package/dist/builtin-extensions/lunr-cron.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js +3 -4
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +2 -2
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +2 -2
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +4 -4
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +5 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +8 -7
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts +2 -2
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.js +2 -2
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +4 -3
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.js +2 -2
- package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +4 -6
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js +26 -18
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
- package/dist/builtin-extensions/pi-web-access/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-web-access/index.js +3 -1
- package/dist/builtin-extensions/pi-web-access/index.js.map +1 -1
- package/dist/catalog/models.json +1 -1
- package/dist/catalog/providers/nvidia.json +1 -1
- package/dist/catalog/providers/opencode-go.json +1 -1
- package/dist/catalog/providers/opencode.json +1 -1
- package/dist/catalog/providers/openrouter.json +1 -1
- package/dist/catalog/providers/qwen-cloud-cn.json +1 -1
- package/dist/catalog/providers/vercel-ai-gateway.json +1 -1
- package/dist/catalog/providers/xai.json +1 -1
- package/dist/catalog/publication.json +3 -3
- package/dist/core/agent-session.d.ts +2 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +11 -3
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/customize.d.ts +1 -0
- package/dist/core/customize.d.ts.map +1 -1
- package/dist/core/customize.js +3 -0
- package/dist/core/customize.js.map +1 -1
- package/dist/core/models-store.d.ts.map +1 -1
- package/dist/core/models-store.js +13 -1
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/permissions.d.ts +9 -0
- package/dist/core/permissions.d.ts.map +1 -1
- package/dist/core/permissions.js +60 -20
- package/dist/core/permissions.js.map +1 -1
- package/dist/core/plan-mode.d.ts.map +1 -1
- package/dist/core/plan-mode.js +49 -7
- package/dist/core/plan-mode.js.map +1 -1
- package/dist/core/settings-manager.d.ts +3 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +8 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/swarm.d.ts +17 -4
- package/dist/core/swarm.d.ts.map +1 -1
- package/dist/core/swarm.js +36 -4
- package/dist/core/swarm.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +2 -1
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +9 -6
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +2 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +2 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +2 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +2 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +13 -3
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +10 -2
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +5 -3
- package/dist/core/tools/write.js.map +1 -1
- package/dist/gateway/agent-bridge.d.ts +2 -1
- package/dist/gateway/agent-bridge.d.ts.map +1 -1
- package/dist/gateway/agent-bridge.js +11 -1
- package/dist/gateway/agent-bridge.js.map +1 -1
- package/dist/gateway/commands.d.ts.map +1 -1
- package/dist/gateway/commands.js +2 -1
- package/dist/gateway/commands.js.map +1 -1
- package/dist/gateway/cron.d.ts +4 -1
- package/dist/gateway/cron.d.ts.map +1 -1
- package/dist/gateway/cron.js +17 -8
- package/dist/gateway/cron.js.map +1 -1
- package/dist/gateway/router.d.ts +1 -1
- package/dist/gateway/router.d.ts.map +1 -1
- package/dist/gateway/router.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +11 -1
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-tail.d.ts +1 -0
- package/dist/modes/interactive/components/thinking-tail.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-tail.js +2 -6
- package/dist/modes/interactive/components/thinking-tail.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +75 -16
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +15 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +139 -34
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/docs/terminal-setup.md +2 -2
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
package/dist/core/customize.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customize.d.ts","sourceRoot":"","sources":["../../src/core/customize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D;;;;;;;GAOG;AAEH,eAAO,MAAM,uBAAuB,eAAgC,CAAC;AAErE,MAAM,WAAW,eAAe;IAC/B,aAAa,IAAI,OAAO,CAAC;IACzB,eAAe,IAAI,OAAO,CAAC;IAC3B,YAAY,IAAI,OAAO,CAAC;IACxB,YAAY,IAAI,OAAO,CAAC;IACxB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,eAAe,IAAI,OAAO,CAAC;IAC3B,iBAAiB,IAAI,OAAO,CAAC;IAC7B,YAAY,IAAI,OAAO,CAAC;IACxB,aAAa,IAAI,OAAO,CAAC;IACzB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,oBAAoB,IAAI,OAAO,CAAC;IAChC,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;CAC1C;
|
|
1
|
+
{"version":3,"file":"customize.d.ts","sourceRoot":"","sources":["../../src/core/customize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D;;;;;;;GAOG;AAEH,eAAO,MAAM,uBAAuB,eAAgC,CAAC;AAErE,MAAM,WAAW,eAAe;IAC/B,aAAa,IAAI,OAAO,CAAC;IACzB,eAAe,IAAI,OAAO,CAAC;IAC3B,YAAY,IAAI,OAAO,CAAC;IACxB,YAAY,IAAI,OAAO,CAAC;IACxB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,eAAe,IAAI,OAAO,CAAC;IAC3B,YAAY,IAAI,OAAO,CAAC;IACxB,iBAAiB,IAAI,OAAO,CAAC;IAC7B,YAAY,IAAI,OAAO,CAAC;IACxB,aAAa,IAAI,OAAO,CAAC;IACzB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,oBAAoB,IAAI,OAAO,CAAC;IAChC,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;CAC1C;AA8CD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,eAAe,EAAE,eAAe,GAAG,IAAI,CAG9E;AAED,4FAA4F;AAC5F,wBAAgB,kBAAkB,IAAI,eAAe,GAAG,SAAS,CAEhE","sourcesContent":["import type { SettingsManager } from \"./settings-manager.ts\";\n\n/**\n * lunR TUI customize bridge.\n *\n * Exposed on `globalThis` under `Symbol.for(\"@lunr/customize\")` so the baked-in\n * ashxj-tui extension can read the customize settings (gutter rail, prompt\n * symbol, footer element toggles) without importing core code — same pattern as\n * the model-tiers and memory-cap bridges.\n */\n\nexport const CUSTOMIZE_BRIDGE_SYMBOL = Symbol.for(\"@lunr/customize\");\n\nexport interface CustomizeBridge {\n\tgetGutterRail(): boolean;\n\tgetPromptSymbol(): boolean;\n\tgetFooterMcp(): boolean;\n\tgetFooterLsp(): boolean;\n\tgetFooterContext(): boolean;\n\tgetFooterTokens(): boolean;\n\tgetFooterTps(): boolean;\n\tgetFooterStatuses(): boolean;\n\tgetFooterGit(): boolean;\n\tgetFooterPlan(): boolean;\n\tgetFooterPlanBar(): boolean;\n\tgetHideThinkingBlock(): boolean;\n\tsetHideThinkingBlock(hide: boolean): void;\n}\n\nlet activeSettingsManager: SettingsManager | undefined;\n\nconst bridge: CustomizeBridge = {\n\tgetGutterRail(): boolean {\n\t\treturn activeSettingsManager?.getGutterRail() ?? true;\n\t},\n\tgetPromptSymbol(): boolean {\n\t\treturn activeSettingsManager?.getPromptSymbol() ?? true;\n\t},\n\tgetFooterMcp(): boolean {\n\t\treturn activeSettingsManager?.getFooterMcp() ?? true;\n\t},\n\tgetFooterLsp(): boolean {\n\t\treturn activeSettingsManager?.getFooterLsp() ?? false;\n\t},\n\tgetFooterContext(): boolean {\n\t\treturn activeSettingsManager?.getFooterContext() ?? true;\n\t},\n\tgetFooterTokens(): boolean {\n\t\treturn activeSettingsManager?.getFooterTokens() ?? true;\n\t},\n\tgetFooterTps(): boolean {\n\t\treturn activeSettingsManager?.getFooterTps() ?? true;\n\t},\n\tgetFooterStatuses(): boolean {\n\t\treturn activeSettingsManager?.getFooterStatuses() ?? true;\n\t},\n\tgetFooterGit(): boolean {\n\t\treturn activeSettingsManager?.getFooterGit() ?? true;\n\t},\n\tgetFooterPlan(): boolean {\n\t\treturn activeSettingsManager?.getFooterPlan() ?? true;\n\t},\n\tgetFooterPlanBar(): boolean {\n\t\treturn activeSettingsManager?.getFooterPlanBar() ?? true;\n\t},\n\tgetHideThinkingBlock(): boolean {\n\t\treturn activeSettingsManager?.getHideThinkingBlock() ?? false;\n\t},\n\tsetHideThinkingBlock(hide: boolean): void {\n\t\tactiveSettingsManager?.setHideThinkingBlock(hide);\n\t},\n};\n\n/**\n * Register (or re-point) the global customize bridge.\n * Safe to call multiple times — later calls only swap the settings source, so an\n * early startup registration (before extensions load) can be replaced by the live\n * runtime settings manager.\n */\nexport function registerCustomizeBridge(settingsManager: SettingsManager): void {\n\tactiveSettingsManager = settingsManager;\n\t(globalThis as Record<symbol, unknown>)[CUSTOMIZE_BRIDGE_SYMBOL] = bridge;\n}\n\n/** Read the bridge from `globalThis`, or undefined when not registered (extension-safe). */\nexport function getCustomizeBridge(): CustomizeBridge | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[CUSTOMIZE_BRIDGE_SYMBOL] as CustomizeBridge | undefined;\n}\n"]}
|
package/dist/core/customize.js
CHANGED
|
@@ -27,6 +27,9 @@ const bridge = {
|
|
|
27
27
|
getFooterTokens() {
|
|
28
28
|
return activeSettingsManager?.getFooterTokens() ?? true;
|
|
29
29
|
},
|
|
30
|
+
getFooterTps() {
|
|
31
|
+
return activeSettingsManager?.getFooterTps() ?? true;
|
|
32
|
+
},
|
|
30
33
|
getFooterStatuses() {
|
|
31
34
|
return activeSettingsManager?.getFooterStatuses() ?? true;
|
|
32
35
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customize.js","sourceRoot":"","sources":["../../src/core/customize.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"customize.js","sourceRoot":"","sources":["../../src/core/customize.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;AAkBrE,IAAI,qBAAkD,CAAC;AAEvD,MAAM,MAAM,GAAoB;IAC/B,aAAa,GAAY;QACxB,OAAO,qBAAqB,EAAE,aAAa,EAAE,IAAI,IAAI,CAAC;IAAA,CACtD;IACD,eAAe,GAAY;QAC1B,OAAO,qBAAqB,EAAE,eAAe,EAAE,IAAI,IAAI,CAAC;IAAA,CACxD;IACD,YAAY,GAAY;QACvB,OAAO,qBAAqB,EAAE,YAAY,EAAE,IAAI,IAAI,CAAC;IAAA,CACrD;IACD,YAAY,GAAY;QACvB,OAAO,qBAAqB,EAAE,YAAY,EAAE,IAAI,KAAK,CAAC;IAAA,CACtD;IACD,gBAAgB,GAAY;QAC3B,OAAO,qBAAqB,EAAE,gBAAgB,EAAE,IAAI,IAAI,CAAC;IAAA,CACzD;IACD,eAAe,GAAY;QAC1B,OAAO,qBAAqB,EAAE,eAAe,EAAE,IAAI,IAAI,CAAC;IAAA,CACxD;IACD,YAAY,GAAY;QACvB,OAAO,qBAAqB,EAAE,YAAY,EAAE,IAAI,IAAI,CAAC;IAAA,CACrD;IACD,iBAAiB,GAAY;QAC5B,OAAO,qBAAqB,EAAE,iBAAiB,EAAE,IAAI,IAAI,CAAC;IAAA,CAC1D;IACD,YAAY,GAAY;QACvB,OAAO,qBAAqB,EAAE,YAAY,EAAE,IAAI,IAAI,CAAC;IAAA,CACrD;IACD,aAAa,GAAY;QACxB,OAAO,qBAAqB,EAAE,aAAa,EAAE,IAAI,IAAI,CAAC;IAAA,CACtD;IACD,gBAAgB,GAAY;QAC3B,OAAO,qBAAqB,EAAE,gBAAgB,EAAE,IAAI,IAAI,CAAC;IAAA,CACzD;IACD,oBAAoB,GAAY;QAC/B,OAAO,qBAAqB,EAAE,oBAAoB,EAAE,IAAI,KAAK,CAAC;IAAA,CAC9D;IACD,oBAAoB,CAAC,IAAa,EAAQ;QACzC,qBAAqB,EAAE,oBAAoB,CAAC,IAAI,CAAC,CAAC;IAAA,CAClD;CACD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CAAC,eAAgC,EAAQ;IAC/E,qBAAqB,GAAG,eAAe,CAAC;IACvC,UAAsC,CAAC,uBAAuB,CAAC,GAAG,MAAM,CAAC;AAAA,CAC1E;AAED,4FAA4F;AAC5F,MAAM,UAAU,kBAAkB,GAAgC;IACjE,OAAQ,UAAsC,CAAC,uBAAuB,CAAgC,CAAC;AAAA,CACvG","sourcesContent":["import type { SettingsManager } from \"./settings-manager.ts\";\n\n/**\n * lunR TUI customize bridge.\n *\n * Exposed on `globalThis` under `Symbol.for(\"@lunr/customize\")` so the baked-in\n * ashxj-tui extension can read the customize settings (gutter rail, prompt\n * symbol, footer element toggles) without importing core code — same pattern as\n * the model-tiers and memory-cap bridges.\n */\n\nexport const CUSTOMIZE_BRIDGE_SYMBOL = Symbol.for(\"@lunr/customize\");\n\nexport interface CustomizeBridge {\n\tgetGutterRail(): boolean;\n\tgetPromptSymbol(): boolean;\n\tgetFooterMcp(): boolean;\n\tgetFooterLsp(): boolean;\n\tgetFooterContext(): boolean;\n\tgetFooterTokens(): boolean;\n\tgetFooterTps(): boolean;\n\tgetFooterStatuses(): boolean;\n\tgetFooterGit(): boolean;\n\tgetFooterPlan(): boolean;\n\tgetFooterPlanBar(): boolean;\n\tgetHideThinkingBlock(): boolean;\n\tsetHideThinkingBlock(hide: boolean): void;\n}\n\nlet activeSettingsManager: SettingsManager | undefined;\n\nconst bridge: CustomizeBridge = {\n\tgetGutterRail(): boolean {\n\t\treturn activeSettingsManager?.getGutterRail() ?? true;\n\t},\n\tgetPromptSymbol(): boolean {\n\t\treturn activeSettingsManager?.getPromptSymbol() ?? true;\n\t},\n\tgetFooterMcp(): boolean {\n\t\treturn activeSettingsManager?.getFooterMcp() ?? true;\n\t},\n\tgetFooterLsp(): boolean {\n\t\treturn activeSettingsManager?.getFooterLsp() ?? false;\n\t},\n\tgetFooterContext(): boolean {\n\t\treturn activeSettingsManager?.getFooterContext() ?? true;\n\t},\n\tgetFooterTokens(): boolean {\n\t\treturn activeSettingsManager?.getFooterTokens() ?? true;\n\t},\n\tgetFooterTps(): boolean {\n\t\treturn activeSettingsManager?.getFooterTps() ?? true;\n\t},\n\tgetFooterStatuses(): boolean {\n\t\treturn activeSettingsManager?.getFooterStatuses() ?? true;\n\t},\n\tgetFooterGit(): boolean {\n\t\treturn activeSettingsManager?.getFooterGit() ?? true;\n\t},\n\tgetFooterPlan(): boolean {\n\t\treturn activeSettingsManager?.getFooterPlan() ?? true;\n\t},\n\tgetFooterPlanBar(): boolean {\n\t\treturn activeSettingsManager?.getFooterPlanBar() ?? true;\n\t},\n\tgetHideThinkingBlock(): boolean {\n\t\treturn activeSettingsManager?.getHideThinkingBlock() ?? false;\n\t},\n\tsetHideThinkingBlock(hide: boolean): void {\n\t\tactiveSettingsManager?.setHideThinkingBlock(hide);\n\t},\n};\n\n/**\n * Register (or re-point) the global customize bridge.\n * Safe to call multiple times — later calls only swap the settings source, so an\n * early startup registration (before extensions load) can be replaced by the live\n * runtime settings manager.\n */\nexport function registerCustomizeBridge(settingsManager: SettingsManager): void {\n\tactiveSettingsManager = settingsManager;\n\t(globalThis as Record<symbol, unknown>)[CUSTOMIZE_BRIDGE_SYMBOL] = bridge;\n}\n\n/** Read the bridge from `globalThis`, or undefined when not registered (extension-safe). */\nexport function getCustomizeBridge(): CustomizeBridge | undefined {\n\treturn (globalThis as Record<symbol, unknown>)[CUSTOMIZE_BRIDGE_SYMBOL] as CustomizeBridge | undefined;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models-store.d.ts","sourceRoot":"","sources":["../../src/core/models-store.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAM3E,qBAAa,8BAA+B,YAAW,WAAW;IACjE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuC;IAEzD,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAEpE;IAEK,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtE;IAEK,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE9C;CACD;AAED,8EAA8E;AAC9E,qBAAa,eAAgB,YAAW,WAAW;IAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAE7C,YAAY,IAAI,GAAE,MAAiD,EAElE;IAED,OAAO,CAAC,KAAK;
|
|
1
|
+
{"version":3,"file":"models-store.d.ts","sourceRoot":"","sources":["../../src/core/models-store.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAM3E,qBAAa,8BAA+B,YAAW,WAAW;IACjE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuC;IAEzD,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAEpE;IAEK,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtE;IAEK,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE9C;CACD;AAED,8EAA8E;AAC9E,qBAAa,eAAgB,YAAW,WAAW;IAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAE7C,YAAY,IAAI,GAAE,MAAiD,EAElE;IAED,OAAO,CAAC,KAAK;IAaP,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAIpE;IAEK,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAMtE;IAEK,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAM9C;CACD","sourcesContent":["import { join } from \"node:path\";\nimport type { ModelsStore, ModelsStoreEntry } from \"@ashx-j/lunr-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { type AuthStorageBackend, FileAuthStorageBackend } from \"./auth-storage.ts\";\n\ntype StoredModels = Record<string, ModelsStoreEntry>;\n\nexport class InMemoryCodingAgentModelsStore implements ModelsStore {\n\tprivate readonly entries = new Map<string, ModelsStoreEntry>();\n\n\tasync read(providerId: string): Promise<ModelsStoreEntry | undefined> {\n\t\treturn this.entries.get(providerId);\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry): Promise<void> {\n\t\tthis.entries.set(providerId, entry);\n\t}\n\n\tasync delete(providerId: string): Promise<void> {\n\t\tthis.entries.delete(providerId);\n\t}\n}\n\n/** Locked JSON-backed storage for dynamically refreshed provider catalogs. */\nexport class FileModelsStore implements ModelsStore {\n\tprivate readonly storage: AuthStorageBackend;\n\n\tconstructor(path: string = join(getAgentDir(), \"models-store.json\")) {\n\t\tthis.storage = new FileAuthStorageBackend(path);\n\t}\n\n\tprivate parse(content: string | undefined): StoredModels {\n\t\tconst trimmed = content?.replace(/^\\uFEFF/, \"\").trim();\n\t\tif (!trimmed) return {};\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(trimmed) as unknown;\n\t\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return {};\n\t\t\treturn parsed as StoredModels;\n\t\t} catch {\n\t\t\t// Mid-write / power-loss can leave NULs or truncated JSON.\n\t\t\treturn {};\n\t\t}\n\t}\n\n\tasync read(providerId: string): Promise<ModelsStoreEntry | undefined> {\n\t\treturn this.storage.withLock((content) => ({\n\t\t\tresult: structuredClone(this.parse(content)[providerId]),\n\t\t}));\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry): Promise<void> {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst current = this.parse(content);\n\t\t\tcurrent[providerId] = structuredClone(entry);\n\t\t\treturn { result: undefined, next: JSON.stringify(current, null, 2) };\n\t\t});\n\t}\n\n\tasync delete(providerId: string): Promise<void> {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst current = this.parse(content);\n\t\t\tdelete current[providerId];\n\t\t\treturn { result: undefined, next: JSON.stringify(current, null, 2) };\n\t\t});\n\t}\n}\n"]}
|
|
@@ -20,7 +20,19 @@ export class FileModelsStore {
|
|
|
20
20
|
this.storage = new FileAuthStorageBackend(path);
|
|
21
21
|
}
|
|
22
22
|
parse(content) {
|
|
23
|
-
|
|
23
|
+
const trimmed = content?.replace(/^\uFEFF/, "").trim();
|
|
24
|
+
if (!trimmed)
|
|
25
|
+
return {};
|
|
26
|
+
try {
|
|
27
|
+
const parsed = JSON.parse(trimmed);
|
|
28
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
29
|
+
return {};
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// Mid-write / power-loss can leave NULs or truncated JSON.
|
|
34
|
+
return {};
|
|
35
|
+
}
|
|
24
36
|
}
|
|
25
37
|
async read(providerId) {
|
|
26
38
|
return this.storage.withLock((content) => ({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models-store.js","sourceRoot":"","sources":["../../src/core/models-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAA2B,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAIpF,MAAM,OAAO,8BAA8B;IACzB,OAAO,GAAG,IAAI,GAAG,EAA4B,CAAC;IAE/D,KAAK,CAAC,IAAI,CAAC,UAAkB,EAAyC;QACrE,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAAA,CACpC;IAED,KAAK,CAAC,KAAK,CAAC,UAAkB,EAAE,KAAuB,EAAiB;QACvE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IAAA,CACpC;IAED,KAAK,CAAC,MAAM,CAAC,UAAkB,EAAiB;QAC/C,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAAA,CAChC;CACD;AAED,8EAA8E;AAC9E,MAAM,OAAO,eAAe;IACV,OAAO,CAAqB;IAE7C,YAAY,IAAI,GAAW,IAAI,CAAC,WAAW,EAAE,EAAE,mBAAmB,CAAC,EAAE;QACpE,IAAI,CAAC,OAAO,GAAG,IAAI,sBAAsB,CAAC,IAAI,CAAC,CAAC;IAAA,CAChD;IAEO,KAAK,CAAC,OAA2B,EAAgB;QACxD,OAAO,OAAO,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"models-store.js","sourceRoot":"","sources":["../../src/core/models-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,WAAW,EAAE,MA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;IAAA,CACD;IAED,KAAK,CAAC,IAAI,CAAC,UAAkB,EAAyC;QACrE,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;YAC1C,MAAM,EAAE,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,CAAC;SACxD,CAAC,CAAC,CAAC;IAAA,CACJ;IAED,KAAK,CAAC,KAAK,CAAC,UAAkB,EAAE,KAAuB,EAAiB;QACvE,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC;YACnD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACpC,OAAO,CAAC,UAAU,CAAC,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;YAC7C,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;QAAA,CACrE,CAAC,CAAC;IAAA,CACH;IAED,KAAK,CAAC,MAAM,CAAC,UAAkB,EAAiB;QAC/C,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC;YACnD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACpC,OAAO,OAAO,CAAC,UAAU,CAAC,CAAC;YAC3B,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;QAAA,CACrE,CAAC,CAAC;IAAA,CACH;CACD","sourcesContent":["import { join } from \"node:path\";\nimport type { ModelsStore, ModelsStoreEntry } from \"@ashx-j/lunr-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { type AuthStorageBackend, FileAuthStorageBackend } from \"./auth-storage.ts\";\n\ntype StoredModels = Record<string, ModelsStoreEntry>;\n\nexport class InMemoryCodingAgentModelsStore implements ModelsStore {\n\tprivate readonly entries = new Map<string, ModelsStoreEntry>();\n\n\tasync read(providerId: string): Promise<ModelsStoreEntry | undefined> {\n\t\treturn this.entries.get(providerId);\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry): Promise<void> {\n\t\tthis.entries.set(providerId, entry);\n\t}\n\n\tasync delete(providerId: string): Promise<void> {\n\t\tthis.entries.delete(providerId);\n\t}\n}\n\n/** Locked JSON-backed storage for dynamically refreshed provider catalogs. */\nexport class FileModelsStore implements ModelsStore {\n\tprivate readonly storage: AuthStorageBackend;\n\n\tconstructor(path: string = join(getAgentDir(), \"models-store.json\")) {\n\t\tthis.storage = new FileAuthStorageBackend(path);\n\t}\n\n\tprivate parse(content: string | undefined): StoredModels {\n\t\tconst trimmed = content?.replace(/^\\uFEFF/, \"\").trim();\n\t\tif (!trimmed) return {};\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(trimmed) as unknown;\n\t\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return {};\n\t\t\treturn parsed as StoredModels;\n\t\t} catch {\n\t\t\t// Mid-write / power-loss can leave NULs or truncated JSON.\n\t\t\treturn {};\n\t\t}\n\t}\n\n\tasync read(providerId: string): Promise<ModelsStoreEntry | undefined> {\n\t\treturn this.storage.withLock((content) => ({\n\t\t\tresult: structuredClone(this.parse(content)[providerId]),\n\t\t}));\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry): Promise<void> {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst current = this.parse(content);\n\t\t\tcurrent[providerId] = structuredClone(entry);\n\t\t\treturn { result: undefined, next: JSON.stringify(current, null, 2) };\n\t\t});\n\t}\n\n\tasync delete(providerId: string): Promise<void> {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst current = this.parse(content);\n\t\t\tdelete current[providerId];\n\t\t\treturn { result: undefined, next: JSON.stringify(current, null, 2) };\n\t\t});\n\t}\n}\n"]}
|
|
@@ -84,6 +84,15 @@ export interface GateOptions {
|
|
|
84
84
|
/** True when the current turn started from an explicit /swarm prompt — the
|
|
85
85
|
* user already asked for the swarm, so the swarm approval gate is skipped. */
|
|
86
86
|
explicitSwarmTurn?: boolean;
|
|
87
|
+
/** Assistant message that issued this tool call. Same-turn sibling SINGLE
|
|
88
|
+
* `subagent` calls count toward the swarm threshold. */
|
|
89
|
+
assistantMessage?: {
|
|
90
|
+
content?: ReadonlyArray<{
|
|
91
|
+
type?: string;
|
|
92
|
+
name?: string;
|
|
93
|
+
arguments?: unknown;
|
|
94
|
+
}>;
|
|
95
|
+
};
|
|
87
96
|
}
|
|
88
97
|
/**
|
|
89
98
|
* Returns a block result when the tool call should be blocked, else undefined.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permissions.d.ts","sourceRoot":"","sources":["../../src/core/permissions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAMH,6BAA6B;AAC7B,eAAO,MAAM,gBAAgB,6CAA8C,CAAC;AAC5E,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/D,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,cAAc,GAAG,cAAc,CAG1E;AAED,kEAAkE;AAClE,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAE5D;AAED;;;GAGG;AACH,wBAAgB,8BAA8B,CAC7C,QAAQ,EAAE,cAAc,GAAG,SAAS,EACpC,WAAW,EAAE,cAAc,GACzB,cAAc,CAGhB;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB;;4EAEwE;IACxE,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf;;uDAEmD;IACnD,IAAI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CASrE;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAW1E;AAED,wBAAgB,qBAAqB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAE9D;AAED,2EAA2E;AAC3E,wBAAgB,0BAA0B,IAAI,IAAI,CAIjD;AAED,+DAA+D;AAC/D,eAAO,MAAM,kBAAkB,4JAC2H,CAAC;AAoB3J,MAAM,WAAW,WAAW;IAC3B;mFAC+E;IAC/E,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAiED;;;;;;GAMG;AACH,wBAAsB,YAAY,CACjC,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,GAAG,EAAE,MAAM,EACX,SAAS,CAAC,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC,CAsEtD","sourcesContent":["/**\n * lunR: permission modes (Manual / YOLO / Plan / Auto).\n *\n * Per-session only — never persisted per session, but the default mode new\n * sessions start with is configurable in /settings (`defaultPermissionMode`,\n * default \"manual\").\n *\n * - manual: every mutating tool call (bash, edit, write) requires approval.\n * - yolo: auto-approve tools; the agent may still ask questions.\n * - plan: read-only; mutating tools are hard-blocked (planModeBlockReason).\n * - auto: fully autonomous; a system-prompt addendum steers the model to\n * self-decide, and rollback is force-enabled for the session.\n *\n * The gate is wired into `agent-session.ts` `_installAgentToolHooks` before\n * the synchronous `_toolCallGates` loop. beforeToolCall is already async, so\n * awaiting the approval dialog is fine.\n *\n * State (mode + session-scoped approvals) is keyed by session id so\n * concurrent gateway chats do not share permission decisions.\n */\n\nimport { resolve } from \"node:path\";\nimport { planModeBlockReason } from \"./plan-mode.ts\";\nimport { effectiveSwarmCount, SWARM_APPROVAL_THRESHOLD } from \"./swarm.ts\";\n\n/** Shift+Tab cycle order. */\nexport const PERMISSION_MODES = [\"manual\", \"yolo\", \"plan\", \"auto\"] as const;\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\nexport function nextPermissionMode(current: PermissionMode): PermissionMode {\n\tconst i = PERMISSION_MODES.indexOf(current);\n\treturn PERMISSION_MODES[(i + 1) % PERMISSION_MODES.length];\n}\n\n/** True when the (default or session) permission mode is plan. */\nexport function isPlanModeActive(sessionId?: string): boolean {\n\treturn getPermissionMode(sessionId) === \"plan\";\n}\n\n/**\n * Destination mode when leaving plan via approve / `/plan off` / `/plan <text>`.\n * Explicit Shift+Tab or `/mode` picks do not use this — they already chose a mode.\n */\nexport function restorePermissionModeAfterPlan(\n\tprevious: PermissionMode | undefined,\n\tdefaultMode: PermissionMode,\n): PermissionMode {\n\tif (previous && previous !== \"plan\") return previous;\n\treturn defaultMode === \"plan\" ? \"yolo\" : defaultMode;\n}\n\nexport interface ApprovalRequest {\n\ttoolName: string;\n\t/** \"bash\" (detail = command), \"edit\"/\"write\" (detail = path),\n\t * \"edit-outside\"/\"write-outside\" when path escapes cwd,\n\t * \"swarm\" for auto-activated agent swarms (detail = summary lines). */\n\taction: string;\n\tdetail: string;\n\t/** \"swarm\" when this is the agent-swarm approval prompt, \"plan\" for the\n\t * present_plan plan-approval prompt — the UI renders a dedicated dialog\n\t * for each instead of the generic tool dialog. */\n\tkind?: \"swarm\" | \"plan\";\n}\n\nexport type ApprovalDecision = \"once\" | \"session\" | \"reject\";\n/** Handlers may return a bare decision string, a reject carrying user feedback\n * that becomes the block reason the model sees, or an approve carrying optional\n * feedback (plan approval with comments). */\nexport type ApprovalResponse =\n\t| ApprovalDecision\n\t| { decision: \"reject\"; feedback: string }\n\t| { decision: \"approve\"; feedback?: string };\n\n/** Read-only tools that never need approval. */\nconst READ_ONLY_TOOLS = new Set([\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"web_search\",\n\t\"web_fetch\",\n\t\"fetch_content\",\n\t\"get_search_content\",\n\t\"sourcegraph\",\n\t\"repo_map\",\n\t\"symbol_outline\",\n\t\"read_block\",\n\t\"code_overview\",\n\t\"ast_search\",\n\t\"lsp_diagnostics\",\n\t\"lsp_hover\",\n\t\"lsp_definition\",\n\t\"lsp_references\",\n\t\"lsp_symbols\",\n\t\"lsp_code_actions\",\n\t\"lsp_completions\",\n\t\"behavior_load\",\n\t\"memory_load\",\n]);\n\n/** Tools that mutate state and must be gated in manual mode. */\nconst MUTATING_TOOLS = new Set([\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"behavior_add\",\n\t\"behavior_remove\",\n\t\"memory_add\",\n\t\"memory_remove\",\n\t\"cron\",\n]);\n\nconst REJECT_REASON = \"Rejected by user (permission mode: manual).\";\nexport const NO_HANDLER_REASON = \"Mutating tool blocked in manual mode: no approval channel available.\";\nexport const SWARM_REJECT_REASON = \"Agent swarm rejected by user.\";\nexport const NO_SWARM_HANDLER_REASON = \"Agent swarm blocked: no approval channel available.\";\n/** Session-approval key for auto-activated agent swarms. */\nconst SWARM_ACTION = \"swarm\";\n\ninterface PermissionContext {\n\tmode: PermissionMode;\n\tapprovals: Set<string>;\n}\n\nconst contexts = new Map<string, PermissionContext>();\nlet defaultContext: PermissionContext = { mode: \"manual\", approvals: new Set() };\nlet approvalHandler: ((req: ApprovalRequest) => Promise<ApprovalResponse>) | undefined;\n\nfunction getContext(sessionId?: string): PermissionContext {\n\tif (!sessionId) return defaultContext;\n\treturn contexts.get(sessionId) ?? defaultContext;\n}\n\nexport function createPermissionContext(sessionId: string, mode: PermissionMode = defaultContext.mode): void {\n\tcontexts.set(sessionId, { mode, approvals: new Set() });\n}\n\nexport function deletePermissionContext(sessionId: string): void {\n\tcontexts.delete(sessionId);\n}\n\nexport function getPermissionMode(sessionId?: string): PermissionMode {\n\treturn getContext(sessionId).mode;\n}\n\nexport function setPermissionMode(mode: PermissionMode, sessionId?: string): void {\n\tgetContext(sessionId).mode = mode;\n}\n\nexport function resetPermissions(defaultMode: PermissionMode = \"manual\", sessionId?: string): void {\n\tif (sessionId) {\n\t\tcontexts.set(sessionId, { mode: defaultMode, approvals: new Set() });\n\t} else {\n\t\tdefaultContext = { mode: defaultMode, approvals: new Set() };\n\t}\n}\n\nexport function registerApprovalHandler(fn: ((req: ApprovalRequest) => Promise<ApprovalResponse>) | undefined): void {\n\tapprovalHandler = fn;\n}\n\n/** Model-facing result texts for the present_plan tool. */\nexport const PLAN_APPROVED_TEXT = \"Plan approved — implement it now.\";\nexport const PLAN_DECLINED_TEXT = \"Plan declined — revise the plan and call present_plan again.\";\nexport const PLAN_PASS_THROUGH_TEXT = \"Plan presented. The user will review and reply.\";\n\n/** lunr: map an approval response to the model-facing present_plan result text. */\nexport function planApprovalResultText(resp: ApprovalResponse): string {\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\tif (decision === \"reject\") {\n\t\treturn feedback\n\t\t\t? `Plan declined: ${feedback} — revise the plan and call present_plan again.`\n\t\t\t: PLAN_DECLINED_TEXT;\n\t}\n\treturn feedback ? `Plan approved with feedback: ${feedback} — implement it now.` : PLAN_APPROVED_TEXT;\n}\n\n/**\n * lunr: present_plan approval request. Unlike the mutating-tool and swarm gates\n * this fails OPEN when no approval handler is registered (or none is reachable,\n * e.g. a gateway turn without a chat context): headless sessions have no one to\n * show the dialog to, so the plan is presented and the user replies in chat\n * instead of deadlocking the turn. Everything else keeps fail-closed.\n */\nexport async function requestPlanApproval(summary: string): Promise<string> {\n\tif (!approvalHandler) return PLAN_PASS_THROUGH_TEXT;\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({ toolName: \"present_plan\", action: \"plan\", detail: summary, kind: \"plan\" });\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : \"approval request failed\";\n\t\tif (message === NO_HANDLER_REASON) return PLAN_PASS_THROUGH_TEXT;\n\t\treturn `Plan declined: ${message} — revise the plan and call present_plan again.`;\n\t}\n\treturn planApprovalResultText(resp);\n}\n\nexport function clearSessionApprovals(sessionId?: string): void {\n\tgetContext(sessionId).approvals.clear();\n}\n\n/** Test seam: remove every per-session context and restore the default. */\nexport function resetAllPermissionContexts(): void {\n\tcontexts.clear();\n\tdefaultContext = { mode: \"manual\", approvals: new Set() };\n\tapprovalHandler = undefined;\n}\n\n/** Appended to the system prompt while auto mode is active. */\nexport const AUTO_MODE_ADDENDUM =\n\t\"You are running fully autonomously. Do not ask the user questions or wait for confirmation; make reasonable decisions and complete the task end-to-end.\";\n\nfunction isPathOutsideCwd(absPath: string, cwd: string): boolean {\n\tconst norm = (p: string) => p.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n\tconst np = norm(absPath);\n\tconst nc = norm(cwd);\n\tif (np === nc) return false;\n\treturn !np.startsWith(`${nc}/`);\n}\n\nfunction resolvePath(cwd: string, p: unknown): string {\n\tif (typeof p !== \"string\") return \"\";\n\tif (!p) return \"\";\n\treturn resolve(cwd, p);\n}\n\nfunction isMutatingTool(toolName: string): boolean {\n\treturn MUTATING_TOOLS.has(toolName);\n}\n\nexport interface GateOptions {\n\t/** True when the current turn started from an explicit /swarm prompt — the\n\t * user already asked for the swarm, so the swarm approval gate is skipped. */\n\texplicitSwarmTurn?: boolean;\n}\n\n/** First task text of a parallel fan-out, used as the dialog summary line. */\nfunction swarmTaskSummary(input: Record<string, unknown>): string {\n\tif (!Array.isArray(input.tasks)) return \"\";\n\tfor (const task of input.tasks) {\n\t\tconst text = task && typeof task === \"object\" ? (task as { task?: unknown }).task : undefined;\n\t\tif (typeof text === \"string\" && text.trim()) return sanitizeDetail(text);\n\t}\n\treturn \"\";\n}\n\n/**\n * Agent-swarm gate. An auto-activated swarm (one `subagent` call launching more\n * than SWARM_APPROVAL_THRESHOLD parallel subagents) requires user approval in\n * manual AND yolo modes; auto mode runs it unconditionally and explicit /swarm\n * turns are pre-approved. Fail-closed without an approval handler, same as the\n * mutating-tool gate.\n */\nasync function gateSwarmCall(\n\tinput: Record<string, unknown>,\n\tctx: PermissionContext,\n\toptions?: GateOptions,\n): Promise<{ block: true; reason: string } | undefined> {\n\tif (ctx.mode === \"auto\") return undefined;\n\tif (options?.explicitSwarmTurn) return undefined;\n\tconst count = effectiveSwarmCount(input);\n\tif (count <= SWARM_APPROVAL_THRESHOLD) return undefined;\n\tif (ctx.approvals.has(SWARM_ACTION)) return undefined;\n\n\tif (!approvalHandler) {\n\t\treturn { block: true, reason: NO_SWARM_HANDLER_REASON };\n\t}\n\n\tconst summary = swarmTaskSummary(input);\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({\n\t\t\ttoolName: \"subagent\",\n\t\t\taction: SWARM_ACTION,\n\t\t\tdetail: summary ? `agent swarm (${count} subagents)\\n${summary}` : `agent swarm (${count} subagents)`,\n\t\t\tkind: \"swarm\",\n\t\t});\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : NO_SWARM_HANDLER_REASON;\n\t\treturn { block: true, reason: message };\n\t}\n\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tif (decision === \"session\") {\n\t\tctx.approvals.add(SWARM_ACTION);\n\t\treturn undefined;\n\t}\n\tif (decision === \"reject\") {\n\t\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\t\treturn { block: true, reason: feedback ? `${SWARM_REJECT_REASON} ${feedback}` : SWARM_REJECT_REASON };\n\t}\n\treturn undefined;\n}\n\nfunction sanitizeDetail(value: unknown): string {\n\tconst text = String(value ?? \"\").trim();\n\treturn text.length > 200 ? `${text.slice(0, 200)}…` : text;\n}\n\n/**\n * Returns a block result when the tool call should be blocked, else undefined.\n * Read-only tools always pass. YOLO and Auto always pass mutating tools. Plan\n * mode hard-blocks mutating tools (no prompt). Manual mode gates every mutating\n * tool; if an approval handler is registered it is asked, otherwise the call is\n * blocked (fail-closed — no silent allow).\n */\nexport async function gateToolCall(\n\ttoolName: string,\n\tinput: Record<string, unknown>,\n\tcwd: string,\n\tsessionId?: string,\n\toptions?: GateOptions,\n): Promise<{ block: true; reason: string } | undefined> {\n\tconst ctx = getContext(sessionId);\n\tif (READ_ONLY_TOOLS.has(toolName)) return undefined;\n\n\t// lunr: agent-swarm gate runs before the mode early-return — it applies in\n\t// yolo mode too (only auto mode bypasses it).\n\tif (toolName === \"subagent\") {\n\t\tconst swarmBlock = await gateSwarmCall(input, ctx, options);\n\t\tif (swarmBlock) return swarmBlock;\n\t}\n\n\tif (ctx.mode === \"plan\") {\n\t\tconst reason = planModeBlockReason(toolName, input);\n\t\treturn reason ? { block: true, reason } : undefined;\n\t}\n\n\tif (ctx.mode !== \"manual\") return undefined;\n\tif (!isMutatingTool(toolName)) return undefined;\n\n\tlet action: string;\n\tlet detail: string;\n\n\tif (toolName === \"bash\") {\n\t\taction = \"bash\";\n\t\tdetail = sanitizeDetail(input.command);\n\t} else if (toolName === \"edit\" || toolName === \"write\") {\n\t\tconst path = resolvePath(cwd, input.path);\n\t\tconst outside = path ? isPathOutsideCwd(path, cwd) : false;\n\t\taction = outside ? `${toolName}-outside` : toolName;\n\t\tdetail = path || String(input.path ?? \"\");\n\t} else if (toolName === \"behavior_add\" || toolName === \"memory_add\") {\n\t\taction = toolName;\n\t\tdetail = sanitizeDetail(input.content);\n\t} else if (toolName === \"behavior_remove\" || toolName === \"memory_remove\") {\n\t\taction = toolName;\n\t\tdetail = sanitizeDetail(input.line);\n\t} else if (toolName === \"cron\") {\n\t\taction = \"cron\";\n\t\tdetail = sanitizeDetail(input.action);\n\t} else {\n\t\t// All other mutating tools fall back to the tool name with no extra detail.\n\t\taction = toolName;\n\t\tdetail = \"\";\n\t}\n\n\tif (ctx.approvals.has(action)) return undefined;\n\n\tif (!approvalHandler) {\n\t\treturn { block: true, reason: NO_HANDLER_REASON };\n\t}\n\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({ toolName, action, detail });\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : NO_HANDLER_REASON;\n\t\treturn { block: true, reason: message };\n\t}\n\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tif (decision === \"session\") {\n\t\tctx.approvals.add(action);\n\t\treturn undefined;\n\t}\n\tif (decision === \"reject\") {\n\t\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\t\treturn { block: true, reason: feedback ? `${REJECT_REASON} ${feedback}` : REJECT_REASON };\n\t}\n\t// \"once\" — allow this call only\n\treturn undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"permissions.d.ts","sourceRoot":"","sources":["../../src/core/permissions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAMH,6BAA6B;AAC7B,eAAO,MAAM,gBAAgB,6CAA8C,CAAC;AAC5E,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/D,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,cAAc,GAAG,cAAc,CAG1E;AAED,kEAAkE;AAClE,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAE5D;AAED;;;GAGG;AACH,wBAAgB,8BAA8B,CAC7C,QAAQ,EAAE,cAAc,GAAG,SAAS,EACpC,WAAW,EAAE,cAAc,GACzB,cAAc,CAGhB;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB;;4EAEwE;IACxE,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf;;uDAEmD;IACnD,IAAI,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;CACxB;AAED,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,SAAS,GAAG,QAAQ,CAAC;AAC7D;;8CAE8C;AAC9C,MAAM,MAAM,gBAAgB,GACzB,gBAAgB,GAChB;IAAE,QAAQ,EAAE,QAAQ,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B,0BAA0B,IAAI,IAAI,CAIjD;AAED,+DAA+D;AAC/D,eAAO,MAAM,kBAAkB,4JAC2H,CAAC;AAyB3J,MAAM,WAAW,WAAW;IAC3B;mFAC+E;IAC/E,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B;6DACyD;IACzD,gBAAgB,CAAC,EAAE;QAClB,OAAO,CAAC,EAAE,aAAa,CAAC;YAAE,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,SAAS,CAAC,EAAE,OAAO,CAAA;SAAE,CAAC,CAAC;KAC/E,CAAC;CACF;AA6FD;;;;;;GAMG;AACH,wBAAsB,YAAY,CACjC,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,GAAG,EAAE,MAAM,EACX,SAAS,CAAC,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC,CAyEtD","sourcesContent":["/**\n * lunR: permission modes (Manual / YOLO / Plan / Auto).\n *\n * Per-session only — never persisted per session, but the default mode new\n * sessions start with is configurable in /settings (`defaultPermissionMode`,\n * default \"manual\").\n *\n * - manual: every mutating tool call (bash, edit, write) requires approval.\n * - yolo: auto-approve tools; the agent may still ask questions.\n * - plan: read-only; mutating tools are hard-blocked (planModeBlockReason).\n * - auto: fully autonomous; a system-prompt addendum steers the model to\n * self-decide, and rollback is force-enabled for the session.\n *\n * The gate is wired into `agent-session.ts` `_installAgentToolHooks` before\n * the synchronous `_toolCallGates` loop. beforeToolCall is already async, so\n * awaiting the approval dialog is fine.\n *\n * State (mode + session-scoped approvals) is keyed by session id so\n * concurrent gateway chats do not share permission decisions.\n */\n\nimport { resolve } from \"node:path\";\nimport { isCodeRewriteMutating, planModeBlockReason } from \"./plan-mode.ts\";\nimport { effectiveSwarmCountForTurn, SWARM_APPROVAL_THRESHOLD } from \"./swarm.ts\";\n\n/** Shift+Tab cycle order. */\nexport const PERMISSION_MODES = [\"manual\", \"yolo\", \"plan\", \"auto\"] as const;\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\nexport function nextPermissionMode(current: PermissionMode): PermissionMode {\n\tconst i = PERMISSION_MODES.indexOf(current);\n\treturn PERMISSION_MODES[(i + 1) % PERMISSION_MODES.length];\n}\n\n/** True when the (default or session) permission mode is plan. */\nexport function isPlanModeActive(sessionId?: string): boolean {\n\treturn getPermissionMode(sessionId) === \"plan\";\n}\n\n/**\n * Destination mode when leaving plan via approve / `/plan off` / `/plan <text>`.\n * Explicit Shift+Tab or `/mode` picks do not use this — they already chose a mode.\n */\nexport function restorePermissionModeAfterPlan(\n\tprevious: PermissionMode | undefined,\n\tdefaultMode: PermissionMode,\n): PermissionMode {\n\tif (previous && previous !== \"plan\") return previous;\n\treturn defaultMode === \"plan\" ? \"yolo\" : defaultMode;\n}\n\nexport interface ApprovalRequest {\n\ttoolName: string;\n\t/** \"bash\" (detail = command), \"edit\"/\"write\" (detail = path),\n\t * \"edit-outside\"/\"write-outside\" when path escapes cwd,\n\t * \"swarm\" for auto-activated agent swarms (detail = summary lines). */\n\taction: string;\n\tdetail: string;\n\t/** \"swarm\" when this is the agent-swarm approval prompt, \"plan\" for the\n\t * present_plan plan-approval prompt — the UI renders a dedicated dialog\n\t * for each instead of the generic tool dialog. */\n\tkind?: \"swarm\" | \"plan\";\n}\n\nexport type ApprovalDecision = \"once\" | \"session\" | \"reject\";\n/** Handlers may return a bare decision string, a reject carrying user feedback\n * that becomes the block reason the model sees, or an approve carrying optional\n * feedback (plan approval with comments). */\nexport type ApprovalResponse =\n\t| ApprovalDecision\n\t| { decision: \"reject\"; feedback: string }\n\t| { decision: \"approve\"; feedback?: string };\n\n/** Read-only tools that never need approval. */\nconst READ_ONLY_TOOLS = new Set([\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"web_search\",\n\t\"web_fetch\",\n\t\"fetch_content\",\n\t\"get_search_content\",\n\t\"sourcegraph\",\n\t\"repo_map\",\n\t\"symbol_outline\",\n\t\"read_block\",\n\t\"code_overview\",\n\t\"ast_search\",\n\t\"lsp_diagnostics\",\n\t\"lsp_hover\",\n\t\"lsp_definition\",\n\t\"lsp_references\",\n\t\"lsp_symbols\",\n\t\"lsp_code_actions\",\n\t\"lsp_completions\",\n\t\"behavior_load\",\n\t\"memory_load\",\n]);\n\n/** Tools that mutate state and must be gated in manual mode. */\nconst MUTATING_TOOLS = new Set([\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"behavior_add\",\n\t\"behavior_remove\",\n\t\"memory_add\",\n\t\"memory_remove\",\n\t\"cron\",\n]);\n\nconst REJECT_REASON = \"Rejected by user (permission mode: manual).\";\nexport const NO_HANDLER_REASON = \"Mutating tool blocked in manual mode: no approval channel available.\";\nexport const SWARM_REJECT_REASON = \"Agent swarm rejected by user.\";\nexport const NO_SWARM_HANDLER_REASON = \"Agent swarm blocked: no approval channel available.\";\n/** Session-approval key for auto-activated agent swarms. */\nconst SWARM_ACTION = \"swarm\";\n\ninterface PermissionContext {\n\tmode: PermissionMode;\n\tapprovals: Set<string>;\n}\n\nconst contexts = new Map<string, PermissionContext>();\nlet defaultContext: PermissionContext = { mode: \"manual\", approvals: new Set() };\nlet approvalHandler: ((req: ApprovalRequest) => Promise<ApprovalResponse>) | undefined;\n/** One swarm prompt covers every sibling SINGLE `subagent` on the same assistant message. */\nconst turnSwarmDecisions = new WeakMap<object, { decision: ApprovalDecision; feedback?: string }>();\n\nfunction getContext(sessionId?: string): PermissionContext {\n\tif (!sessionId) return defaultContext;\n\treturn contexts.get(sessionId) ?? defaultContext;\n}\n\nexport function createPermissionContext(sessionId: string, mode: PermissionMode = defaultContext.mode): void {\n\tcontexts.set(sessionId, { mode, approvals: new Set() });\n}\n\nexport function deletePermissionContext(sessionId: string): void {\n\tcontexts.delete(sessionId);\n}\n\nexport function getPermissionMode(sessionId?: string): PermissionMode {\n\treturn getContext(sessionId).mode;\n}\n\nexport function setPermissionMode(mode: PermissionMode, sessionId?: string): void {\n\tgetContext(sessionId).mode = mode;\n}\n\nexport function resetPermissions(defaultMode: PermissionMode = \"manual\", sessionId?: string): void {\n\tif (sessionId) {\n\t\tcontexts.set(sessionId, { mode: defaultMode, approvals: new Set() });\n\t} else {\n\t\tdefaultContext = { mode: defaultMode, approvals: new Set() };\n\t}\n}\n\nexport function registerApprovalHandler(fn: ((req: ApprovalRequest) => Promise<ApprovalResponse>) | undefined): void {\n\tapprovalHandler = fn;\n}\n\n/** Model-facing result texts for the present_plan tool. */\nexport const PLAN_APPROVED_TEXT = \"Plan approved — implement it now.\";\nexport const PLAN_DECLINED_TEXT = \"Plan declined — revise the plan and call present_plan again.\";\nexport const PLAN_PASS_THROUGH_TEXT = \"Plan presented. The user will review and reply.\";\n\n/** lunr: map an approval response to the model-facing present_plan result text. */\nexport function planApprovalResultText(resp: ApprovalResponse): string {\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\tif (decision === \"reject\") {\n\t\treturn feedback\n\t\t\t? `Plan declined: ${feedback} — revise the plan and call present_plan again.`\n\t\t\t: PLAN_DECLINED_TEXT;\n\t}\n\treturn feedback ? `Plan approved with feedback: ${feedback} — implement it now.` : PLAN_APPROVED_TEXT;\n}\n\n/**\n * lunr: present_plan approval request. Unlike the mutating-tool and swarm gates\n * this fails OPEN when no approval handler is registered (or none is reachable,\n * e.g. a gateway turn without a chat context): headless sessions have no one to\n * show the dialog to, so the plan is presented and the user replies in chat\n * instead of deadlocking the turn. Everything else keeps fail-closed.\n */\nexport async function requestPlanApproval(summary: string): Promise<string> {\n\tif (!approvalHandler) return PLAN_PASS_THROUGH_TEXT;\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({ toolName: \"present_plan\", action: \"plan\", detail: summary, kind: \"plan\" });\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : \"approval request failed\";\n\t\tif (message === NO_HANDLER_REASON) return PLAN_PASS_THROUGH_TEXT;\n\t\treturn `Plan declined: ${message} — revise the plan and call present_plan again.`;\n\t}\n\treturn planApprovalResultText(resp);\n}\n\nexport function clearSessionApprovals(sessionId?: string): void {\n\tgetContext(sessionId).approvals.clear();\n}\n\n/** Test seam: remove every per-session context and restore the default. */\nexport function resetAllPermissionContexts(): void {\n\tcontexts.clear();\n\tdefaultContext = { mode: \"manual\", approvals: new Set() };\n\tapprovalHandler = undefined;\n}\n\n/** Appended to the system prompt while auto mode is active. */\nexport const AUTO_MODE_ADDENDUM =\n\t\"You are running fully autonomously. Do not ask the user questions or wait for confirmation; make reasonable decisions and complete the task end-to-end.\";\n\nfunction isPathOutsideCwd(absPath: string, cwd: string): boolean {\n\tconst norm = (p: string) => p.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n\tconst np = norm(absPath);\n\tconst nc = norm(cwd);\n\tif (np === nc) return false;\n\treturn !np.startsWith(`${nc}/`);\n}\n\nfunction resolvePath(cwd: string, p: unknown): string {\n\tif (typeof p !== \"string\") return \"\";\n\tif (!p) return \"\";\n\treturn resolve(cwd, p);\n}\n\nfunction isMutatingTool(toolName: string): boolean {\n\treturn MUTATING_TOOLS.has(toolName);\n}\n\nfunction requiresManualApproval(toolName: string, input: Record<string, unknown>): boolean {\n\tif (isMutatingTool(toolName)) return true;\n\treturn toolName === \"code_rewrite\" && isCodeRewriteMutating(input);\n}\n\nexport interface GateOptions {\n\t/** True when the current turn started from an explicit /swarm prompt — the\n\t * user already asked for the swarm, so the swarm approval gate is skipped. */\n\texplicitSwarmTurn?: boolean;\n\t/** Assistant message that issued this tool call. Same-turn sibling SINGLE\n\t * `subagent` calls count toward the swarm threshold. */\n\tassistantMessage?: {\n\t\tcontent?: ReadonlyArray<{ type?: string; name?: string; arguments?: unknown }>;\n\t};\n}\n\nfunction firstTaskText(value: unknown): string {\n\tif (typeof value === \"string\" && value.trim()) return sanitizeDetail(value);\n\treturn \"\";\n}\n\n/** First task text of a parallel fan-out or sibling SINGLE, used as the dialog summary. */\nfunction swarmTaskSummary(input: Record<string, unknown>, assistantMessage?: GateOptions[\"assistantMessage\"]): string {\n\tif (Array.isArray(input.tasks)) {\n\t\tfor (const task of input.tasks) {\n\t\t\tconst text = task && typeof task === \"object\" ? firstTaskText((task as { task?: unknown }).task) : \"\";\n\t\t\tif (text) return text;\n\t\t}\n\t}\n\tconst own = firstTaskText(input.task);\n\tif (own) return own;\n\tfor (const block of assistantMessage?.content ?? []) {\n\t\tif (block.type !== \"toolCall\" || block.name !== \"subagent\") continue;\n\t\tconst args =\n\t\t\tblock.arguments && typeof block.arguments === \"object\" && !Array.isArray(block.arguments)\n\t\t\t\t? (block.arguments as Record<string, unknown>)\n\t\t\t\t: undefined;\n\t\tconst text = firstTaskText(args?.task);\n\t\tif (text) return text;\n\t}\n\treturn \"\";\n}\n\n/**\n * Agent-swarm gate. An auto-activated swarm (more than SWARM_APPROVAL_THRESHOLD\n * parallel subagents in one `tasks`/`chain.parallel` call, or that many same-turn\n * SINGLE `subagent` calls) requires user approval in manual AND yolo modes; auto\n * mode runs it unconditionally and explicit /swarm turns are pre-approved.\n * Fail-closed without an approval handler, same as the mutating-tool gate.\n */\nasync function gateSwarmCall(\n\tinput: Record<string, unknown>,\n\tctx: PermissionContext,\n\toptions?: GateOptions,\n): Promise<{ block: true; reason: string } | undefined> {\n\tif (ctx.mode === \"auto\") return undefined;\n\tif (options?.explicitSwarmTurn) return undefined;\n\tconst count = effectiveSwarmCountForTurn(input, options?.assistantMessage);\n\tif (count <= SWARM_APPROVAL_THRESHOLD) return undefined;\n\tif (ctx.approvals.has(SWARM_ACTION)) return undefined;\n\n\tconst turnKey = options?.assistantMessage;\n\tconst cached = turnKey ? turnSwarmDecisions.get(turnKey) : undefined;\n\tif (cached) {\n\t\tif (cached.decision === \"reject\") {\n\t\t\treturn { block: true, reason: cached.feedback ? `${SWARM_REJECT_REASON} ${cached.feedback}` : SWARM_REJECT_REASON };\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tif (!approvalHandler) {\n\t\treturn { block: true, reason: NO_SWARM_HANDLER_REASON };\n\t}\n\n\tconst summary = swarmTaskSummary(input, options?.assistantMessage);\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({\n\t\t\ttoolName: \"subagent\",\n\t\t\taction: SWARM_ACTION,\n\t\t\tdetail: summary ? `agent swarm (${count} subagents)\\n${summary}` : `agent swarm (${count} subagents)`,\n\t\t\tkind: \"swarm\",\n\t\t});\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : NO_SWARM_HANDLER_REASON;\n\t\treturn { block: true, reason: message };\n\t}\n\n\tconst rawDecision = typeof resp === \"string\" ? resp : resp.decision;\n\tconst decision: ApprovalDecision = rawDecision === \"approve\" ? \"once\" : rawDecision;\n\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\tif (turnKey) turnSwarmDecisions.set(turnKey, { decision, ...(feedback ? { feedback } : {}) });\n\tif (decision === \"session\") {\n\t\tctx.approvals.add(SWARM_ACTION);\n\t\treturn undefined;\n\t}\n\tif (decision === \"reject\") {\n\t\treturn { block: true, reason: feedback ? `${SWARM_REJECT_REASON} ${feedback}` : SWARM_REJECT_REASON };\n\t}\n\treturn undefined;\n}\n\nfunction sanitizeDetail(value: unknown): string {\n\tconst text = String(value ?? \"\").trim();\n\treturn text.length > 200 ? `${text.slice(0, 200)}…` : text;\n}\n\n/**\n * Returns a block result when the tool call should be blocked, else undefined.\n * Read-only tools always pass. YOLO and Auto always pass mutating tools. Plan\n * mode hard-blocks mutating tools (no prompt). Manual mode gates every mutating\n * tool; if an approval handler is registered it is asked, otherwise the call is\n * blocked (fail-closed — no silent allow).\n */\nexport async function gateToolCall(\n\ttoolName: string,\n\tinput: Record<string, unknown>,\n\tcwd: string,\n\tsessionId?: string,\n\toptions?: GateOptions,\n): Promise<{ block: true; reason: string } | undefined> {\n\tconst ctx = getContext(sessionId);\n\tif (READ_ONLY_TOOLS.has(toolName)) return undefined;\n\n\t// lunr: agent-swarm gate runs before the mode early-return — it applies in\n\t// yolo mode too (only auto mode bypasses it).\n\tif (toolName === \"subagent\") {\n\t\tconst swarmBlock = await gateSwarmCall(input, ctx, options);\n\t\tif (swarmBlock) return swarmBlock;\n\t}\n\n\tif (ctx.mode === \"plan\") {\n\t\tconst reason = planModeBlockReason(toolName, input);\n\t\treturn reason ? { block: true, reason } : undefined;\n\t}\n\n\tif (ctx.mode !== \"manual\") return undefined;\n\tif (!requiresManualApproval(toolName, input)) return undefined;\n\n\tlet action: string;\n\tlet detail: string;\n\n\tif (toolName === \"bash\") {\n\t\taction = \"bash\";\n\t\tdetail = sanitizeDetail(input.command);\n\t} else if (toolName === \"edit\" || toolName === \"write\") {\n\t\tconst path = resolvePath(cwd, input.path);\n\t\tconst outside = path ? isPathOutsideCwd(path, cwd) : false;\n\t\taction = outside ? `${toolName}-outside` : toolName;\n\t\tdetail = path || String(input.path ?? \"\");\n\t} else if (toolName === \"behavior_add\" || toolName === \"memory_add\") {\n\t\taction = toolName;\n\t\tdetail = sanitizeDetail(input.content);\n\t} else if (toolName === \"behavior_remove\" || toolName === \"memory_remove\") {\n\t\taction = toolName;\n\t\tdetail = sanitizeDetail(input.line);\n\t} else if (toolName === \"cron\") {\n\t\taction = \"cron\";\n\t\tdetail = sanitizeDetail(input.action);\n\t} else if (toolName === \"code_rewrite\") {\n\t\taction = \"code_rewrite\";\n\t\tdetail = sanitizeDetail(input.path ?? input.pattern);\n\t} else {\n\t\t// All other mutating tools fall back to the tool name with no extra detail.\n\t\taction = toolName;\n\t\tdetail = \"\";\n\t}\n\n\tif (ctx.approvals.has(action)) return undefined;\n\n\tif (!approvalHandler) {\n\t\treturn { block: true, reason: NO_HANDLER_REASON };\n\t}\n\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({ toolName, action, detail });\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : NO_HANDLER_REASON;\n\t\treturn { block: true, reason: message };\n\t}\n\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tif (decision === \"session\") {\n\t\tctx.approvals.add(action);\n\t\treturn undefined;\n\t}\n\tif (decision === \"reject\") {\n\t\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\t\treturn { block: true, reason: feedback ? `${REJECT_REASON} ${feedback}` : REJECT_REASON };\n\t}\n\t// \"once\" — allow this call only\n\treturn undefined;\n}\n"]}
|
package/dist/core/permissions.js
CHANGED
|
@@ -19,8 +19,8 @@
|
|
|
19
19
|
* concurrent gateway chats do not share permission decisions.
|
|
20
20
|
*/
|
|
21
21
|
import { resolve } from "node:path";
|
|
22
|
-
import { planModeBlockReason } from "./plan-mode.js";
|
|
23
|
-
import {
|
|
22
|
+
import { isCodeRewriteMutating, planModeBlockReason } from "./plan-mode.js";
|
|
23
|
+
import { effectiveSwarmCountForTurn, SWARM_APPROVAL_THRESHOLD } from "./swarm.js";
|
|
24
24
|
/** Shift+Tab cycle order. */
|
|
25
25
|
export const PERMISSION_MODES = ["manual", "yolo", "plan", "auto"];
|
|
26
26
|
export function nextPermissionMode(current) {
|
|
@@ -86,6 +86,8 @@ const SWARM_ACTION = "swarm";
|
|
|
86
86
|
const contexts = new Map();
|
|
87
87
|
let defaultContext = { mode: "manual", approvals: new Set() };
|
|
88
88
|
let approvalHandler;
|
|
89
|
+
/** One swarm prompt covers every sibling SINGLE `subagent` on the same assistant message. */
|
|
90
|
+
const turnSwarmDecisions = new WeakMap();
|
|
89
91
|
function getContext(sessionId) {
|
|
90
92
|
if (!sessionId)
|
|
91
93
|
return defaultContext;
|
|
@@ -180,38 +182,69 @@ function resolvePath(cwd, p) {
|
|
|
180
182
|
function isMutatingTool(toolName) {
|
|
181
183
|
return MUTATING_TOOLS.has(toolName);
|
|
182
184
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
185
|
+
function requiresManualApproval(toolName, input) {
|
|
186
|
+
if (isMutatingTool(toolName))
|
|
187
|
+
return true;
|
|
188
|
+
return toolName === "code_rewrite" && isCodeRewriteMutating(input);
|
|
189
|
+
}
|
|
190
|
+
function firstTaskText(value) {
|
|
191
|
+
if (typeof value === "string" && value.trim())
|
|
192
|
+
return sanitizeDetail(value);
|
|
193
|
+
return "";
|
|
194
|
+
}
|
|
195
|
+
/** First task text of a parallel fan-out or sibling SINGLE, used as the dialog summary. */
|
|
196
|
+
function swarmTaskSummary(input, assistantMessage) {
|
|
197
|
+
if (Array.isArray(input.tasks)) {
|
|
198
|
+
for (const task of input.tasks) {
|
|
199
|
+
const text = task && typeof task === "object" ? firstTaskText(task.task) : "";
|
|
200
|
+
if (text)
|
|
201
|
+
return text;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const own = firstTaskText(input.task);
|
|
205
|
+
if (own)
|
|
206
|
+
return own;
|
|
207
|
+
for (const block of assistantMessage?.content ?? []) {
|
|
208
|
+
if (block.type !== "toolCall" || block.name !== "subagent")
|
|
209
|
+
continue;
|
|
210
|
+
const args = block.arguments && typeof block.arguments === "object" && !Array.isArray(block.arguments)
|
|
211
|
+
? block.arguments
|
|
212
|
+
: undefined;
|
|
213
|
+
const text = firstTaskText(args?.task);
|
|
214
|
+
if (text)
|
|
215
|
+
return text;
|
|
191
216
|
}
|
|
192
217
|
return "";
|
|
193
218
|
}
|
|
194
219
|
/**
|
|
195
|
-
* Agent-swarm gate. An auto-activated swarm (
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
* mutating-tool gate.
|
|
220
|
+
* Agent-swarm gate. An auto-activated swarm (more than SWARM_APPROVAL_THRESHOLD
|
|
221
|
+
* parallel subagents in one `tasks`/`chain.parallel` call, or that many same-turn
|
|
222
|
+
* SINGLE `subagent` calls) requires user approval in manual AND yolo modes; auto
|
|
223
|
+
* mode runs it unconditionally and explicit /swarm turns are pre-approved.
|
|
224
|
+
* Fail-closed without an approval handler, same as the mutating-tool gate.
|
|
200
225
|
*/
|
|
201
226
|
async function gateSwarmCall(input, ctx, options) {
|
|
202
227
|
if (ctx.mode === "auto")
|
|
203
228
|
return undefined;
|
|
204
229
|
if (options?.explicitSwarmTurn)
|
|
205
230
|
return undefined;
|
|
206
|
-
const count =
|
|
231
|
+
const count = effectiveSwarmCountForTurn(input, options?.assistantMessage);
|
|
207
232
|
if (count <= SWARM_APPROVAL_THRESHOLD)
|
|
208
233
|
return undefined;
|
|
209
234
|
if (ctx.approvals.has(SWARM_ACTION))
|
|
210
235
|
return undefined;
|
|
236
|
+
const turnKey = options?.assistantMessage;
|
|
237
|
+
const cached = turnKey ? turnSwarmDecisions.get(turnKey) : undefined;
|
|
238
|
+
if (cached) {
|
|
239
|
+
if (cached.decision === "reject") {
|
|
240
|
+
return { block: true, reason: cached.feedback ? `${SWARM_REJECT_REASON} ${cached.feedback}` : SWARM_REJECT_REASON };
|
|
241
|
+
}
|
|
242
|
+
return undefined;
|
|
243
|
+
}
|
|
211
244
|
if (!approvalHandler) {
|
|
212
245
|
return { block: true, reason: NO_SWARM_HANDLER_REASON };
|
|
213
246
|
}
|
|
214
|
-
const summary = swarmTaskSummary(input);
|
|
247
|
+
const summary = swarmTaskSummary(input, options?.assistantMessage);
|
|
215
248
|
let resp;
|
|
216
249
|
try {
|
|
217
250
|
resp = await approvalHandler({
|
|
@@ -225,13 +258,16 @@ async function gateSwarmCall(input, ctx, options) {
|
|
|
225
258
|
const message = err instanceof Error ? err.message : NO_SWARM_HANDLER_REASON;
|
|
226
259
|
return { block: true, reason: message };
|
|
227
260
|
}
|
|
228
|
-
const
|
|
261
|
+
const rawDecision = typeof resp === "string" ? resp : resp.decision;
|
|
262
|
+
const decision = rawDecision === "approve" ? "once" : rawDecision;
|
|
263
|
+
const feedback = typeof resp === "string" ? undefined : resp.feedback?.trim();
|
|
264
|
+
if (turnKey)
|
|
265
|
+
turnSwarmDecisions.set(turnKey, { decision, ...(feedback ? { feedback } : {}) });
|
|
229
266
|
if (decision === "session") {
|
|
230
267
|
ctx.approvals.add(SWARM_ACTION);
|
|
231
268
|
return undefined;
|
|
232
269
|
}
|
|
233
270
|
if (decision === "reject") {
|
|
234
|
-
const feedback = typeof resp === "string" ? undefined : resp.feedback?.trim();
|
|
235
271
|
return { block: true, reason: feedback ? `${SWARM_REJECT_REASON} ${feedback}` : SWARM_REJECT_REASON };
|
|
236
272
|
}
|
|
237
273
|
return undefined;
|
|
@@ -264,7 +300,7 @@ export async function gateToolCall(toolName, input, cwd, sessionId, options) {
|
|
|
264
300
|
}
|
|
265
301
|
if (ctx.mode !== "manual")
|
|
266
302
|
return undefined;
|
|
267
|
-
if (!
|
|
303
|
+
if (!requiresManualApproval(toolName, input))
|
|
268
304
|
return undefined;
|
|
269
305
|
let action;
|
|
270
306
|
let detail;
|
|
@@ -290,6 +326,10 @@ export async function gateToolCall(toolName, input, cwd, sessionId, options) {
|
|
|
290
326
|
action = "cron";
|
|
291
327
|
detail = sanitizeDetail(input.action);
|
|
292
328
|
}
|
|
329
|
+
else if (toolName === "code_rewrite") {
|
|
330
|
+
action = "code_rewrite";
|
|
331
|
+
detail = sanitizeDetail(input.path ?? input.pattern);
|
|
332
|
+
}
|
|
293
333
|
else {
|
|
294
334
|
// All other mutating tools fall back to the tool name with no extra detail.
|
|
295
335
|
action = toolName;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permissions.js","sourceRoot":"","sources":["../../src/core/permissions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,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,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,aAAa,IAAI,QAAQ,EAAE,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;IAC3F,CAAC;IACD,kCAAgC;IAChC,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["/**\n * lunR: permission modes (Manual / YOLO / Plan / Auto).\n *\n * Per-session only — never persisted per session, but the default mode new\n * sessions start with is configurable in /settings (`defaultPermissionMode`,\n * default \"manual\").\n *\n * - manual: every mutating tool call (bash, edit, write) requires approval.\n * - yolo: auto-approve tools; the agent may still ask questions.\n * - plan: read-only; mutating tools are hard-blocked (planModeBlockReason).\n * - auto: fully autonomous; a system-prompt addendum steers the model to\n * self-decide, and rollback is force-enabled for the session.\n *\n * The gate is wired into `agent-session.ts` `_installAgentToolHooks` before\n * the synchronous `_toolCallGates` loop. beforeToolCall is already async, so\n * awaiting the approval dialog is fine.\n *\n * State (mode + session-scoped approvals) is keyed by session id so\n * concurrent gateway chats do not share permission decisions.\n */\n\nimport { resolve } from \"node:path\";\nimport { planModeBlockReason } from \"./plan-mode.ts\";\nimport { effectiveSwarmCount, SWARM_APPROVAL_THRESHOLD } from \"./swarm.ts\";\n\n/** Shift+Tab cycle order. */\nexport const PERMISSION_MODES = [\"manual\", \"yolo\", \"plan\", \"auto\"] as const;\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\nexport function nextPermissionMode(current: PermissionMode): PermissionMode {\n\tconst i = PERMISSION_MODES.indexOf(current);\n\treturn PERMISSION_MODES[(i + 1) % PERMISSION_MODES.length];\n}\n\n/** True when the (default or session) permission mode is plan. */\nexport function isPlanModeActive(sessionId?: string): boolean {\n\treturn getPermissionMode(sessionId) === \"plan\";\n}\n\n/**\n * Destination mode when leaving plan via approve / `/plan off` / `/plan <text>`.\n * Explicit Shift+Tab or `/mode` picks do not use this — they already chose a mode.\n */\nexport function restorePermissionModeAfterPlan(\n\tprevious: PermissionMode | undefined,\n\tdefaultMode: PermissionMode,\n): PermissionMode {\n\tif (previous && previous !== \"plan\") return previous;\n\treturn defaultMode === \"plan\" ? \"yolo\" : defaultMode;\n}\n\nexport interface ApprovalRequest {\n\ttoolName: string;\n\t/** \"bash\" (detail = command), \"edit\"/\"write\" (detail = path),\n\t * \"edit-outside\"/\"write-outside\" when path escapes cwd,\n\t * \"swarm\" for auto-activated agent swarms (detail = summary lines). */\n\taction: string;\n\tdetail: string;\n\t/** \"swarm\" when this is the agent-swarm approval prompt, \"plan\" for the\n\t * present_plan plan-approval prompt — the UI renders a dedicated dialog\n\t * for each instead of the generic tool dialog. */\n\tkind?: \"swarm\" | \"plan\";\n}\n\nexport type ApprovalDecision = \"once\" | \"session\" | \"reject\";\n/** Handlers may return a bare decision string, a reject carrying user feedback\n * that becomes the block reason the model sees, or an approve carrying optional\n * feedback (plan approval with comments). */\nexport type ApprovalResponse =\n\t| ApprovalDecision\n\t| { decision: \"reject\"; feedback: string }\n\t| { decision: \"approve\"; feedback?: string };\n\n/** Read-only tools that never need approval. */\nconst READ_ONLY_TOOLS = new Set([\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"web_search\",\n\t\"web_fetch\",\n\t\"fetch_content\",\n\t\"get_search_content\",\n\t\"sourcegraph\",\n\t\"repo_map\",\n\t\"symbol_outline\",\n\t\"read_block\",\n\t\"code_overview\",\n\t\"ast_search\",\n\t\"lsp_diagnostics\",\n\t\"lsp_hover\",\n\t\"lsp_definition\",\n\t\"lsp_references\",\n\t\"lsp_symbols\",\n\t\"lsp_code_actions\",\n\t\"lsp_completions\",\n\t\"behavior_load\",\n\t\"memory_load\",\n]);\n\n/** Tools that mutate state and must be gated in manual mode. */\nconst MUTATING_TOOLS = new Set([\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"behavior_add\",\n\t\"behavior_remove\",\n\t\"memory_add\",\n\t\"memory_remove\",\n\t\"cron\",\n]);\n\nconst REJECT_REASON = \"Rejected by user (permission mode: manual).\";\nexport const NO_HANDLER_REASON = \"Mutating tool blocked in manual mode: no approval channel available.\";\nexport const SWARM_REJECT_REASON = \"Agent swarm rejected by user.\";\nexport const NO_SWARM_HANDLER_REASON = \"Agent swarm blocked: no approval channel available.\";\n/** Session-approval key for auto-activated agent swarms. */\nconst SWARM_ACTION = \"swarm\";\n\ninterface PermissionContext {\n\tmode: PermissionMode;\n\tapprovals: Set<string>;\n}\n\nconst contexts = new Map<string, PermissionContext>();\nlet defaultContext: PermissionContext = { mode: \"manual\", approvals: new Set() };\nlet approvalHandler: ((req: ApprovalRequest) => Promise<ApprovalResponse>) | undefined;\n\nfunction getContext(sessionId?: string): PermissionContext {\n\tif (!sessionId) return defaultContext;\n\treturn contexts.get(sessionId) ?? defaultContext;\n}\n\nexport function createPermissionContext(sessionId: string, mode: PermissionMode = defaultContext.mode): void {\n\tcontexts.set(sessionId, { mode, approvals: new Set() });\n}\n\nexport function deletePermissionContext(sessionId: string): void {\n\tcontexts.delete(sessionId);\n}\n\nexport function getPermissionMode(sessionId?: string): PermissionMode {\n\treturn getContext(sessionId).mode;\n}\n\nexport function setPermissionMode(mode: PermissionMode, sessionId?: string): void {\n\tgetContext(sessionId).mode = mode;\n}\n\nexport function resetPermissions(defaultMode: PermissionMode = \"manual\", sessionId?: string): void {\n\tif (sessionId) {\n\t\tcontexts.set(sessionId, { mode: defaultMode, approvals: new Set() });\n\t} else {\n\t\tdefaultContext = { mode: defaultMode, approvals: new Set() };\n\t}\n}\n\nexport function registerApprovalHandler(fn: ((req: ApprovalRequest) => Promise<ApprovalResponse>) | undefined): void {\n\tapprovalHandler = fn;\n}\n\n/** Model-facing result texts for the present_plan tool. */\nexport const PLAN_APPROVED_TEXT = \"Plan approved — implement it now.\";\nexport const PLAN_DECLINED_TEXT = \"Plan declined — revise the plan and call present_plan again.\";\nexport const PLAN_PASS_THROUGH_TEXT = \"Plan presented. The user will review and reply.\";\n\n/** lunr: map an approval response to the model-facing present_plan result text. */\nexport function planApprovalResultText(resp: ApprovalResponse): string {\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\tif (decision === \"reject\") {\n\t\treturn feedback\n\t\t\t? `Plan declined: ${feedback} — revise the plan and call present_plan again.`\n\t\t\t: PLAN_DECLINED_TEXT;\n\t}\n\treturn feedback ? `Plan approved with feedback: ${feedback} — implement it now.` : PLAN_APPROVED_TEXT;\n}\n\n/**\n * lunr: present_plan approval request. Unlike the mutating-tool and swarm gates\n * this fails OPEN when no approval handler is registered (or none is reachable,\n * e.g. a gateway turn without a chat context): headless sessions have no one to\n * show the dialog to, so the plan is presented and the user replies in chat\n * instead of deadlocking the turn. Everything else keeps fail-closed.\n */\nexport async function requestPlanApproval(summary: string): Promise<string> {\n\tif (!approvalHandler) return PLAN_PASS_THROUGH_TEXT;\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({ toolName: \"present_plan\", action: \"plan\", detail: summary, kind: \"plan\" });\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : \"approval request failed\";\n\t\tif (message === NO_HANDLER_REASON) return PLAN_PASS_THROUGH_TEXT;\n\t\treturn `Plan declined: ${message} — revise the plan and call present_plan again.`;\n\t}\n\treturn planApprovalResultText(resp);\n}\n\nexport function clearSessionApprovals(sessionId?: string): void {\n\tgetContext(sessionId).approvals.clear();\n}\n\n/** Test seam: remove every per-session context and restore the default. */\nexport function resetAllPermissionContexts(): void {\n\tcontexts.clear();\n\tdefaultContext = { mode: \"manual\", approvals: new Set() };\n\tapprovalHandler = undefined;\n}\n\n/** Appended to the system prompt while auto mode is active. */\nexport const AUTO_MODE_ADDENDUM =\n\t\"You are running fully autonomously. Do not ask the user questions or wait for confirmation; make reasonable decisions and complete the task end-to-end.\";\n\nfunction isPathOutsideCwd(absPath: string, cwd: string): boolean {\n\tconst norm = (p: string) => p.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n\tconst np = norm(absPath);\n\tconst nc = norm(cwd);\n\tif (np === nc) return false;\n\treturn !np.startsWith(`${nc}/`);\n}\n\nfunction resolvePath(cwd: string, p: unknown): string {\n\tif (typeof p !== \"string\") return \"\";\n\tif (!p) return \"\";\n\treturn resolve(cwd, p);\n}\n\nfunction isMutatingTool(toolName: string): boolean {\n\treturn MUTATING_TOOLS.has(toolName);\n}\n\nexport interface GateOptions {\n\t/** True when the current turn started from an explicit /swarm prompt — the\n\t * user already asked for the swarm, so the swarm approval gate is skipped. */\n\texplicitSwarmTurn?: boolean;\n}\n\n/** First task text of a parallel fan-out, used as the dialog summary line. */\nfunction swarmTaskSummary(input: Record<string, unknown>): string {\n\tif (!Array.isArray(input.tasks)) return \"\";\n\tfor (const task of input.tasks) {\n\t\tconst text = task && typeof task === \"object\" ? (task as { task?: unknown }).task : undefined;\n\t\tif (typeof text === \"string\" && text.trim()) return sanitizeDetail(text);\n\t}\n\treturn \"\";\n}\n\n/**\n * Agent-swarm gate. An auto-activated swarm (one `subagent` call launching more\n * than SWARM_APPROVAL_THRESHOLD parallel subagents) requires user approval in\n * manual AND yolo modes; auto mode runs it unconditionally and explicit /swarm\n * turns are pre-approved. Fail-closed without an approval handler, same as the\n * mutating-tool gate.\n */\nasync function gateSwarmCall(\n\tinput: Record<string, unknown>,\n\tctx: PermissionContext,\n\toptions?: GateOptions,\n): Promise<{ block: true; reason: string } | undefined> {\n\tif (ctx.mode === \"auto\") return undefined;\n\tif (options?.explicitSwarmTurn) return undefined;\n\tconst count = effectiveSwarmCount(input);\n\tif (count <= SWARM_APPROVAL_THRESHOLD) return undefined;\n\tif (ctx.approvals.has(SWARM_ACTION)) return undefined;\n\n\tif (!approvalHandler) {\n\t\treturn { block: true, reason: NO_SWARM_HANDLER_REASON };\n\t}\n\n\tconst summary = swarmTaskSummary(input);\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({\n\t\t\ttoolName: \"subagent\",\n\t\t\taction: SWARM_ACTION,\n\t\t\tdetail: summary ? `agent swarm (${count} subagents)\\n${summary}` : `agent swarm (${count} subagents)`,\n\t\t\tkind: \"swarm\",\n\t\t});\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : NO_SWARM_HANDLER_REASON;\n\t\treturn { block: true, reason: message };\n\t}\n\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tif (decision === \"session\") {\n\t\tctx.approvals.add(SWARM_ACTION);\n\t\treturn undefined;\n\t}\n\tif (decision === \"reject\") {\n\t\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\t\treturn { block: true, reason: feedback ? `${SWARM_REJECT_REASON} ${feedback}` : SWARM_REJECT_REASON };\n\t}\n\treturn undefined;\n}\n\nfunction sanitizeDetail(value: unknown): string {\n\tconst text = String(value ?? \"\").trim();\n\treturn text.length > 200 ? `${text.slice(0, 200)}…` : text;\n}\n\n/**\n * Returns a block result when the tool call should be blocked, else undefined.\n * Read-only tools always pass. YOLO and Auto always pass mutating tools. Plan\n * mode hard-blocks mutating tools (no prompt). Manual mode gates every mutating\n * tool; if an approval handler is registered it is asked, otherwise the call is\n * blocked (fail-closed — no silent allow).\n */\nexport async function gateToolCall(\n\ttoolName: string,\n\tinput: Record<string, unknown>,\n\tcwd: string,\n\tsessionId?: string,\n\toptions?: GateOptions,\n): Promise<{ block: true; reason: string } | undefined> {\n\tconst ctx = getContext(sessionId);\n\tif (READ_ONLY_TOOLS.has(toolName)) return undefined;\n\n\t// lunr: agent-swarm gate runs before the mode early-return — it applies in\n\t// yolo mode too (only auto mode bypasses it).\n\tif (toolName === \"subagent\") {\n\t\tconst swarmBlock = await gateSwarmCall(input, ctx, options);\n\t\tif (swarmBlock) return swarmBlock;\n\t}\n\n\tif (ctx.mode === \"plan\") {\n\t\tconst reason = planModeBlockReason(toolName, input);\n\t\treturn reason ? { block: true, reason } : undefined;\n\t}\n\n\tif (ctx.mode !== \"manual\") return undefined;\n\tif (!isMutatingTool(toolName)) return undefined;\n\n\tlet action: string;\n\tlet detail: string;\n\n\tif (toolName === \"bash\") {\n\t\taction = \"bash\";\n\t\tdetail = sanitizeDetail(input.command);\n\t} else if (toolName === \"edit\" || toolName === \"write\") {\n\t\tconst path = resolvePath(cwd, input.path);\n\t\tconst outside = path ? isPathOutsideCwd(path, cwd) : false;\n\t\taction = outside ? `${toolName}-outside` : toolName;\n\t\tdetail = path || String(input.path ?? \"\");\n\t} else if (toolName === \"behavior_add\" || toolName === \"memory_add\") {\n\t\taction = toolName;\n\t\tdetail = sanitizeDetail(input.content);\n\t} else if (toolName === \"behavior_remove\" || toolName === \"memory_remove\") {\n\t\taction = toolName;\n\t\tdetail = sanitizeDetail(input.line);\n\t} else if (toolName === \"cron\") {\n\t\taction = \"cron\";\n\t\tdetail = sanitizeDetail(input.action);\n\t} else {\n\t\t// All other mutating tools fall back to the tool name with no extra detail.\n\t\taction = toolName;\n\t\tdetail = \"\";\n\t}\n\n\tif (ctx.approvals.has(action)) return undefined;\n\n\tif (!approvalHandler) {\n\t\treturn { block: true, reason: NO_HANDLER_REASON };\n\t}\n\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({ toolName, action, detail });\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : NO_HANDLER_REASON;\n\t\treturn { block: true, reason: message };\n\t}\n\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tif (decision === \"session\") {\n\t\tctx.approvals.add(action);\n\t\treturn undefined;\n\t}\n\tif (decision === \"reject\") {\n\t\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\t\treturn { block: true, reason: feedback ? `${REJECT_REASON} ${feedback}` : REJECT_REASON };\n\t}\n\t// \"once\" — allow this call only\n\treturn undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"permissions.js","sourceRoot":"","sources":["../../src/core/permissions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW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AE,IAAI,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC;IACnD,CAAC;IAED,IAAI,IAAsB,CAAC;IAC3B,IAAI,CAAC;QACJ,IAAI,GAAG,MAAM,eAAe,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAC5D,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,iBAAiB,CAAC;QACvE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;IACzC,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC;IACjE,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5B,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC1B,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,QAAQ,KAAK,QAAQ,EAAE,CAAC;QAC3B,MAAM,QAAQ,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC;QAC9E,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,aAAa,IAAI,QAAQ,EAAE,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;IAC3F,CAAC;IACD,kCAAgC;IAChC,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["/**\n * lunR: permission modes (Manual / YOLO / Plan / Auto).\n *\n * Per-session only — never persisted per session, but the default mode new\n * sessions start with is configurable in /settings (`defaultPermissionMode`,\n * default \"manual\").\n *\n * - manual: every mutating tool call (bash, edit, write) requires approval.\n * - yolo: auto-approve tools; the agent may still ask questions.\n * - plan: read-only; mutating tools are hard-blocked (planModeBlockReason).\n * - auto: fully autonomous; a system-prompt addendum steers the model to\n * self-decide, and rollback is force-enabled for the session.\n *\n * The gate is wired into `agent-session.ts` `_installAgentToolHooks` before\n * the synchronous `_toolCallGates` loop. beforeToolCall is already async, so\n * awaiting the approval dialog is fine.\n *\n * State (mode + session-scoped approvals) is keyed by session id so\n * concurrent gateway chats do not share permission decisions.\n */\n\nimport { resolve } from \"node:path\";\nimport { isCodeRewriteMutating, planModeBlockReason } from \"./plan-mode.ts\";\nimport { effectiveSwarmCountForTurn, SWARM_APPROVAL_THRESHOLD } from \"./swarm.ts\";\n\n/** Shift+Tab cycle order. */\nexport const PERMISSION_MODES = [\"manual\", \"yolo\", \"plan\", \"auto\"] as const;\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\nexport function nextPermissionMode(current: PermissionMode): PermissionMode {\n\tconst i = PERMISSION_MODES.indexOf(current);\n\treturn PERMISSION_MODES[(i + 1) % PERMISSION_MODES.length];\n}\n\n/** True when the (default or session) permission mode is plan. */\nexport function isPlanModeActive(sessionId?: string): boolean {\n\treturn getPermissionMode(sessionId) === \"plan\";\n}\n\n/**\n * Destination mode when leaving plan via approve / `/plan off` / `/plan <text>`.\n * Explicit Shift+Tab or `/mode` picks do not use this — they already chose a mode.\n */\nexport function restorePermissionModeAfterPlan(\n\tprevious: PermissionMode | undefined,\n\tdefaultMode: PermissionMode,\n): PermissionMode {\n\tif (previous && previous !== \"plan\") return previous;\n\treturn defaultMode === \"plan\" ? \"yolo\" : defaultMode;\n}\n\nexport interface ApprovalRequest {\n\ttoolName: string;\n\t/** \"bash\" (detail = command), \"edit\"/\"write\" (detail = path),\n\t * \"edit-outside\"/\"write-outside\" when path escapes cwd,\n\t * \"swarm\" for auto-activated agent swarms (detail = summary lines). */\n\taction: string;\n\tdetail: string;\n\t/** \"swarm\" when this is the agent-swarm approval prompt, \"plan\" for the\n\t * present_plan plan-approval prompt — the UI renders a dedicated dialog\n\t * for each instead of the generic tool dialog. */\n\tkind?: \"swarm\" | \"plan\";\n}\n\nexport type ApprovalDecision = \"once\" | \"session\" | \"reject\";\n/** Handlers may return a bare decision string, a reject carrying user feedback\n * that becomes the block reason the model sees, or an approve carrying optional\n * feedback (plan approval with comments). */\nexport type ApprovalResponse =\n\t| ApprovalDecision\n\t| { decision: \"reject\"; feedback: string }\n\t| { decision: \"approve\"; feedback?: string };\n\n/** Read-only tools that never need approval. */\nconst READ_ONLY_TOOLS = new Set([\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"web_search\",\n\t\"web_fetch\",\n\t\"fetch_content\",\n\t\"get_search_content\",\n\t\"sourcegraph\",\n\t\"repo_map\",\n\t\"symbol_outline\",\n\t\"read_block\",\n\t\"code_overview\",\n\t\"ast_search\",\n\t\"lsp_diagnostics\",\n\t\"lsp_hover\",\n\t\"lsp_definition\",\n\t\"lsp_references\",\n\t\"lsp_symbols\",\n\t\"lsp_code_actions\",\n\t\"lsp_completions\",\n\t\"behavior_load\",\n\t\"memory_load\",\n]);\n\n/** Tools that mutate state and must be gated in manual mode. */\nconst MUTATING_TOOLS = new Set([\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"behavior_add\",\n\t\"behavior_remove\",\n\t\"memory_add\",\n\t\"memory_remove\",\n\t\"cron\",\n]);\n\nconst REJECT_REASON = \"Rejected by user (permission mode: manual).\";\nexport const NO_HANDLER_REASON = \"Mutating tool blocked in manual mode: no approval channel available.\";\nexport const SWARM_REJECT_REASON = \"Agent swarm rejected by user.\";\nexport const NO_SWARM_HANDLER_REASON = \"Agent swarm blocked: no approval channel available.\";\n/** Session-approval key for auto-activated agent swarms. */\nconst SWARM_ACTION = \"swarm\";\n\ninterface PermissionContext {\n\tmode: PermissionMode;\n\tapprovals: Set<string>;\n}\n\nconst contexts = new Map<string, PermissionContext>();\nlet defaultContext: PermissionContext = { mode: \"manual\", approvals: new Set() };\nlet approvalHandler: ((req: ApprovalRequest) => Promise<ApprovalResponse>) | undefined;\n/** One swarm prompt covers every sibling SINGLE `subagent` on the same assistant message. */\nconst turnSwarmDecisions = new WeakMap<object, { decision: ApprovalDecision; feedback?: string }>();\n\nfunction getContext(sessionId?: string): PermissionContext {\n\tif (!sessionId) return defaultContext;\n\treturn contexts.get(sessionId) ?? defaultContext;\n}\n\nexport function createPermissionContext(sessionId: string, mode: PermissionMode = defaultContext.mode): void {\n\tcontexts.set(sessionId, { mode, approvals: new Set() });\n}\n\nexport function deletePermissionContext(sessionId: string): void {\n\tcontexts.delete(sessionId);\n}\n\nexport function getPermissionMode(sessionId?: string): PermissionMode {\n\treturn getContext(sessionId).mode;\n}\n\nexport function setPermissionMode(mode: PermissionMode, sessionId?: string): void {\n\tgetContext(sessionId).mode = mode;\n}\n\nexport function resetPermissions(defaultMode: PermissionMode = \"manual\", sessionId?: string): void {\n\tif (sessionId) {\n\t\tcontexts.set(sessionId, { mode: defaultMode, approvals: new Set() });\n\t} else {\n\t\tdefaultContext = { mode: defaultMode, approvals: new Set() };\n\t}\n}\n\nexport function registerApprovalHandler(fn: ((req: ApprovalRequest) => Promise<ApprovalResponse>) | undefined): void {\n\tapprovalHandler = fn;\n}\n\n/** Model-facing result texts for the present_plan tool. */\nexport const PLAN_APPROVED_TEXT = \"Plan approved — implement it now.\";\nexport const PLAN_DECLINED_TEXT = \"Plan declined — revise the plan and call present_plan again.\";\nexport const PLAN_PASS_THROUGH_TEXT = \"Plan presented. The user will review and reply.\";\n\n/** lunr: map an approval response to the model-facing present_plan result text. */\nexport function planApprovalResultText(resp: ApprovalResponse): string {\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\tif (decision === \"reject\") {\n\t\treturn feedback\n\t\t\t? `Plan declined: ${feedback} — revise the plan and call present_plan again.`\n\t\t\t: PLAN_DECLINED_TEXT;\n\t}\n\treturn feedback ? `Plan approved with feedback: ${feedback} — implement it now.` : PLAN_APPROVED_TEXT;\n}\n\n/**\n * lunr: present_plan approval request. Unlike the mutating-tool and swarm gates\n * this fails OPEN when no approval handler is registered (or none is reachable,\n * e.g. a gateway turn without a chat context): headless sessions have no one to\n * show the dialog to, so the plan is presented and the user replies in chat\n * instead of deadlocking the turn. Everything else keeps fail-closed.\n */\nexport async function requestPlanApproval(summary: string): Promise<string> {\n\tif (!approvalHandler) return PLAN_PASS_THROUGH_TEXT;\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({ toolName: \"present_plan\", action: \"plan\", detail: summary, kind: \"plan\" });\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : \"approval request failed\";\n\t\tif (message === NO_HANDLER_REASON) return PLAN_PASS_THROUGH_TEXT;\n\t\treturn `Plan declined: ${message} — revise the plan and call present_plan again.`;\n\t}\n\treturn planApprovalResultText(resp);\n}\n\nexport function clearSessionApprovals(sessionId?: string): void {\n\tgetContext(sessionId).approvals.clear();\n}\n\n/** Test seam: remove every per-session context and restore the default. */\nexport function resetAllPermissionContexts(): void {\n\tcontexts.clear();\n\tdefaultContext = { mode: \"manual\", approvals: new Set() };\n\tapprovalHandler = undefined;\n}\n\n/** Appended to the system prompt while auto mode is active. */\nexport const AUTO_MODE_ADDENDUM =\n\t\"You are running fully autonomously. Do not ask the user questions or wait for confirmation; make reasonable decisions and complete the task end-to-end.\";\n\nfunction isPathOutsideCwd(absPath: string, cwd: string): boolean {\n\tconst norm = (p: string) => p.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n\tconst np = norm(absPath);\n\tconst nc = norm(cwd);\n\tif (np === nc) return false;\n\treturn !np.startsWith(`${nc}/`);\n}\n\nfunction resolvePath(cwd: string, p: unknown): string {\n\tif (typeof p !== \"string\") return \"\";\n\tif (!p) return \"\";\n\treturn resolve(cwd, p);\n}\n\nfunction isMutatingTool(toolName: string): boolean {\n\treturn MUTATING_TOOLS.has(toolName);\n}\n\nfunction requiresManualApproval(toolName: string, input: Record<string, unknown>): boolean {\n\tif (isMutatingTool(toolName)) return true;\n\treturn toolName === \"code_rewrite\" && isCodeRewriteMutating(input);\n}\n\nexport interface GateOptions {\n\t/** True when the current turn started from an explicit /swarm prompt — the\n\t * user already asked for the swarm, so the swarm approval gate is skipped. */\n\texplicitSwarmTurn?: boolean;\n\t/** Assistant message that issued this tool call. Same-turn sibling SINGLE\n\t * `subagent` calls count toward the swarm threshold. */\n\tassistantMessage?: {\n\t\tcontent?: ReadonlyArray<{ type?: string; name?: string; arguments?: unknown }>;\n\t};\n}\n\nfunction firstTaskText(value: unknown): string {\n\tif (typeof value === \"string\" && value.trim()) return sanitizeDetail(value);\n\treturn \"\";\n}\n\n/** First task text of a parallel fan-out or sibling SINGLE, used as the dialog summary. */\nfunction swarmTaskSummary(input: Record<string, unknown>, assistantMessage?: GateOptions[\"assistantMessage\"]): string {\n\tif (Array.isArray(input.tasks)) {\n\t\tfor (const task of input.tasks) {\n\t\t\tconst text = task && typeof task === \"object\" ? firstTaskText((task as { task?: unknown }).task) : \"\";\n\t\t\tif (text) return text;\n\t\t}\n\t}\n\tconst own = firstTaskText(input.task);\n\tif (own) return own;\n\tfor (const block of assistantMessage?.content ?? []) {\n\t\tif (block.type !== \"toolCall\" || block.name !== \"subagent\") continue;\n\t\tconst args =\n\t\t\tblock.arguments && typeof block.arguments === \"object\" && !Array.isArray(block.arguments)\n\t\t\t\t? (block.arguments as Record<string, unknown>)\n\t\t\t\t: undefined;\n\t\tconst text = firstTaskText(args?.task);\n\t\tif (text) return text;\n\t}\n\treturn \"\";\n}\n\n/**\n * Agent-swarm gate. An auto-activated swarm (more than SWARM_APPROVAL_THRESHOLD\n * parallel subagents in one `tasks`/`chain.parallel` call, or that many same-turn\n * SINGLE `subagent` calls) requires user approval in manual AND yolo modes; auto\n * mode runs it unconditionally and explicit /swarm turns are pre-approved.\n * Fail-closed without an approval handler, same as the mutating-tool gate.\n */\nasync function gateSwarmCall(\n\tinput: Record<string, unknown>,\n\tctx: PermissionContext,\n\toptions?: GateOptions,\n): Promise<{ block: true; reason: string } | undefined> {\n\tif (ctx.mode === \"auto\") return undefined;\n\tif (options?.explicitSwarmTurn) return undefined;\n\tconst count = effectiveSwarmCountForTurn(input, options?.assistantMessage);\n\tif (count <= SWARM_APPROVAL_THRESHOLD) return undefined;\n\tif (ctx.approvals.has(SWARM_ACTION)) return undefined;\n\n\tconst turnKey = options?.assistantMessage;\n\tconst cached = turnKey ? turnSwarmDecisions.get(turnKey) : undefined;\n\tif (cached) {\n\t\tif (cached.decision === \"reject\") {\n\t\t\treturn { block: true, reason: cached.feedback ? `${SWARM_REJECT_REASON} ${cached.feedback}` : SWARM_REJECT_REASON };\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tif (!approvalHandler) {\n\t\treturn { block: true, reason: NO_SWARM_HANDLER_REASON };\n\t}\n\n\tconst summary = swarmTaskSummary(input, options?.assistantMessage);\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({\n\t\t\ttoolName: \"subagent\",\n\t\t\taction: SWARM_ACTION,\n\t\t\tdetail: summary ? `agent swarm (${count} subagents)\\n${summary}` : `agent swarm (${count} subagents)`,\n\t\t\tkind: \"swarm\",\n\t\t});\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : NO_SWARM_HANDLER_REASON;\n\t\treturn { block: true, reason: message };\n\t}\n\n\tconst rawDecision = typeof resp === \"string\" ? resp : resp.decision;\n\tconst decision: ApprovalDecision = rawDecision === \"approve\" ? \"once\" : rawDecision;\n\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\tif (turnKey) turnSwarmDecisions.set(turnKey, { decision, ...(feedback ? { feedback } : {}) });\n\tif (decision === \"session\") {\n\t\tctx.approvals.add(SWARM_ACTION);\n\t\treturn undefined;\n\t}\n\tif (decision === \"reject\") {\n\t\treturn { block: true, reason: feedback ? `${SWARM_REJECT_REASON} ${feedback}` : SWARM_REJECT_REASON };\n\t}\n\treturn undefined;\n}\n\nfunction sanitizeDetail(value: unknown): string {\n\tconst text = String(value ?? \"\").trim();\n\treturn text.length > 200 ? `${text.slice(0, 200)}…` : text;\n}\n\n/**\n * Returns a block result when the tool call should be blocked, else undefined.\n * Read-only tools always pass. YOLO and Auto always pass mutating tools. Plan\n * mode hard-blocks mutating tools (no prompt). Manual mode gates every mutating\n * tool; if an approval handler is registered it is asked, otherwise the call is\n * blocked (fail-closed — no silent allow).\n */\nexport async function gateToolCall(\n\ttoolName: string,\n\tinput: Record<string, unknown>,\n\tcwd: string,\n\tsessionId?: string,\n\toptions?: GateOptions,\n): Promise<{ block: true; reason: string } | undefined> {\n\tconst ctx = getContext(sessionId);\n\tif (READ_ONLY_TOOLS.has(toolName)) return undefined;\n\n\t// lunr: agent-swarm gate runs before the mode early-return — it applies in\n\t// yolo mode too (only auto mode bypasses it).\n\tif (toolName === \"subagent\") {\n\t\tconst swarmBlock = await gateSwarmCall(input, ctx, options);\n\t\tif (swarmBlock) return swarmBlock;\n\t}\n\n\tif (ctx.mode === \"plan\") {\n\t\tconst reason = planModeBlockReason(toolName, input);\n\t\treturn reason ? { block: true, reason } : undefined;\n\t}\n\n\tif (ctx.mode !== \"manual\") return undefined;\n\tif (!requiresManualApproval(toolName, input)) return undefined;\n\n\tlet action: string;\n\tlet detail: string;\n\n\tif (toolName === \"bash\") {\n\t\taction = \"bash\";\n\t\tdetail = sanitizeDetail(input.command);\n\t} else if (toolName === \"edit\" || toolName === \"write\") {\n\t\tconst path = resolvePath(cwd, input.path);\n\t\tconst outside = path ? isPathOutsideCwd(path, cwd) : false;\n\t\taction = outside ? `${toolName}-outside` : toolName;\n\t\tdetail = path || String(input.path ?? \"\");\n\t} else if (toolName === \"behavior_add\" || toolName === \"memory_add\") {\n\t\taction = toolName;\n\t\tdetail = sanitizeDetail(input.content);\n\t} else if (toolName === \"behavior_remove\" || toolName === \"memory_remove\") {\n\t\taction = toolName;\n\t\tdetail = sanitizeDetail(input.line);\n\t} else if (toolName === \"cron\") {\n\t\taction = \"cron\";\n\t\tdetail = sanitizeDetail(input.action);\n\t} else if (toolName === \"code_rewrite\") {\n\t\taction = \"code_rewrite\";\n\t\tdetail = sanitizeDetail(input.path ?? input.pattern);\n\t} else {\n\t\t// All other mutating tools fall back to the tool name with no extra detail.\n\t\taction = toolName;\n\t\tdetail = \"\";\n\t}\n\n\tif (ctx.approvals.has(action)) return undefined;\n\n\tif (!approvalHandler) {\n\t\treturn { block: true, reason: NO_HANDLER_REASON };\n\t}\n\n\tlet resp: ApprovalResponse;\n\ttry {\n\t\tresp = await approvalHandler({ toolName, action, detail });\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : NO_HANDLER_REASON;\n\t\treturn { block: true, reason: message };\n\t}\n\n\tconst decision = typeof resp === \"string\" ? resp : resp.decision;\n\tif (decision === \"session\") {\n\t\tctx.approvals.add(action);\n\t\treturn undefined;\n\t}\n\tif (decision === \"reject\") {\n\t\tconst feedback = typeof resp === \"string\" ? undefined : resp.feedback?.trim();\n\t\treturn { block: true, reason: feedback ? `${REJECT_REASON} ${feedback}` : REJECT_REASON };\n\t}\n\t// \"once\" — allow this call only\n\treturn undefined;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan-mode.d.ts","sourceRoot":"","sources":["../../src/core/plan-mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,+DAA+D;AAC/D,eAAO,MAAM,kBAAkB,+RACyP,CAAC;AAEzR,4EAA4E;AAC5E,eAAO,MAAM,uBAAuB,gEAA2D,CAAC;AAgJhG,yFAAyF;AACzF,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAE7D;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAcxF;AAOD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAe9D","sourcesContent":["/**\n * lunr: plan permission mode — read-only tool-gating heuristics + system-prompt addendum.\n *\n * Plan is a first-class permission mode (`PermissionMode = \"plan\"`). `gateToolCall`\n * in permissions.ts applies `planModeBlockReason` when the session is in plan:\n * `edit`/`write` and mutating `bash` are hard-blocked; read tools stay open.\n * InteractiveMode installs `PLAN_MODE_ADDENDUM` via the shared system-prompt\n * append slot (same slot auto mode uses).\n *\n * Bash heuristic (conservative, blocklist-based — NOT a security boundary):\n * - any `>`/`>>` redirect outside quotes blocks the whole command;\n * - the command is split on `;`, `|`, `&` separators (outside quotes) and every segment's\n * leading command must be read-only:\n * - known mutating commands (rm, mv, cp, mkdir, sed -i, tee, …) are blocked;\n * - `git` is limited to read-only subcommands (status/log/diff/show/… plus flag-only\n * branch/tag/remote); mutating subcommands (add/commit/push/checkout/…) are blocked;\n * - package managers are limited to read-only subcommands (install/add/remove/… blocked);\n * - arbitrary runners (sudo, xargs, npx, sh -c …) are blocked.\n * Unknown-but-not-listed commands are ALLOWED (blocklist, not allowlist) — the model is\n * additionally steered by the system-prompt addendum. False positives are expected; the\n * user can run the command themselves or exit plan mode with /plan off.\n */\n\n/** Appended to the system prompt while plan mode is active. */\nexport const PLAN_MODE_ADDENDUM =\n\t\"You are in plan mode. Investigate read-only, then present your plan by calling the present_plan tool with a concise summary — the user approves or declines it in a dialog. Do not make changes until the plan is approved. The user can also exit plan mode manually with /plan off.\";\n\n/** Error returned to the model when a tool call is blocked by plan mode. */\nexport const PLAN_MODE_BLOCK_MESSAGE = \"Plan mode is active — propose a plan; no file changes.\";\n\nconst BLOCKED_TOOLS = new Set([\n\t\"edit\",\n\t\"write\",\n\t\"behavior_add\",\n\t\"behavior_remove\",\n\t\"memory_add\",\n\t\"memory_remove\",\n\t\"cron\",\n]);\n\n/** Small allowlist of read-only commands permitted in plan mode. Everything else is rejected. */\nconst ALLOWED_COMMANDS = new Set([\n\t\"ls\",\n\t\"ll\",\n\t\"cat\",\n\t\"tac\",\n\t\"grep\",\n\t\"rg\",\n\t\"find\",\n\t\"pwd\",\n\t\"echo\",\n\t\"printf\",\n\t\"head\",\n\t\"tail\",\n\t\"wc\",\n\t\"less\",\n\t\"more\",\n\t\"sort\",\n\t\"uniq\",\n\t\"diff\",\n\t\"cmp\",\n\t\"comm\",\n\t\"test\",\n\t\"[\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"whereis\",\n\t\"stat\",\n\t\"file\",\n\t\"id\",\n\t\"whoami\",\n\t\"who\",\n\t\"date\",\n\t\"cal\",\n\t\"env\",\n\t\"printenv\",\n\t\"uname\",\n\t\"hostname\",\n\t\"uptime\",\n\t\"nproc\",\n\t\"tput\",\n\t\"git\",\n\t\"gh\",\n\t\"node\",\n\t\"npm\",\n\t\"pnpm\",\n\t\"yarn\",\n\t\"bun\",\n]);\n\nconst MUTATING_GIT_SUBCOMMANDS = new Set([\n\t\"add\",\n\t\"commit\",\n\t\"push\",\n\t\"pull\",\n\t\"merge\",\n\t\"rebase\",\n\t\"reset\",\n\t\"checkout\",\n\t\"switch\",\n\t\"restore\",\n\t\"rm\",\n\t\"mv\",\n\t\"stash\",\n\t\"cherry-pick\",\n\t\"revert\",\n\t\"clean\",\n\t\"fetch\",\n\t\"config\",\n\t\"apply\",\n\t\"am\",\n\t\"init\",\n\t\"clone\",\n\t\"submodule\",\n\t\"worktree\",\n\t\"gc\",\n\t\"prune\",\n\t\"update-index\",\n]);\n\n// git subcommands that are read-only only when they carry no positional args or\n// mutating flags (`git branch` lists, `git branch foo` / `git branch -d foo` mutate).\nconst CONDITIONAL_GIT_SUBCOMMANDS = new Set([\"branch\", \"tag\", \"remote\"]);\nconst CONDITIONAL_GIT_MUTATING_FLAGS = new Set([\"-d\", \"-D\", \"-m\", \"-M\", \"-c\", \"-C\"]);\n\nconst PACKAGE_MANAGER_MUTATIONS: Record<string, Set<string>> = {\n\tnpm: new Set([\n\t\t\"install\",\n\t\t\"add\",\n\t\t\"remove\",\n\t\t\"uninstall\",\n\t\t\"update\",\n\t\t\"upgrade\",\n\t\t\"publish\",\n\t\t\"link\",\n\t\t\"unlink\",\n\t\t\"ci\",\n\t\t\"init\",\n\t]),\n\tpnpm: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"update\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n\tyarn: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n\tbun: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"update\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n};\n\n// Almost every subcommand mutates the system.\nconst ALWAYS_MUTATING_MANAGERS = new Set([\n\t\"apt\",\n\t\"apt-get\",\n\t\"brew\",\n\t\"dnf\",\n\t\"yum\",\n\t\"pacman\",\n\t\"choco\",\n\t\"winget\",\n\t\"scoop\",\n]);\n\n/** Flags that cause an interpreter to execute code and are never allowed in plan mode. */\nconst EXECUTING_NODE_FLAGS = new Set([\n\t\"-e\",\n\t\"--eval\",\n\t\"-p\",\n\t\"--print\",\n\t\"-r\",\n\t\"--require\",\n\t\"--import\",\n\t\"-i\",\n\t\"--interactive\",\n]);\nconst EXECUTING_PYTHON_FLAGS = new Set([\"-c\", \"-m\", \"-i\", \"--interactive\"]);\n\n/** Apply-mode rewrite only. Default / omitted `dry_run` is preview and stays allowed. */\nexport function isCodeRewriteMutating(input: unknown): boolean {\n\treturn (input as { dry_run?: unknown } | undefined)?.dry_run === false;\n}\n\n/**\n * Returns the block reason when plan mode should block this tool call, else undefined.\n */\nexport function planModeBlockReason(toolName: string, input: unknown): string | undefined {\n\tif (BLOCKED_TOOLS.has(toolName)) {\n\t\treturn PLAN_MODE_BLOCK_MESSAGE;\n\t}\n\tif (toolName === \"code_rewrite\" && isCodeRewriteMutating(input)) {\n\t\treturn PLAN_MODE_BLOCK_MESSAGE;\n\t}\n\tif (toolName === \"bash\") {\n\t\tconst command = readBashCommand(input);\n\t\tif (command && isMutatingBashCommand(command)) {\n\t\t\treturn `${PLAN_MODE_BLOCK_MESSAGE} Blocked command: ${command}`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction readBashCommand(input: unknown): string {\n\tconst command = (input as { command?: unknown } | undefined)?.command;\n\treturn typeof command === \"string\" ? command : \"\";\n}\n\n/**\n * Plan-mode bash allowlist. A command is mutating unless every segment is a\n * known read-only command used safely (no redirects, no command substitution,\n * no process substitution, no executing-interpreter flags).\n */\nexport function isMutatingBashCommand(command: string): boolean {\n\tif (!command.trim()) return false;\n\n\t// Any output redirect outside quotes can write a file.\n\tif (hasUnquotedRedirect(command)) return true;\n\n\t// Command substitution / process substitution / grouped redirect syntaxes\n\t// bypass a simple command-name check.\n\tif (hasShellSubstitution(command)) return true;\n\n\t// Every segment separated by ; | & && || must individually be read-only.\n\tfor (const segment of splitShellSegments(command)) {\n\t\tif (isMutatingSegment(segment)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasUnquotedRedirect(command: string): boolean {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \">\") return true;\n\t}\n\treturn false;\n}\n\nfunction splitShellSegments(command: string): string[] {\n\tconst segments: string[] = [];\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tlet start = 0;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\t// Combined operators && and || split as one boundary.\n\t\tif ((ch === \"&\" && next === \"&\") || (ch === \"|\" && next === \"|\")) {\n\t\t\tsegments.push(command.slice(start, i));\n\t\t\ti++;\n\t\t\tstart = i + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\" || ch === \"\\n\") {\n\t\t\tsegments.push(command.slice(start, i));\n\t\t\tstart = i + 1;\n\t\t}\n\t}\n\tsegments.push(command.slice(start));\n\treturn segments.map((s) => s.trim()).filter((s) => s.length > 0);\n}\n\n/** True when the command contains command/process substitution outside quotes. */\nfunction hasShellSubstitution(command: string): boolean {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"`\") return true;\n\t\tif (ch === \"$\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \"<\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \">\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \"&\" && command[i + 1] === \">\") return true;\n\t}\n\treturn false;\n}\n\nfunction isMutatingSegment(segment: string): boolean {\n\tlet tokens = segment.split(/\\s+/).filter((t) => t.length > 0);\n\t// Skip leading env assignments (FOO=bar cmd …) and command wrappers we can't see through.\n\twhile (tokens.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) {\n\t\ttokens = tokens.slice(1);\n\t}\n\tif (tokens.length === 0) return false;\n\n\tconst command = basenameOf(tokens[0]).toLowerCase();\n\tconst args = tokens.slice(1);\n\n\tif (ALWAYS_MUTATING_MANAGERS.has(command)) return true;\n\n\tif (command === \"sed\") {\n\t\treturn args.some((a) => a === \"-i\" || a.startsWith(\"-i\") || a.startsWith(\"--in-place\") || /^-[^-]*i/.test(a));\n\t}\n\tif (command === \"find\") {\n\t\treturn args.some((a) => [\"-delete\", \"-exec\", \"-execdir\", \"-ok\", \"-okdir\"].includes(a));\n\t}\n\tif (command === \"git\") {\n\t\treturn isMutatingGit(args);\n\t}\n\tif (command === \"gh\") {\n\t\t// Allow read-only views; block everything that changes remote state.\n\t\tconst sub = `${args[0] ?? \"\"} ${args[1] ?? \"\"}`;\n\t\treturn ![\n\t\t\t\"pr view\",\n\t\t\t\"pr list\",\n\t\t\t\"pr status\",\n\t\t\t\"issue view\",\n\t\t\t\"issue list\",\n\t\t\t\"issue status\",\n\t\t\t\"repo view\",\n\t\t\t\"release view\",\n\t\t\t\"release list\",\n\t\t\t\"run list\",\n\t\t\t\"run view\",\n\t\t\t\"status\",\n\t\t].includes(sub.trim());\n\t}\n\tif (command === \"sh\" || command === \"bash\" || command === \"zsh\" || command === \"dash\") {\n\t\t// `sh -c '…'` runs arbitrary code; bare `sh script` also executes. Block -c; allow\n\t\t// nothing else is too restrictive for `bash --version`, so allow flag-only invocations.\n\t\treturn args.some((a) => a === \"-c\" || a === \"-s\") || args.some((a) => !a.startsWith(\"-\"));\n\t}\n\n\tconst pkgMutations = PACKAGE_MANAGER_MUTATIONS[command];\n\tif (pkgMutations) {\n\t\tconst subcommand = args.find((a) => !a.startsWith(\"-\"))?.toLowerCase();\n\t\treturn subcommand !== undefined && pkgMutations.has(subcommand);\n\t}\n\n\t// Node / Python interpreters: flag-only, no executing flags, no positional scripts.\n\tif (command === \"node\") {\n\t\treturn args.some((a) => !a.startsWith(\"-\")) || args.some((a) => EXECUTING_NODE_FLAGS.has(a));\n\t}\n\tif (command === \"python\" || command === \"python3\") {\n\t\treturn args.some((a) => !a.startsWith(\"-\")) || args.some((a) => EXECUTING_PYTHON_FLAGS.has(a));\n\t}\n\n\t// Final gate: the command must be in the read-only allowlist.\n\treturn !ALLOWED_COMMANDS.has(command);\n}\n\nfunction isMutatingGit(args: string[]): boolean {\n\t// Skip global flags like --no-pager / -C <dir> / -c key=val crudely: find the first\n\t// token that doesn't start with \"-\" (imperfect for -C/-c values; conservative is fine).\n\tlet index = 0;\n\twhile (args[index] === \"--no-pager\") index++;\n\tconst subcommand = args[index]?.toLowerCase();\n\tif (!subcommand) return false;\n\tif (subcommand.startsWith(\"-\")) return false; // bare `git --version` etc. is read-only\n\n\tif (MUTATING_GIT_SUBCOMMANDS.has(subcommand)) return true;\n\tif (CONDITIONAL_GIT_SUBCOMMANDS.has(subcommand)) {\n\t\tconst rest = args.slice(index + 1);\n\t\treturn rest.some((a) => !a.startsWith(\"-\") || CONDITIONAL_GIT_MUTATING_FLAGS.has(a));\n\t}\n\treturn false;\n}\n\nfunction basenameOf(token: string): string {\n\tconst parts = token.split(/[\\\\/]/);\n\treturn parts[parts.length - 1] ?? token;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"plan-mode.d.ts","sourceRoot":"","sources":["../../src/core/plan-mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,+DAA+D;AAC/D,eAAO,MAAM,kBAAkB,+RACyP,CAAC;AAEzR,4EAA4E;AAC5E,eAAO,MAAM,uBAAuB,gEAA2D,CAAC;AAgJhG,yFAAyF;AACzF,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAE7D;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAcxF;AAOD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAe9D","sourcesContent":["/**\n * lunr: plan permission mode — read-only tool-gating heuristics + system-prompt addendum.\n *\n * Plan is a first-class permission mode (`PermissionMode = \"plan\"`). `gateToolCall`\n * in permissions.ts applies `planModeBlockReason` when the session is in plan:\n * `edit`/`write` and mutating `bash` are hard-blocked; read tools stay open.\n * InteractiveMode installs `PLAN_MODE_ADDENDUM` via the shared system-prompt\n * append slot (same slot auto mode uses).\n *\n * Bash heuristic (conservative, blocklist-based — NOT a security boundary):\n * - any `>`/`>>` redirect outside quotes blocks the whole command;\n * - the command is split on `;`, `|`, `&` separators (outside quotes) and every segment's\n * leading command must be read-only:\n * - known mutating commands (rm, mv, cp, mkdir, sed -i, tee, …) are blocked;\n * - `git` is limited to read-only subcommands (status/log/diff/show/… plus flag-only\n * branch/tag/remote); mutating subcommands (add/commit/push/checkout/…) are blocked;\n * - package managers are limited to read-only subcommands (install/add/remove/… blocked);\n * - arbitrary runners (sudo, xargs, npx, sh -c …) are blocked.\n * Unknown-but-not-listed commands are ALLOWED (blocklist, not allowlist) — the model is\n * additionally steered by the system-prompt addendum. False positives are expected; the\n * user can run the command themselves or exit plan mode with /plan off.\n */\n\n/** Appended to the system prompt while plan mode is active. */\nexport const PLAN_MODE_ADDENDUM =\n\t\"You are in plan mode. Investigate read-only, then present your plan by calling the present_plan tool with a concise summary — the user approves or declines it in a dialog. Do not make changes until the plan is approved. The user can also exit plan mode manually with /plan off.\";\n\n/** Error returned to the model when a tool call is blocked by plan mode. */\nexport const PLAN_MODE_BLOCK_MESSAGE = \"Plan mode is active — propose a plan; no file changes.\";\n\nconst BLOCKED_TOOLS = new Set([\n\t\"edit\",\n\t\"write\",\n\t\"behavior_add\",\n\t\"behavior_remove\",\n\t\"memory_add\",\n\t\"memory_remove\",\n\t\"cron\",\n]);\n\n/** Small allowlist of read-only commands permitted in plan mode. Everything else is rejected. */\nconst ALLOWED_COMMANDS = new Set([\n\t\"ls\",\n\t\"ll\",\n\t\"cat\",\n\t\"tac\",\n\t\"grep\",\n\t\"rg\",\n\t\"find\",\n\t\"pwd\",\n\t\"echo\",\n\t\"printf\",\n\t\"head\",\n\t\"tail\",\n\t\"wc\",\n\t\"less\",\n\t\"more\",\n\t\"sort\",\n\t\"uniq\",\n\t\"diff\",\n\t\"cmp\",\n\t\"comm\",\n\t\"test\",\n\t\"[\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"whereis\",\n\t\"stat\",\n\t\"file\",\n\t\"id\",\n\t\"whoami\",\n\t\"who\",\n\t\"date\",\n\t\"cal\",\n\t\"env\",\n\t\"printenv\",\n\t\"uname\",\n\t\"hostname\",\n\t\"uptime\",\n\t\"nproc\",\n\t\"tput\",\n\t\"git\",\n\t\"gh\",\n\t\"node\",\n\t\"npm\",\n\t\"pnpm\",\n\t\"yarn\",\n\t\"bun\",\n]);\n\nconst MUTATING_GIT_SUBCOMMANDS = new Set([\n\t\"add\",\n\t\"commit\",\n\t\"push\",\n\t\"pull\",\n\t\"merge\",\n\t\"rebase\",\n\t\"reset\",\n\t\"checkout\",\n\t\"switch\",\n\t\"restore\",\n\t\"rm\",\n\t\"mv\",\n\t\"stash\",\n\t\"cherry-pick\",\n\t\"revert\",\n\t\"clean\",\n\t\"fetch\",\n\t\"config\",\n\t\"apply\",\n\t\"am\",\n\t\"init\",\n\t\"clone\",\n\t\"submodule\",\n\t\"worktree\",\n\t\"gc\",\n\t\"prune\",\n\t\"update-index\",\n]);\n\n// git subcommands that are read-only only when they carry no positional args or\n// mutating flags (`git branch` lists, `git branch foo` / `git branch -d foo` mutate).\nconst CONDITIONAL_GIT_SUBCOMMANDS = new Set([\"branch\", \"tag\", \"remote\"]);\nconst CONDITIONAL_GIT_MUTATING_FLAGS = new Set([\"-d\", \"-D\", \"-m\", \"-M\", \"-c\", \"-C\"]);\n\nconst PACKAGE_MANAGER_MUTATIONS: Record<string, Set<string>> = {\n\tnpm: new Set([\n\t\t\"install\",\n\t\t\"add\",\n\t\t\"remove\",\n\t\t\"uninstall\",\n\t\t\"update\",\n\t\t\"upgrade\",\n\t\t\"publish\",\n\t\t\"link\",\n\t\t\"unlink\",\n\t\t\"ci\",\n\t\t\"init\",\n\t]),\n\tpnpm: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"update\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n\tyarn: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n\tbun: new Set([\"install\", \"add\", \"remove\", \"uninstall\", \"update\", \"upgrade\", \"publish\", \"link\", \"unlink\", \"init\"]),\n};\n\n// Almost every subcommand mutates the system.\nconst ALWAYS_MUTATING_MANAGERS = new Set([\n\t\"apt\",\n\t\"apt-get\",\n\t\"brew\",\n\t\"dnf\",\n\t\"yum\",\n\t\"pacman\",\n\t\"choco\",\n\t\"winget\",\n\t\"scoop\",\n]);\n\n/** Flags that cause an interpreter to execute code and are never allowed in plan mode. */\nconst EXECUTING_NODE_FLAGS = new Set([\n\t\"-e\",\n\t\"--eval\",\n\t\"-p\",\n\t\"--print\",\n\t\"-r\",\n\t\"--require\",\n\t\"--import\",\n\t\"-i\",\n\t\"--interactive\",\n]);\nconst EXECUTING_PYTHON_FLAGS = new Set([\"-c\", \"-m\", \"-i\", \"--interactive\"]);\n\n/** Apply-mode rewrite only. Default / omitted `dry_run` is preview and stays allowed. */\nexport function isCodeRewriteMutating(input: unknown): boolean {\n\treturn (input as { dry_run?: unknown } | undefined)?.dry_run === false;\n}\n\n/**\n * Returns the block reason when plan mode should block this tool call, else undefined.\n */\nexport function planModeBlockReason(toolName: string, input: unknown): string | undefined {\n\tif (BLOCKED_TOOLS.has(toolName)) {\n\t\treturn PLAN_MODE_BLOCK_MESSAGE;\n\t}\n\tif (toolName === \"code_rewrite\" && isCodeRewriteMutating(input)) {\n\t\treturn PLAN_MODE_BLOCK_MESSAGE;\n\t}\n\tif (toolName === \"bash\") {\n\t\tconst command = readBashCommand(input);\n\t\tif (command && isMutatingBashCommand(command)) {\n\t\t\treturn `${PLAN_MODE_BLOCK_MESSAGE} Blocked command: ${command}`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction readBashCommand(input: unknown): string {\n\tconst command = (input as { command?: unknown } | undefined)?.command;\n\treturn typeof command === \"string\" ? command : \"\";\n}\n\n/**\n * Plan-mode bash allowlist. A command is mutating unless every segment is a\n * known read-only command used safely (no redirects, no command substitution,\n * no process substitution, no executing-interpreter flags).\n */\nexport function isMutatingBashCommand(command: string): boolean {\n\tif (!command.trim()) return false;\n\n\t// Any output redirect outside quotes can write a file.\n\tif (hasUnquotedRedirect(command)) return true;\n\n\t// Command substitution / process substitution / grouped redirect syntaxes\n\t// bypass a simple command-name check.\n\tif (hasShellSubstitution(command)) return true;\n\n\t// Every segment separated by ; | & && || must individually be read-only.\n\tfor (const segment of splitShellSegments(command)) {\n\t\tif (isMutatingSegment(segment)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasUnquotedRedirect(command: string): boolean {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \">\") return true;\n\t}\n\treturn false;\n}\n\nfunction splitShellSegments(command: string): string[] {\n\tconst segments: string[] = [];\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tlet start = 0;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\t// Combined operators && and || split as one boundary.\n\t\tif ((ch === \"&\" && next === \"&\") || (ch === \"|\" && next === \"|\")) {\n\t\t\tsegments.push(command.slice(start, i));\n\t\t\ti++;\n\t\t\tstart = i + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\" || ch === \"\\n\") {\n\t\t\tsegments.push(command.slice(start, i));\n\t\t\tstart = i + 1;\n\t\t}\n\t}\n\tsegments.push(command.slice(start));\n\treturn segments.map((s) => s.trim()).filter((s) => s.length > 0);\n}\n\n/** True when the command contains command/process substitution outside quotes. */\nfunction hasShellSubstitution(command: string): boolean {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"`\") return true;\n\t\tif (ch === \"$\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \"<\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \">\" && command[i + 1] === \"(\") return true;\n\t\tif (ch === \"&\" && command[i + 1] === \">\") return true;\n\t}\n\treturn false;\n}\n\nfunction isMutatingSegment(segment: string): boolean {\n\tlet tokens = segment.split(/\\s+/).filter((t) => t.length > 0);\n\t// Skip leading env assignments (FOO=bar cmd …) and command wrappers we can't see through.\n\twhile (tokens.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) {\n\t\ttokens = tokens.slice(1);\n\t}\n\tif (tokens.length === 0) return false;\n\n\tconst command = basenameOf(tokens[0]).toLowerCase();\n\tconst args = tokens.slice(1);\n\n\tif (ALWAYS_MUTATING_MANAGERS.has(command)) return true;\n\n\tif (command === \"sed\") {\n\t\treturn args.some((a) => a === \"-i\" || a.startsWith(\"-i\") || a.startsWith(\"--in-place\") || /^-[^-]*i/.test(a));\n\t}\n\tif (command === \"find\") {\n\t\treturn args.some((a) => [\"-delete\", \"-exec\", \"-execdir\", \"-ok\", \"-okdir\"].includes(a));\n\t}\n\tif (command === \"git\") {\n\t\treturn isMutatingGit(args);\n\t}\n\tif (command === \"gh\") {\n\t\t// Allow read-only views; block everything that changes remote state.\n\t\tconst sub = `${args[0] ?? \"\"} ${args[1] ?? \"\"}`;\n\t\treturn ![\n\t\t\t\"pr view\",\n\t\t\t\"pr list\",\n\t\t\t\"pr status\",\n\t\t\t\"issue view\",\n\t\t\t\"issue list\",\n\t\t\t\"issue status\",\n\t\t\t\"repo view\",\n\t\t\t\"release view\",\n\t\t\t\"release list\",\n\t\t\t\"run list\",\n\t\t\t\"run view\",\n\t\t\t\"status\",\n\t\t].includes(sub.trim());\n\t}\n\tif (command === \"sh\" || command === \"bash\" || command === \"zsh\" || command === \"dash\") {\n\t\t// `sh -c '…'` runs arbitrary code; bare `sh script` also executes. Block -c; allow\n\t\t// nothing else is too restrictive for `bash --version`, so allow flag-only invocations.\n\t\treturn args.some((a) => a === \"-c\" || a === \"-s\") || args.some((a) => !a.startsWith(\"-\"));\n\t}\n\n\tconst pkgMutations = PACKAGE_MANAGER_MUTATIONS[command];\n\tif (pkgMutations) {\n\t\tconst subcommand = args.find((a) => !a.startsWith(\"-\"))?.toLowerCase();\n\t\treturn subcommand !== undefined && pkgMutations.has(subcommand);\n\t}\n\n\t// Node / Python interpreters: flag-only, no executing flags, no positional scripts.\n\tif (command === \"node\") {\n\t\treturn args.some((a) => !a.startsWith(\"-\")) || args.some((a) => EXECUTING_NODE_FLAGS.has(a));\n\t}\n\tif (command === \"python\" || command === \"python3\") {\n\t\treturn args.some((a) => !a.startsWith(\"-\")) || args.some((a) => EXECUTING_PYTHON_FLAGS.has(a));\n\t}\n\n\t// Final gate: the command must be in the read-only allowlist.\n\treturn !ALLOWED_COMMANDS.has(command);\n}\n\n/** Global git options that take no value. Unknown leading flags are treated as mutating. */\nconst GIT_GLOBAL_FLAGS = new Set([\n\t\"--no-pager\",\n\t\"--paginate\",\n\t\"-p\",\n\t\"--version\",\n\t\"--help\",\n\t\"-h\",\n\t\"--bare\",\n\t\"--no-replace-objects\",\n\t\"--no-optional-locks\",\n\t\"--literal-pathspecs\",\n\t\"--glob-pathspecs\",\n\t\"--noglob-pathspecs\",\n\t\"--icase-pathspecs\",\n]);\n\n/** Walk past known `git` globals. Returns the subcommand index, or -1 to block. */\nfunction gitSubcommandIndex(args: string[]): number {\n\tlet index = 0;\n\twhile (index < args.length) {\n\t\tconst token = args[index];\n\t\tif (!token.startsWith(\"-\")) return index;\n\t\tif (token === \"--\") return index + 1;\n\t\tif (GIT_GLOBAL_FLAGS.has(token)) {\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (token === \"-C\" || token === \"-c\" || token === \"--git-dir\" || token === \"--work-tree\" || token === \"--namespace\") {\n\t\t\tif (args[index + 1] === undefined) return -1;\n\t\t\tindex += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\ttoken.startsWith(\"--git-dir=\") ||\n\t\t\ttoken.startsWith(\"--work-tree=\") ||\n\t\t\ttoken.startsWith(\"--namespace=\") ||\n\t\t\ttoken.startsWith(\"--config-env=\")\n\t\t) {\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\t\treturn -1;\n\t}\n\treturn index;\n}\n\nfunction isMutatingGit(args: string[]): boolean {\n\tconst index = gitSubcommandIndex(args);\n\tif (index < 0) return true;\n\tconst subcommand = args[index]?.toLowerCase();\n\tif (!subcommand) return false;\n\n\tif (MUTATING_GIT_SUBCOMMANDS.has(subcommand)) return true;\n\tif (CONDITIONAL_GIT_SUBCOMMANDS.has(subcommand)) {\n\t\tconst rest = args.slice(index + 1);\n\t\treturn rest.some((a) => !a.startsWith(\"-\") || CONDITIONAL_GIT_MUTATING_FLAGS.has(a));\n\t}\n\treturn false;\n}\n\nfunction basenameOf(token: string): string {\n\tconst parts = token.split(/[\\\\/]/);\n\treturn parts[parts.length - 1] ?? token;\n}\n"]}
|