ceulen 0.5.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +365 -12
- package/README.md +87 -91
- package/extensions/lib/advisor-marker.ts +33 -0
- package/extensions/lib/panel.ts +25 -2
- package/extensions/lib/rate.ts +24 -0
- package/extensions/lib/registry.test.ts +67 -0
- package/extensions/lib/registry.ts +104 -8
- package/extensions/lib/tools.ts +47 -0
- package/extensions/lib/usage-store.ts +33 -0
- package/extensions/modules/advisor/commands/advisor.ts +244 -0
- package/extensions/modules/advisor/configPanel.ts +194 -0
- package/extensions/modules/advisor/index.ts +235 -0
- package/extensions/modules/advisor/lib/config.ts +248 -0
- package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
- package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
- package/extensions/modules/advisor/lib/model-picker.ts +47 -0
- package/extensions/modules/advisor/lib/watcher.ts +288 -0
- package/extensions/modules/advisor/test/compliance.test.ts +125 -0
- package/extensions/modules/advisor/test/config.test.ts +202 -0
- package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
- package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
- package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
- package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
- package/extensions/modules/advisor/test/module.test.ts +649 -0
- package/extensions/modules/advisor/test/watcher.test.ts +478 -0
- package/extensions/modules/classifier/configPanel.ts +104 -0
- package/extensions/modules/classifier/index.ts +297 -0
- package/extensions/modules/classifier/lib/settings.ts +95 -0
- package/extensions/modules/classifier/test/classifier.test.ts +475 -0
- package/extensions/modules/composer/index.ts +152 -3
- package/extensions/modules/composer/lib/footer.ts +119 -0
- package/extensions/modules/composer/lib/shapes.ts +265 -26
- package/extensions/modules/composer/test/editor.test.ts +1 -1
- package/extensions/modules/composer/test/footer.test.ts +96 -0
- package/extensions/modules/composer/test/module.test.ts +113 -11
- package/extensions/modules/composer/test/screen.test.ts +29 -1
- package/extensions/modules/composer/test/shapes.test.ts +224 -8
- package/extensions/modules/config/defaultTools.ts +96 -0
- package/extensions/modules/config/index.ts +147 -7
- package/extensions/modules/config/piSettings.ts +254 -69
- package/extensions/modules/config/test/defaultTools.test.ts +122 -0
- package/extensions/modules/config/test/menu.test.ts +64 -0
- package/extensions/modules/config/test/panel.test.ts +38 -23
- package/extensions/modules/config/test/piSettings.test.ts +130 -3
- package/extensions/modules/config/test/renderTools.test.ts +71 -0
- package/extensions/modules/config/test/tools.test.ts +146 -0
- package/extensions/modules/fff/index.ts +2094 -0
- package/extensions/modules/fff/lib/query.ts +129 -0
- package/extensions/modules/fff/test/index.test.ts +607 -0
- package/extensions/modules/fff/test/query.test.ts +71 -0
- package/extensions/modules/munin/configPanel.ts +108 -0
- package/extensions/modules/munin/index.ts +641 -0
- package/extensions/modules/munin/lib/helpers.ts +471 -0
- package/extensions/modules/munin/lib/retry.ts +20 -0
- package/extensions/modules/munin/lib/sdk.ts +218 -0
- package/extensions/modules/munin/test/config.test.ts +168 -0
- package/extensions/modules/munin/test/configPanel.test.ts +186 -0
- package/extensions/modules/munin/test/extension.test.ts +224 -0
- package/extensions/modules/munin/test/helpers.test.ts +523 -0
- package/extensions/modules/munin/test/retry.test.ts +145 -0
- package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
- package/extensions/modules/plan/configPanel.ts +152 -0
- package/extensions/modules/plan/index.ts +917 -0
- package/extensions/modules/plan/lib/plan-tools.ts +72 -0
- package/extensions/modules/plan/lib/prompt.ts +65 -0
- package/extensions/modules/plan/lib/settings.ts +166 -0
- package/extensions/modules/plan/lib/shell-gate.ts +200 -0
- package/extensions/modules/plan/test/configPanel.test.ts +96 -0
- package/extensions/modules/plan/test/harness.ts +133 -0
- package/extensions/modules/plan/test/module.test.ts +305 -0
- package/extensions/modules/plan/test/settings.test.ts +114 -0
- package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
- package/extensions/modules/ponytail/index.ts +23 -73
- package/extensions/modules/ponytail/lib/config.ts +1 -6
- package/extensions/modules/ponytail/test/extension.test.ts +1 -85
- package/extensions/modules/repair/configPanel.ts +96 -0
- package/extensions/modules/repair/index.ts +414 -0
- package/extensions/modules/repair/lib/auto-bg.ts +333 -0
- package/extensions/modules/repair/lib/edit-repair.ts +155 -0
- package/extensions/modules/repair/lib/editor.ts +251 -0
- package/extensions/modules/repair/lib/guards.ts +34 -0
- package/extensions/modules/repair/lib/input-repair.ts +324 -0
- package/extensions/modules/repair/lib/patch.ts +481 -0
- package/extensions/modules/repair/lib/settings.ts +114 -0
- package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
- package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
- package/extensions/modules/repair/test/editor.test.ts +141 -0
- package/extensions/modules/repair/test/guards.test.ts +64 -0
- package/extensions/modules/repair/test/input-repair.test.ts +231 -0
- package/extensions/modules/repair/test/patch.test.ts +563 -0
- package/extensions/modules/repair/test/settings.test.ts +167 -0
- package/extensions/modules/repair/test/wrapper.test.ts +210 -0
- package/extensions/modules/router/commands/commands.ts +4 -0
- package/extensions/modules/router/configPanel.ts +24 -10
- package/extensions/modules/router/lib/client.ts +63 -0
- package/extensions/modules/router/lib/provider.ts +34 -13
- package/extensions/modules/router/lib/systemone.ts +152 -0
- package/extensions/modules/router/test/unit.test.ts +260 -0
- package/extensions/modules/rtk/findFallback.js +68 -0
- package/extensions/modules/rtk/index.ts +248 -0
- package/extensions/modules/rtk/safe-rewrite.js +74 -0
- package/extensions/modules/rtk/test/findFallback.test.js +66 -0
- package/extensions/modules/rtk/test/index.test.js +131 -0
- package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
- package/extensions/modules/rtk/version-gate.js +34 -0
- package/extensions/modules/rules/index.ts +120 -0
- package/extensions/modules/rules/lib/rules.ts +348 -0
- package/extensions/modules/rules/test/lib.test.ts +263 -0
- package/extensions/modules/rules/test/module.test.ts +222 -0
- package/extensions/modules/serena/index.ts +629 -0
- package/extensions/modules/serena/lib/detect.ts +73 -0
- package/extensions/modules/serena/lib/env.ts +76 -0
- package/extensions/modules/serena/lib/guidance.ts +26 -0
- package/extensions/modules/serena/lib/normalize.ts +27 -0
- package/extensions/modules/serena/lib/symbol-key.ts +20 -0
- package/extensions/modules/serena/lib/truncate.ts +20 -0
- package/extensions/modules/serena/test/env.test.ts +122 -0
- package/extensions/modules/serena/test/index.test.ts +347 -0
- package/extensions/modules/serena/test/worker.test.ts +562 -0
- package/extensions/modules/serena/worker.ts +858 -0
- package/extensions/modules/steering/configPanel.ts +122 -0
- package/extensions/modules/steering/index.ts +616 -0
- package/extensions/modules/steering/lib/anchor.ts +175 -0
- package/extensions/modules/steering/lib/errors.ts +253 -0
- package/extensions/modules/steering/lib/family.ts +33 -0
- package/extensions/modules/steering/lib/guidance.ts +172 -0
- package/extensions/modules/steering/lib/history.ts +170 -0
- package/extensions/modules/steering/lib/settings.ts +127 -0
- package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
- package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
- package/extensions/modules/steering/test/anchor.test.ts +160 -0
- package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
- package/extensions/modules/steering/test/errors.test.ts +309 -0
- package/extensions/modules/steering/test/family.test.ts +43 -0
- package/extensions/modules/steering/test/guidance.test.ts +357 -0
- package/extensions/modules/steering/test/harness.ts +93 -0
- package/extensions/modules/steering/test/history.test.ts +118 -0
- package/extensions/modules/steering/test/settings.test.ts +182 -0
- package/extensions/modules/steering/test/status.test.ts +71 -0
- package/extensions/modules/steering/test/toolCall.test.ts +99 -0
- package/extensions/modules/subagent/agents/planner.md +14 -0
- package/extensions/modules/subagent/agents/reviewer.md +42 -0
- package/extensions/modules/subagent/agents/scout.md +47 -0
- package/extensions/modules/subagent/agents/tester.md +12 -0
- package/extensions/modules/subagent/agents/worker.md +18 -0
- package/extensions/modules/subagent/configPanel.ts +219 -0
- package/extensions/modules/subagent/index.ts +2464 -0
- package/extensions/modules/subagent/lib/agents.ts +408 -0
- package/extensions/modules/subagent/lib/background.ts +383 -0
- package/extensions/modules/subagent/lib/herdr.ts +1019 -0
- package/extensions/modules/subagent/lib/history.ts +126 -0
- package/extensions/modules/subagent/lib/model.ts +156 -0
- package/extensions/modules/subagent/lib/render.ts +335 -0
- package/extensions/modules/subagent/lib/result.ts +110 -0
- package/extensions/modules/subagent/lib/roles.ts +296 -0
- package/extensions/modules/subagent/lib/routing.ts +228 -0
- package/extensions/modules/subagent/lib/runner.ts +559 -0
- package/extensions/modules/subagent/lib/schema.ts +21 -0
- package/extensions/modules/subagent/lib/security.ts +763 -0
- package/extensions/modules/subagent/lib/settings.ts +159 -0
- package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
- package/extensions/modules/subagent/lib/threads.ts +135 -0
- package/extensions/modules/subagent/lib/types.ts +18 -0
- package/extensions/modules/subagent/lib/widget.ts +475 -0
- package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
- package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
- package/extensions/modules/subagent/test/routing.test.ts +524 -0
- package/extensions/modules/subagent/test/widget.test.ts +208 -0
- package/extensions/modules/todo/index.ts +478 -0
- package/extensions/modules/todo/test/todo.test.ts +252 -0
- package/extensions/modules/usage/index.ts +70 -16
- package/extensions/modules/usage/test/genrate.test.ts +70 -0
- package/extensions/modules/usage/test/parsers.test.ts +13 -0
- package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
- package/extensions/modules/ux/UPSTREAM +24 -0
- package/extensions/modules/ux/index.ts +393 -0
- package/extensions/modules/ux/lib/audit.ts +562 -0
- package/extensions/modules/ux/lib/config.ts +136 -0
- package/extensions/modules/ux/lib/instructions.ts +77 -0
- package/extensions/modules/ux/test/audit.test.ts +756 -0
- package/extensions/modules/ux/test/extension.test.ts +394 -0
- package/extensions/modules/ux/test/instructions.test.ts +19 -0
- package/extensions/modules/web/configPanel.ts +218 -0
- package/extensions/modules/web/index.ts +978 -0
- package/extensions/modules/web/lib/agy.ts +209 -0
- package/extensions/modules/web/lib/brave.ts +42 -0
- package/extensions/modules/web/lib/cdp.ts +686 -0
- package/extensions/modules/web/lib/chatapi.ts +101 -0
- package/extensions/modules/web/lib/chatgpt.ts +796 -0
- package/extensions/modules/web/lib/chrome.ts +328 -0
- package/extensions/modules/web/lib/config.ts +136 -0
- package/extensions/modules/web/lib/content.ts +99 -0
- package/extensions/modules/web/lib/crawl4ai.ts +172 -0
- package/extensions/modules/web/lib/extract.ts +235 -0
- package/extensions/modules/web/lib/firecrawl.ts +56 -0
- package/extensions/modules/web/lib/format.ts +197 -0
- package/extensions/modules/web/lib/gemini-auth.ts +286 -0
- package/extensions/modules/web/lib/gemini-dr.ts +338 -0
- package/extensions/modules/web/lib/gemini.ts +551 -0
- package/extensions/modules/web/lib/imageapi.ts +559 -0
- package/extensions/modules/web/lib/retry.ts +71 -0
- package/extensions/modules/web/lib/search.ts +237 -0
- package/extensions/modules/web/lib/searxng.ts +69 -0
- package/extensions/modules/web/lib/settings.ts +157 -0
- package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
- package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
- package/extensions/modules/web/test/agy.test.ts +383 -0
- package/extensions/modules/web/test/cdp.test.ts +717 -0
- package/extensions/modules/web/test/chat.test.ts +171 -0
- package/extensions/modules/web/test/chatgpt.test.ts +633 -0
- package/extensions/modules/web/test/chrome.test.ts +282 -0
- package/extensions/modules/web/test/config.test.ts +218 -0
- package/extensions/modules/web/test/configPanel.test.ts +198 -0
- package/extensions/modules/web/test/crawl.test.ts +134 -0
- package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
- package/extensions/modules/web/test/extension.test.ts +118 -0
- package/extensions/modules/web/test/extract.test.ts +436 -0
- package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
- package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
- package/extensions/modules/web/test/fixtures/interaction.html +31 -0
- package/extensions/modules/web/test/format.test.ts +230 -0
- package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
- package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
- package/extensions/modules/web/test/gemini.test.ts +472 -0
- package/extensions/modules/web/test/hook.test.ts +101 -0
- package/extensions/modules/web/test/image.test.ts +1089 -0
- package/extensions/modules/web/test/retry.test.ts +119 -0
- package/extensions/modules/web/test/screenshot.test.ts +109 -0
- package/extensions/modules/web/test/search.test.ts +210 -0
- package/extensions/modules/web/test/settings.test.ts +165 -0
- package/extensions/modules/web/test/skill.test.ts +72 -0
- package/extensions/modules/web/types.d.ts +3 -0
- package/extensions/modules/web/vendor/package.json +1 -0
- package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
- package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
- package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
- package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
- package/extensions/modules/web/vendor/readability/index.js +9 -0
- package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
- package/extensions/modules/zai/configPanel.ts +154 -0
- package/extensions/modules/zai/index.ts +186 -0
- package/extensions/modules/zai/lib/anthropic.ts +159 -0
- package/extensions/modules/zai/lib/settings.ts +198 -0
- package/extensions/modules/zai/lib/signing.ts +721 -0
- package/extensions/modules/zai/lib/throttle.ts +198 -0
- package/extensions/modules/zai/test/anthropic.test.ts +132 -0
- package/extensions/modules/zai/test/configPanel.test.ts +230 -0
- package/extensions/modules/zai/test/extension.test.ts +249 -0
- package/extensions/modules/zai/test/settings.test.ts +183 -0
- package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
- package/extensions/modules/zai/test/signing.test.ts +364 -0
- package/extensions/modules/zai/test/throttle.test.ts +329 -0
- package/package.json +19 -4
- package/scripts/validate-themes.mjs +75 -0
- package/skills/munin/SKILL.md +117 -0
- package/skills/ux-capture/SKILL.md +202 -0
- package/skills/ux-design/SKILL.md +279 -0
- package/skills/ux-presets/SKILL.md +484 -0
- package/skills/ux-routing/SKILL.md +46 -0
- package/skills/web/SKILL.md +153 -0
- package/themes/alabaster.json +93 -0
- package/themes/amethyst.json +96 -0
- package/themes/anthracite.json +93 -0
- package/themes/basalt.json +91 -0
- package/themes/birch.json +95 -0
- package/themes/catppuccin-mocha.json +91 -0
- package/themes/dark-abyss.json +91 -0
- package/themes/dark-arctic.json +104 -0
- package/themes/dark-aurora.json +95 -0
- package/themes/dark-catppuccin.json +107 -0
- package/themes/dark-cavern.json +91 -0
- package/themes/dark-celestial.json +106 -0
- package/themes/dark-copper.json +95 -0
- package/themes/dark-cosmos.json +90 -0
- package/themes/dark-cyberpunk.json +102 -0
- package/themes/dark-dracula.json +98 -0
- package/themes/dark-eclipse.json +91 -0
- package/themes/dark-ember.json +95 -0
- package/themes/dark-equinox.json +90 -0
- package/themes/dark-forest.json +96 -0
- package/themes/dark-github.json +105 -0
- package/themes/dark-gruvbox.json +112 -0
- package/themes/dark-lavender.json +95 -0
- package/themes/dark-lunar.json +89 -0
- package/themes/dark-midnight.json +95 -0
- package/themes/dark-monochrome.json +94 -0
- package/themes/dark-monokai.json +98 -0
- package/themes/dark-nebula.json +90 -0
- package/themes/dark-neon-noir.json +100 -0
- package/themes/dark-nord.json +98 -0
- package/themes/dark-ocean.json +101 -0
- package/themes/dark-one.json +100 -0
- package/themes/dark-poimandres.json +115 -0
- package/themes/dark-rainforest.json +91 -0
- package/themes/dark-reef.json +91 -0
- package/themes/dark-retro.json +92 -0
- package/themes/dark-rose-pine.json +96 -0
- package/themes/dark-sakura.json +95 -0
- package/themes/dark-slate.json +95 -0
- package/themes/dark-solarized.json +97 -0
- package/themes/dark-solstice.json +90 -0
- package/themes/dark-starfall.json +91 -0
- package/themes/dark-sunset.json +99 -0
- package/themes/dark-swamp.json +90 -0
- package/themes/dark-synthwave.json +103 -0
- package/themes/dark-taiga.json +91 -0
- package/themes/dark-terminal.json +95 -0
- package/themes/dark-tokyo-night.json +101 -0
- package/themes/dark-tundra.json +91 -0
- package/themes/dark-twilight.json +91 -0
- package/themes/dark-volcanic.json +91 -0
- package/themes/dark.json +80 -0
- package/themes/graphite.json +92 -0
- package/themes/light-arctic.json +107 -0
- package/themes/light-aurora-day.json +91 -0
- package/themes/light-canyon.json +91 -0
- package/themes/light-catppuccin.json +106 -0
- package/themes/light-cirrus.json +90 -0
- package/themes/light-coral.json +95 -0
- package/themes/light-cyberpunk.json +96 -0
- package/themes/light-dawn.json +90 -0
- package/themes/light-dunes.json +91 -0
- package/themes/light-eucalyptus.json +95 -0
- package/themes/light-forest.json +100 -0
- package/themes/light-frost.json +95 -0
- package/themes/light-github.json +115 -0
- package/themes/light-glacier.json +91 -0
- package/themes/light-gruvbox.json +108 -0
- package/themes/light-haze.json +90 -0
- package/themes/light-honeycomb.json +95 -0
- package/themes/light-lagoon.json +91 -0
- package/themes/light-lavender.json +95 -0
- package/themes/light-meadow.json +91 -0
- package/themes/light-mint.json +95 -0
- package/themes/light-monochrome.json +101 -0
- package/themes/light-ocean.json +99 -0
- package/themes/light-one.json +99 -0
- package/themes/light-opal.json +91 -0
- package/themes/light-orchard.json +91 -0
- package/themes/light-paper.json +95 -0
- package/themes/light-poimandres.json +115 -0
- package/themes/light-prism.json +90 -0
- package/themes/light-retro.json +98 -0
- package/themes/light-sand.json +95 -0
- package/themes/light-savanna.json +91 -0
- package/themes/light-solarized.json +102 -0
- package/themes/light-soleil.json +90 -0
- package/themes/light-sunset.json +99 -0
- package/themes/light-synthwave.json +98 -0
- package/themes/light-tokyo-night.json +111 -0
- package/themes/light-wetland.json +91 -0
- package/themes/light-zenith.json +89 -0
- package/themes/light.json +80 -0
- package/themes/limestone.json +94 -0
- package/themes/mahogany.json +97 -0
- package/themes/marble.json +93 -0
- package/themes/mirage.json +79 -0
- package/themes/obsidian.json +91 -0
- package/themes/onyx.json +91 -0
- package/themes/pearl.json +93 -0
- package/themes/porcelain.json +91 -0
- package/themes/quartz.json +96 -0
- package/themes/sandstone.json +95 -0
- package/themes/titanium.json +90 -0
|
@@ -0,0 +1,917 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* plan — read-only plan mode for ceulen.
|
|
3
|
+
*
|
|
4
|
+
* Ported from @bacnh85/pi-plan 0.16.6 (extensions/modules/plan/), reduced to
|
|
5
|
+
* the permission + review gate: mode toggle, tool gating, write_plan,
|
|
6
|
+
* ask_user_question, plan model/thinking, approval handoff, and the
|
|
7
|
+
* save-plans policy. Dropped from upstream (ceulen covers them elsewhere or
|
|
8
|
+
* pi's API cannot express them): the implement→verify→review flow (subagent
|
|
9
|
+
* worktree + advisor cover the loop), /rewind, /goal, /specs, /handoff, /btw,
|
|
10
|
+
* /doctor, the fallback chain (advisor module), and the Jev plan gate
|
|
11
|
+
* (classifier module notes tool_call can only block, never approve in
|
|
12
|
+
* pi 1.0.0).
|
|
13
|
+
*
|
|
14
|
+
* Plan files: `<repo>/.pi/plans/<timestamp>-<slug>.md` by default; the
|
|
15
|
+
* `plan.savePlans` setting decides WHICH plans hit disk — `all` (every
|
|
16
|
+
* write_plan), `approved` (drafts stay in memory, the file is written at
|
|
17
|
+
* approval), `none` (never). /config → Tasks → Plan mode edits it all.
|
|
18
|
+
*
|
|
19
|
+
* Registration surface: /plan (toggle), /plan-approve (current|new),
|
|
20
|
+
* /plan-model, /plan-thinking, /plan-auto, the --plan flag, ctrl+alt+p,
|
|
21
|
+
* tools write_plan + ask_user_question, and the shared state entry type.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type {
|
|
25
|
+
ExtensionAPI,
|
|
26
|
+
ExtensionCommandContext,
|
|
27
|
+
ExtensionContext,
|
|
28
|
+
ExtensionToolContext,
|
|
29
|
+
} from "@earendil-works/pi-coding-agent";
|
|
30
|
+
import { isToolCallEventType, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
31
|
+
import { Type } from "typebox";
|
|
32
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
33
|
+
import path from "node:path";
|
|
34
|
+
import { classifyCommand, probeDiffDrivers } from "./lib/shell-gate.js";import {
|
|
35
|
+
BLOCKED_TOOLS,
|
|
36
|
+
extractSubagentNames,
|
|
37
|
+
INTERPRETER_TOKENS,
|
|
38
|
+
READ_ONLY_TOOLS,
|
|
39
|
+
} from "./lib/plan-tools.js";
|
|
40
|
+
import { buildPlanModePrompt } from "./lib/prompt.js";
|
|
41
|
+
import {
|
|
42
|
+
DEFAULT_PLANS_DIR,
|
|
43
|
+
expandPlansDir,
|
|
44
|
+
isInsidePlansDir,
|
|
45
|
+
isThinkingLevel,
|
|
46
|
+
planPath,
|
|
47
|
+
readPlanSettings,
|
|
48
|
+
relativeToCwd,
|
|
49
|
+
writePlanSection,
|
|
50
|
+
THINKING_LEVELS,
|
|
51
|
+
type PlanSettings,
|
|
52
|
+
type ThinkingLevel,
|
|
53
|
+
} from "./lib/settings.js";
|
|
54
|
+
import { getPlanRegistry, planConfig, setPlanBridge, setPlanRegistry, type PlanBridge } from "./configPanel.js";
|
|
55
|
+
import { readDisabledTools } from "../../lib/tools.js";
|
|
56
|
+
// Sandbox semantics live in ONE place: the subagent module resolves agent
|
|
57
|
+
// frontmatter (user + project + bundled). discoverAgents is a pure fs loader,
|
|
58
|
+
// independent of whether the subagent module itself is enabled.
|
|
59
|
+
import { discoverAgents } from "../subagent/lib/agents.js";
|
|
60
|
+
|
|
61
|
+
export const PLAN_STATUS_KEY = "ceulen-plan";
|
|
62
|
+
export const PLAN_ENTRY_TYPE = "ceulen-plan";
|
|
63
|
+
export const PLAN_TOOL = "write_plan";
|
|
64
|
+
export const ASK_USER_QUESTION_TOOL = "ask_user_question";
|
|
65
|
+
|
|
66
|
+
/** Persisted plan-mode session state (branch-scoped via appendEntry). */
|
|
67
|
+
export interface PlanState {
|
|
68
|
+
enabled: boolean;
|
|
69
|
+
toolsBeforePlan?: string[];
|
|
70
|
+
lastPlanPath?: string;
|
|
71
|
+
lastPlanTitle?: string;
|
|
72
|
+
/** Plan content for the savePlans=approved|none paths (file deferred/absent). */
|
|
73
|
+
lastPlanContent?: string;
|
|
74
|
+
/** The current plan was approved+handed off — the next entry starts fresh. */
|
|
75
|
+
planApproved?: boolean;
|
|
76
|
+
planReadyForReview?: boolean;
|
|
77
|
+
prePlanModel?: string;
|
|
78
|
+
prePlanThinking?: ThinkingLevel;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface WritePlanParams {
|
|
82
|
+
title?: string;
|
|
83
|
+
content: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface PlanQuestionOption {
|
|
87
|
+
label: string;
|
|
88
|
+
description?: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
interface PlanQuestionParams {
|
|
92
|
+
question: string;
|
|
93
|
+
options: PlanQuestionOption[];
|
|
94
|
+
recommended?: string;
|
|
95
|
+
allowOther?: boolean;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function deriveTitle(content: string): string | undefined {
|
|
99
|
+
return content.match(/^#\s+(.+)$/m)?.[1]?.trim() || undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function normalizePlanContent(title: string, content: string): string {
|
|
103
|
+
const body = content.trim();
|
|
104
|
+
if (/^#\s+/m.test(body)) return `${body}\n`;
|
|
105
|
+
return `# ${title}\n\n${body}\n`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function splitModelRef(ref: string): { provider: string; id: string } | undefined {
|
|
109
|
+
const slash = ref.indexOf("/");
|
|
110
|
+
if (slash <= 0 || slash === ref.length - 1) return undefined;
|
|
111
|
+
return { provider: ref.slice(0, slash), id: ref.slice(slash + 1) };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function currentModelRef(ctx: ExtensionContext): string | undefined {
|
|
115
|
+
return ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function formatShortContextUsage(ctx: ExtensionContext): string {
|
|
119
|
+
const usage = ctx.getContextUsage();
|
|
120
|
+
return usage?.percent === null || usage?.percent === undefined
|
|
121
|
+
? "Context unknown."
|
|
122
|
+
: `Context: ${Math.round(usage.percent)}% used.`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function clip(s: string): string {
|
|
126
|
+
return s.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 120);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Build the execution prompt for the approved plan. */
|
|
130
|
+
export function buildExecutionPrompt(relativePlan: string, mode: "current" | "new"): string {
|
|
131
|
+
const prefix = mode === "new" ? "This is a fresh session created from an approved plan. " : "";
|
|
132
|
+
const where = relativePlan ? ` at ${relativePlan}` : " above";
|
|
133
|
+
return `${prefix}Execute the approved plan${where}. Read the plan file if needed, keep the implementation scoped to the plan, update it if reality differs materially, and run the verification described there.`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Read the last persisted plan-mode entry on a branch. Exported for tests. */
|
|
137
|
+
export function resolvePlanState(entries: unknown): PlanState | undefined {
|
|
138
|
+
if (!Array.isArray(entries)) return undefined;
|
|
139
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
140
|
+
const entry = entries[i] as { type?: string; customType?: string; data?: PlanState } | undefined;
|
|
141
|
+
if (entry?.type !== "custom" || entry?.customType !== PLAN_ENTRY_TYPE) continue;
|
|
142
|
+
return entry.data && typeof entry.data === "object" ? entry.data : { enabled: false };
|
|
143
|
+
}
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export default function planModule(pi: ExtensionAPI): void {
|
|
148
|
+
let planModeEnabled = false;
|
|
149
|
+
let settings: PlanSettings = readPlanSettings();
|
|
150
|
+
let liveCwd = process.cwd();
|
|
151
|
+
let liveTrusted = false;
|
|
152
|
+
/** Session-scoped allow list from the confirm tier. Keyed by tool name or
|
|
153
|
+
* `bash:<first token>` / `bash-cmd:<full command>`; cleared on mode toggle. */
|
|
154
|
+
const sessionAllows = new Set<string>();
|
|
155
|
+
let toolsBeforePlan: string[] | undefined;
|
|
156
|
+
let prePlanModel: string | undefined;
|
|
157
|
+
let prePlanThinking: ThinkingLevel | undefined;
|
|
158
|
+
let lastPlanPath: string | undefined;
|
|
159
|
+
let lastPlanTitle: string | undefined;
|
|
160
|
+
let lastPlanContent: string | undefined;
|
|
161
|
+
/** Set when the current plan was approved+handed off — the next plan-mode
|
|
162
|
+
* entry starts fresh instead of reusing the stale path/title. */
|
|
163
|
+
let planApproved = false;
|
|
164
|
+
let planReadyForReview = false;
|
|
165
|
+
let applyingStoredModel = false;
|
|
166
|
+
let writePlanInProgress = false;
|
|
167
|
+
/** Per-tool kill-switch re-read per call: a live /config toggle must never
|
|
168
|
+
* be silently undone by entering plan mode. */
|
|
169
|
+
const planToolsAvailable = (): string[] =>
|
|
170
|
+
[PLAN_TOOL, ASK_USER_QUESTION_TOOL].filter((t) => !readDisabledTools().has(t));
|
|
171
|
+
|
|
172
|
+
// ── State / settings ────────────────────────────────────────
|
|
173
|
+
|
|
174
|
+
function refreshSettings(ctx?: ExtensionContext): void {
|
|
175
|
+
if (ctx) {
|
|
176
|
+
liveCwd = ctx.cwd ?? liveCwd;
|
|
177
|
+
try { liveTrusted = ctx.isProjectTrusted?.() === true; } catch { liveTrusted = false; }
|
|
178
|
+
}
|
|
179
|
+
settings = readPlanSettings({ cwd: liveCwd, isProjectTrusted: () => liveTrusted });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Persist the working settings to the global `plan` section. */
|
|
183
|
+
/** Write ONE plan key to the GLOBAL settings file — never the merged
|
|
184
|
+
* snapshot: a project-overlay value must not be promoted to global, and
|
|
185
|
+
* a full write would resurrect stale siblings over concurrent edits. */
|
|
186
|
+
function persistSettings(patch: Partial<PlanSettings>): void {
|
|
187
|
+
writePlanSection(patch);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function persistState(): void {
|
|
191
|
+
pi.appendEntry(PLAN_ENTRY_TYPE, {
|
|
192
|
+
enabled: planModeEnabled,
|
|
193
|
+
toolsBeforePlan,
|
|
194
|
+
lastPlanPath,
|
|
195
|
+
lastPlanTitle,
|
|
196
|
+
lastPlanContent,
|
|
197
|
+
planApproved,
|
|
198
|
+
planReadyForReview,
|
|
199
|
+
prePlanModel,
|
|
200
|
+
prePlanThinking,
|
|
201
|
+
} satisfies PlanState);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function updateStatus(ctx: ExtensionContext): void {
|
|
205
|
+
ctx.ui.setStatus(PLAN_STATUS_KEY, planModeEnabled ? ctx.ui.theme.fg("accent", "Plan mode") : undefined);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Restore branch-scoped state (session_start / session_tree). */
|
|
209
|
+
function restoreStateFromBranch(ctx: ExtensionContext): void {
|
|
210
|
+
const saved = resolvePlanState(ctx.sessionManager.getBranch());
|
|
211
|
+
if (!saved) {
|
|
212
|
+
planModeEnabled = false;
|
|
213
|
+
toolsBeforePlan = undefined;
|
|
214
|
+
lastPlanPath = undefined;
|
|
215
|
+
lastPlanTitle = undefined;
|
|
216
|
+
lastPlanContent = undefined;
|
|
217
|
+
planApproved = false;
|
|
218
|
+
planReadyForReview = false;
|
|
219
|
+
prePlanModel = undefined;
|
|
220
|
+
prePlanThinking = undefined;
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
planModeEnabled = saved.enabled ?? false;
|
|
224
|
+
toolsBeforePlan = saved.toolsBeforePlan;
|
|
225
|
+
lastPlanPath = saved.lastPlanPath;
|
|
226
|
+
lastPlanTitle = saved.lastPlanTitle;
|
|
227
|
+
lastPlanContent = saved.lastPlanContent;
|
|
228
|
+
planApproved = saved.planApproved === true;
|
|
229
|
+
planReadyForReview = saved.planReadyForReview === true;
|
|
230
|
+
prePlanModel = typeof saved.prePlanModel === "string" ? saved.prePlanModel : undefined;
|
|
231
|
+
prePlanThinking = typeof saved.prePlanThinking === "string" && isThinkingLevel(saved.prePlanThinking) ? saved.prePlanThinking : undefined;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ── Tool set ────────────────────────────────────────────────
|
|
235
|
+
|
|
236
|
+
/** Enter plan mode: keep active read tools, add the plan tools, strip mutators. */
|
|
237
|
+
function enablePlanTools(): void {
|
|
238
|
+
const baseline = [...new Set([...(toolsBeforePlan ?? pi.getActiveTools()), ...planToolsAvailable()])];
|
|
239
|
+
toolsBeforePlan = baseline;
|
|
240
|
+
pi.setActiveTools(baseline.filter((t) => !BLOCKED_TOOLS.has(t)));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function restoreTools(): void {
|
|
244
|
+
if (toolsBeforePlan) pi.setActiveTools(toolsBeforePlan);
|
|
245
|
+
toolsBeforePlan = undefined;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ── Plan model / thinking ───────────────────────────────────
|
|
249
|
+
|
|
250
|
+
function applyThinking(level: ThinkingLevel): void {
|
|
251
|
+
try {
|
|
252
|
+
pi.setThinkingLevel(level);
|
|
253
|
+
} catch {
|
|
254
|
+
/* model clamp / unknown level — keep the current one */
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Apply the configured plan model + thinking. Only called while plan mode is
|
|
259
|
+
* active; records the pre-plan model/thinking once so leaving plan mode
|
|
260
|
+
* restores stock Pi behavior (in-plan /model picks stay session-temporary). */
|
|
261
|
+
async function applyPlanModeConfig(ctx: ExtensionContext): Promise<void> {
|
|
262
|
+
if (!planModeEnabled) return;
|
|
263
|
+
if (prePlanModel === undefined) prePlanModel = currentModelRef(ctx);
|
|
264
|
+
if (prePlanThinking === undefined) prePlanThinking = pi.getThinkingLevel() as ThinkingLevel;
|
|
265
|
+
|
|
266
|
+
const target = settings.planModel;
|
|
267
|
+
if (target) {
|
|
268
|
+
const parsed = splitModelRef(target);
|
|
269
|
+
const model = parsed ? ctx.modelRegistry.find(parsed.provider, parsed.id) : undefined;
|
|
270
|
+
if (!model) {
|
|
271
|
+
if (target !== currentModelRef(ctx)) {
|
|
272
|
+
ctx.ui.notify(`Plan model not loaded yet: ${target} — keeping the current model.`, "warning");
|
|
273
|
+
}
|
|
274
|
+
} else if (target !== currentModelRef(ctx)) {
|
|
275
|
+
applyingStoredModel = true;
|
|
276
|
+
try {
|
|
277
|
+
const ok = await pi.setModel(model);
|
|
278
|
+
if (!ok) ctx.ui.notify(`No API key for ${target}; plan model switch skipped.`, "warning");
|
|
279
|
+
} catch (error) {
|
|
280
|
+
ctx.ui.notify(`Plan model switch failed: ${String(error)}`, "warning");
|
|
281
|
+
} finally {
|
|
282
|
+
applyingStoredModel = false;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (settings.planThinking && isThinkingLevel(settings.planThinking)) applyThinking(settings.planThinking);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function restorePrePlanModel(ctx: ExtensionContext): Promise<void> {
|
|
290
|
+
if (!prePlanModel || prePlanModel === currentModelRef(ctx)) return;
|
|
291
|
+
const parsed = splitModelRef(prePlanModel);
|
|
292
|
+
const model = parsed ? ctx.modelRegistry.find(parsed.provider, parsed.id) : undefined;
|
|
293
|
+
if (!model) {
|
|
294
|
+
prePlanModel = undefined;
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
applyingStoredModel = true;
|
|
298
|
+
try { await pi.setModel(model); } catch { /* keep current */ }
|
|
299
|
+
finally { applyingStoredModel = false; }
|
|
300
|
+
prePlanModel = undefined;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function restorePrePlanThinking(): void {
|
|
304
|
+
if (prePlanThinking && pi.getThinkingLevel() !== prePlanThinking) applyThinking(prePlanThinking);
|
|
305
|
+
prePlanThinking = undefined;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function restorePrePlan(ctx: ExtensionContext): Promise<void> {
|
|
309
|
+
await restorePrePlanModel(ctx);
|
|
310
|
+
restorePrePlanThinking();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// ── Mode toggle ─────────────────────────────────────────────
|
|
314
|
+
|
|
315
|
+
async function enterPlanMode(ctx: ExtensionContext): Promise<void> {
|
|
316
|
+
planModeEnabled = true;
|
|
317
|
+
sessionAllows.clear();
|
|
318
|
+
refreshSettings(ctx);
|
|
319
|
+
// A previously approved plan must not leak into a new planning session;
|
|
320
|
+
// an unapproved draft survives a toggle-off/toggle-on so refinement works.
|
|
321
|
+
if (planApproved) {
|
|
322
|
+
lastPlanPath = undefined;
|
|
323
|
+
lastPlanTitle = undefined;
|
|
324
|
+
lastPlanContent = undefined;
|
|
325
|
+
planApproved = false;
|
|
326
|
+
}
|
|
327
|
+
planReadyForReview = false;
|
|
328
|
+
enablePlanTools();
|
|
329
|
+
await applyPlanModeConfig(ctx);
|
|
330
|
+
updateStatus(ctx);
|
|
331
|
+
persistState();
|
|
332
|
+
ctx.ui.notify(`Plan mode enabled. Plans directory: ${expandPlansDir(settings.plansDir)}/`, "info");
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function leavePlanMode(ctx: ExtensionContext): Promise<void> {
|
|
336
|
+
planModeEnabled = false;
|
|
337
|
+
planReadyForReview = false;
|
|
338
|
+
sessionAllows.clear();
|
|
339
|
+
restoreTools();
|
|
340
|
+
await restorePrePlan(ctx);
|
|
341
|
+
updateStatus(ctx);
|
|
342
|
+
persistState();
|
|
343
|
+
ctx.ui.notify("Plan mode disabled.", "info");
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function togglePlanMode(ctx: ExtensionContext): Promise<void> {
|
|
347
|
+
if (planModeEnabled) await leavePlanMode(ctx);
|
|
348
|
+
else await enterPlanMode(ctx);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ── write_plan ──────────────────────────────────────────────
|
|
352
|
+
|
|
353
|
+
async function writePlanFile(destination: string, content: string): Promise<void> {
|
|
354
|
+
await withFileMutationQueue(destination, async () => {
|
|
355
|
+
await mkdir(path.dirname(destination), { recursive: true });
|
|
356
|
+
await writeFile(destination, content, "utf8");
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async function executeWritePlan(params: WritePlanParams, ctx: ExtensionToolContext) {
|
|
361
|
+
if (writePlanInProgress) throw new Error("write_plan is already in progress, wait for completion before calling again.");
|
|
362
|
+
writePlanInProgress = true;
|
|
363
|
+
try {
|
|
364
|
+
refreshSettings(ctx);
|
|
365
|
+
const title = params.title?.trim() || deriveTitle(params.content) || "Plan";
|
|
366
|
+
const content = normalizePlanContent(title, params.content);
|
|
367
|
+
|
|
368
|
+
// Refinement of the same draft reuses its path (containment-checked).
|
|
369
|
+
const reusable = lastPlanPath && lastPlanTitle === title && isInsidePlansDir(path.resolve(ctx.cwd, lastPlanPath), settings.plansDir, ctx.cwd)
|
|
370
|
+
? path.resolve(ctx.cwd, lastPlanPath)
|
|
371
|
+
: undefined;
|
|
372
|
+
const destination = reusable ?? planPath(ctx.cwd, title, settings.plansDir);
|
|
373
|
+
|
|
374
|
+
if (settings.savePlans === "all") await writePlanFile(destination, content);
|
|
375
|
+
lastPlanPath = destination;
|
|
376
|
+
lastPlanTitle = title;
|
|
377
|
+
lastPlanContent = content;
|
|
378
|
+
planReadyForReview = true;
|
|
379
|
+
persistState();
|
|
380
|
+
|
|
381
|
+
const where = settings.savePlans === "none"
|
|
382
|
+
? "kept in this conversation only (plan.savePlans = none)"
|
|
383
|
+
: settings.savePlans === "approved"
|
|
384
|
+
? `held for approval — the file is written to ${relativeToCwd(ctx.cwd, destination)} once approved`
|
|
385
|
+
: `written to ${relativeToCwd(ctx.cwd, destination)}`;
|
|
386
|
+
const tail = settings.autoApprove
|
|
387
|
+
? "Autonomous approval is armed: execution starts automatically."
|
|
388
|
+
: `The plan is ready for approval: stop and tell the user — /plan-approve is prefilled and the user presses Enter to choose current-session or fresh-session execution. Do not use ${ASK_USER_QUESTION_TOOL} to offer approve/execute options.`;
|
|
389
|
+
return {
|
|
390
|
+
content: [{ type: "text" as const, text: `Plan ${where}. ${tail}` }],
|
|
391
|
+
details: { path: settings.savePlans === "none" ? undefined : destination, title, savePlans: settings.savePlans },
|
|
392
|
+
};
|
|
393
|
+
} finally {
|
|
394
|
+
writePlanInProgress = false;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// ── ask_user_question ───────────────────────────────────────
|
|
399
|
+
|
|
400
|
+
/** Validate ask_user_question params. Throws on invalid input. */
|
|
401
|
+
function validateQuestionParams(typedParams: PlanQuestionParams): { options: PlanQuestionOption[]; recommendedIndex: number | null } {
|
|
402
|
+
const options = typedParams.options ?? [];
|
|
403
|
+
const labels = options.map((o) => o.label.trim());
|
|
404
|
+
if (labels.some((l) => !l)) throw new Error("Each option must have a non-blank label.");
|
|
405
|
+
if (new Set(labels).size !== labels.length) throw new Error("Option labels must be unique.");
|
|
406
|
+
if (labels.some((l) => l.toLowerCase() === "other" || l.toLowerCase().startsWith("other "))) {
|
|
407
|
+
throw new Error('Option labels cannot conflict with the "Other" label.');
|
|
408
|
+
}
|
|
409
|
+
let recommendedIndex: number | null = null;
|
|
410
|
+
if (typedParams.recommended) {
|
|
411
|
+
const recTrim = typedParams.recommended.trim();
|
|
412
|
+
const matchIdx = labels.findIndex((l) => l.toLowerCase() === recTrim.toLowerCase());
|
|
413
|
+
if (matchIdx === -1) throw new Error("recommended must match one of the option labels.");
|
|
414
|
+
recommendedIndex = matchIdx;
|
|
415
|
+
}
|
|
416
|
+
return { options, recommendedIndex };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// ponytail: ctx.ui.select is not reentrant — serialize concurrent dialogs.
|
|
420
|
+
let askQuestionQueue: Promise<unknown> = Promise.resolve();
|
|
421
|
+
|
|
422
|
+
async function executeAskQuestion(_toolCallId: string, params: unknown, _signal: unknown, _onUpdate: unknown, ctx: ExtensionToolContext) {
|
|
423
|
+
const typedParams = params as PlanQuestionParams;
|
|
424
|
+
const { options, recommendedIndex } = validateQuestionParams(typedParams);
|
|
425
|
+
const textBlock = (text: string) => ({ type: "text" as const, text });
|
|
426
|
+
const cancelled = {
|
|
427
|
+
content: [textBlock("User cancelled the question.")],
|
|
428
|
+
details: { question: typedParams.question, options, answer: null, cancelled: true, wasCustom: false },
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
if (!ctx.hasUI) {
|
|
432
|
+
return {
|
|
433
|
+
content: [textBlock("UI is not available. Ask this question directly in chat and wait for the user's answer.")],
|
|
434
|
+
details: { question: typedParams.question, options, answer: null, wasCustom: false, cancelled: false },
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
const allowOther = typedParams.allowOther !== false;
|
|
438
|
+
const displayLabels = options.map((option, i) => {
|
|
439
|
+
const star = recommendedIndex !== null && i === recommendedIndex && options.length > 1 ? "★ " : "";
|
|
440
|
+
return option.description ? `${star}${option.label} — ${option.description}` : `${star}${option.label}`;
|
|
441
|
+
});
|
|
442
|
+
const otherLabel = "Other / type my answer";
|
|
443
|
+
const choice = await ctx.ui.select(typedParams.question, allowOther ? [...displayLabels, otherLabel] : displayLabels);
|
|
444
|
+
if (!choice) return cancelled;
|
|
445
|
+
|
|
446
|
+
if (choice === otherLabel) {
|
|
447
|
+
const answer = (await ctx.ui.editor("Your answer", ""))?.trim();
|
|
448
|
+
if (!answer) return cancelled;
|
|
449
|
+
return {
|
|
450
|
+
content: [textBlock(`User wrote: ${answer}`)],
|
|
451
|
+
details: { question: typedParams.question, options, answer, wasCustom: true, cancelled: false },
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
const selectedIndex = displayLabels.indexOf(choice);
|
|
455
|
+
const answer = options[selectedIndex]?.label ?? choice;
|
|
456
|
+
return {
|
|
457
|
+
content: [textBlock(`User selected: ${answer}`)],
|
|
458
|
+
details: { question: typedParams.question, options, answer, selectedIndex, wasCustom: false, cancelled: false },
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function executeAskQuestionQueued(toolCallId: string, params: unknown, signal: unknown, onUpdate: unknown, ctx: ExtensionToolContext) {
|
|
463
|
+
const run = () => executeAskQuestion(toolCallId, params, signal, onUpdate, ctx);
|
|
464
|
+
const result = askQuestionQueue.then(run, run);
|
|
465
|
+
askQuestionQueue = result.catch(() => {});
|
|
466
|
+
return result;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ── Approval ────────────────────────────────────────────────
|
|
470
|
+
|
|
471
|
+
/** Persist a deferred (savePlans=approved) plan right before execution. */
|
|
472
|
+
async function materializePlan(): Promise<void> {
|
|
473
|
+
if (settings.savePlans !== "approved") return;
|
|
474
|
+
if (!lastPlanPath || !lastPlanContent) return;
|
|
475
|
+
await writePlanFile(lastPlanPath, lastPlanContent);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** Exit plan mode for execution and return the plan's relative path ("" for
|
|
479
|
+
* the never-persisted policy). */
|
|
480
|
+
async function exitPlanForExecution(ctx: ExtensionContext): Promise<string> {
|
|
481
|
+
const relativePlan = lastPlanPath && settings.savePlans !== "none" ? relativeToCwd(ctx.cwd, lastPlanPath) : "";
|
|
482
|
+
planModeEnabled = false;
|
|
483
|
+
planApproved = true;
|
|
484
|
+
planReadyForReview = false;
|
|
485
|
+
sessionAllows.clear();
|
|
486
|
+
restoreTools();
|
|
487
|
+
await restorePrePlan(ctx);
|
|
488
|
+
updateStatus(ctx);
|
|
489
|
+
persistState();
|
|
490
|
+
return relativePlan;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** Approve + execute in the current session. Shared by /plan-approve and
|
|
494
|
+
* the auto-approve settle path (no command context needed). */
|
|
495
|
+
async function executeInCurrentSession(ctx: ExtensionContext): Promise<void> {
|
|
496
|
+
await materializePlan();
|
|
497
|
+
const relativePlan = await exitPlanForExecution(ctx);
|
|
498
|
+
pi.sendUserMessage(buildExecutionPrompt(relativePlan, "current"), { deliverAs: "followUp" });
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** Approve + hand the plan to a fresh session (command context only:
|
|
502
|
+
* newSession() is a command API). */
|
|
503
|
+
async function executeInNewSession(ctx: ExtensionCommandContext): Promise<void> {
|
|
504
|
+
if (!lastPlanPath || !lastPlanContent) {
|
|
505
|
+
ctx.ui.notify("No approved plan is available to execute.", "error");
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
await materializePlan();
|
|
509
|
+
const relativePlan = await exitPlanForExecution(ctx);
|
|
510
|
+
const parentSession = ctx.sessionManager.getSessionFile();
|
|
511
|
+
// planApproved: the handed-off plan must NOT be reused as a draft when
|
|
512
|
+
// plan mode is entered again in the child session.
|
|
513
|
+
const state: PlanState = { enabled: false, lastPlanPath, lastPlanTitle, lastPlanContent, planApproved: true, planReadyForReview: false };
|
|
514
|
+
await ctx.waitForIdle();
|
|
515
|
+
const result = await ctx.newSession({
|
|
516
|
+
parentSession,
|
|
517
|
+
setup: async (sessionManager) => { sessionManager.appendCustomEntry(PLAN_ENTRY_TYPE, state); },
|
|
518
|
+
withSession: async (replacementCtx) => { await replacementCtx.sendUserMessage(buildExecutionPrompt(relativePlan, "new")); },
|
|
519
|
+
});
|
|
520
|
+
if (result.cancelled) ctx.ui.notify("New-session execution cancelled.", "info");
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
async function handlePlanApproval(args: string, ctx: ExtensionCommandContext): Promise<void> {
|
|
524
|
+
if (!lastPlanContent) {
|
|
525
|
+
ctx.ui.notify("No plan is ready for approval.", "warning");
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
let mode = args.trim().toLowerCase();
|
|
529
|
+
if (!mode) {
|
|
530
|
+
if (!ctx.hasUI) {
|
|
531
|
+
ctx.ui.notify("Usage: /plan-approve current|new", "warning");
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
const currentChoice = "Implement in current session";
|
|
535
|
+
const newChoice = `Clear context and implement · ${formatShortContextUsage(ctx)}`;
|
|
536
|
+
const stayChoice = "Stay in Plan mode";
|
|
537
|
+
const choice = await ctx.ui.select("Implement this plan?", [currentChoice, newChoice, stayChoice]);
|
|
538
|
+
if (!choice || choice === stayChoice) return;
|
|
539
|
+
mode = choice === currentChoice ? "current" : "new";
|
|
540
|
+
}
|
|
541
|
+
if (mode !== "current" && mode !== "new") {
|
|
542
|
+
ctx.ui.notify("Usage: /plan-approve current|new", "warning");
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
if (mode === "new" && settings.savePlans === "none") {
|
|
546
|
+
ctx.ui.notify("plan.savePlans = none keeps plans out of the repository — fresh-session execution needs a plan file. Use current-session execution or change plan.savePlans.", "warning");
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
if (mode === "current") await executeInCurrentSession(ctx);
|
|
550
|
+
else await executeInNewSession(ctx);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// ── Confirm tier ────────────────────────────────────────────
|
|
554
|
+
|
|
555
|
+
async function planApprovalPrompt(ctx: ExtensionContext, title: string, detail: string, rememberKey: string): Promise<string | undefined> {
|
|
556
|
+
const choice = await ctx.ui.select(`${title}\n\n${detail}`, ["Allow once", "Allow for this session", "Deny"]);
|
|
557
|
+
if (choice === "Allow for this session") {
|
|
558
|
+
sessionAllows.add(rememberKey);
|
|
559
|
+
return undefined;
|
|
560
|
+
}
|
|
561
|
+
if (choice === undefined || choice === "Deny") return `${title.replace(/ in plan mode\?$/, "")} rejected by user.`;
|
|
562
|
+
return undefined; // Allow once
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** True when every named subagent resolves to a read-only sandbox. */
|
|
566
|
+
function subagentsReadOnly(names: string[], cwd: string): boolean {
|
|
567
|
+
try {
|
|
568
|
+
const { agents } = discoverAgents(cwd, "both", path.resolve(import.meta.dirname, "../subagent/agents"));
|
|
569
|
+
return names.length > 0 && names.every((name) => agents.find((a) => a.name === name)?.sandbox === "read-only");
|
|
570
|
+
} catch {
|
|
571
|
+
return false; // fail closed → confirm tier
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// ── Registration ────────────────────────────────────────────
|
|
576
|
+
|
|
577
|
+
pi.registerFlag("plan", {
|
|
578
|
+
description: "Start in ceulen plan mode (read-only planning)",
|
|
579
|
+
type: "boolean",
|
|
580
|
+
default: false,
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
pi.registerTool({
|
|
584
|
+
name: PLAN_TOOL,
|
|
585
|
+
label: "Write Plan",
|
|
586
|
+
description: `Write/replace a plan as Markdown under the configured plans directory (default ${DEFAULT_PLANS_DIR}/). Use when the plan is ready for review.`,
|
|
587
|
+
promptSnippet: `Write the plan under ${DEFAULT_PLANS_DIR}/ as Markdown for user review`,
|
|
588
|
+
promptGuidelines: [
|
|
589
|
+
`Use ${PLAN_TOOL} in plan mode after exploration. No edit/write until the plan is approved.`,
|
|
590
|
+
`Don't call ${PLAN_TOOL} while blocking questions remain; use ${ASK_USER_QUESTION_TOOL} first.`,
|
|
591
|
+
],
|
|
592
|
+
defaultActive: !readDisabledTools().has(PLAN_TOOL),
|
|
593
|
+
parameters: Type.Object({
|
|
594
|
+
title: Type.Optional(Type.String({ description: "Short plan title. Optional: derived from the first '# Heading' in content when omitted." })),
|
|
595
|
+
content: Type.String({ description: "Markdown plan content" }),
|
|
596
|
+
}),
|
|
597
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
598
|
+
return executeWritePlan(params as WritePlanParams, ctx);
|
|
599
|
+
},
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
pi.registerTool({
|
|
603
|
+
name: ASK_USER_QUESTION_TOOL,
|
|
604
|
+
label: "Ask User Question",
|
|
605
|
+
description: "Ask the user a clarifying question with selectable options, a recommended default, and optional free-form input. Works in any mode.",
|
|
606
|
+
promptSnippet: "Ask the user a clarifying question with 2-4 options and a recommended default; works in any mode",
|
|
607
|
+
promptGuidelines: [
|
|
608
|
+
"Use only when repo research leaves a consequential ambiguity.",
|
|
609
|
+
"Prefer 2-4 concrete options. Use short labels.",
|
|
610
|
+
"Don't ask what's discoverable from the repo.",
|
|
611
|
+
"Respect the user's stated preference.",
|
|
612
|
+
"Provide a recommended option when one choice is clearly preferable.",
|
|
613
|
+
`Never issue multiple ${ASK_USER_QUESTION_TOOL} calls in the same turn — ask one question, await the answer, then decide.`,
|
|
614
|
+
],
|
|
615
|
+
defaultActive: !readDisabledTools().has(ASK_USER_QUESTION_TOOL),
|
|
616
|
+
parameters: Type.Object({
|
|
617
|
+
question: Type.String({ description: "Question to ask the user" }),
|
|
618
|
+
options: Type.Array(
|
|
619
|
+
Type.Object({
|
|
620
|
+
label: Type.String({ description: "Option label" }),
|
|
621
|
+
description: Type.Optional(Type.String({ description: "Optional explanation" })),
|
|
622
|
+
}),
|
|
623
|
+
{ description: "Options to choose from (2-4 required)", minItems: 2, maxItems: 4 },
|
|
624
|
+
),
|
|
625
|
+
recommended: Type.Optional(Type.String({ description: "Label of the recommended option (must match one option label). It is shown with a ★ marker." })),
|
|
626
|
+
allowOther: Type.Optional(Type.Boolean({ description: "Allow free-form user answer; default true" })),
|
|
627
|
+
}),
|
|
628
|
+
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
629
|
+
return executeAskQuestionQueued(toolCallId, params, signal, onUpdate, ctx);
|
|
630
|
+
},
|
|
631
|
+
});
|
|
632
|
+
|
|
633
|
+
pi.registerCommand("plan", {
|
|
634
|
+
description: "Toggle ceulen plan mode (read-only planning)",
|
|
635
|
+
handler: async (args, ctx) => {
|
|
636
|
+
if (args.trim().length > 0) {
|
|
637
|
+
ctx.ui.notify("/plan does not take arguments; use /plan to toggle plan mode.", "warning");
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
await togglePlanMode(ctx);
|
|
641
|
+
},
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
pi.registerCommand("plan-approve", {
|
|
645
|
+
description: "Approve the current plan for current-session or fresh-session execution",
|
|
646
|
+
getArgumentCompletions: (prefix) => {
|
|
647
|
+
const items = ["current", "new"]
|
|
648
|
+
.filter((k) => k.startsWith(prefix.trim().toLowerCase()))
|
|
649
|
+
.map((k) => ({ value: k, label: k }));
|
|
650
|
+
return items.length > 0 ? items : null;
|
|
651
|
+
},
|
|
652
|
+
handler: async (args, ctx) => handlePlanApproval(args, ctx),
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
pi.registerCommand("plan-model", {
|
|
656
|
+
description: "Set the plan-mode model (global); normal mode follows Pi's own /model",
|
|
657
|
+
getArgumentCompletions: (prefix) => {
|
|
658
|
+
const q = prefix.trim().toLowerCase();
|
|
659
|
+
const refs = (getPlanRegistry()?.getAvailable() ?? []).map((m) => `${m.provider}/${m.id}`);
|
|
660
|
+
const items = [...["clear"].filter((k) => k.startsWith(q)), ...refs.filter((r) => r.toLowerCase().includes(q))]
|
|
661
|
+
.slice(0, 25)
|
|
662
|
+
.map((v) => ({ value: v, label: v }));
|
|
663
|
+
return items.length > 0 ? items : null;
|
|
664
|
+
},
|
|
665
|
+
handler: async (args, ctx) => {
|
|
666
|
+
refreshSettings(ctx);
|
|
667
|
+
const trimmed = args.trim();
|
|
668
|
+
if (trimmed.toLowerCase() === "clear") {
|
|
669
|
+
if (!settings.planModel) return ctx.ui.notify("No plan model configured.", "info");
|
|
670
|
+
settings.planModel = "";
|
|
671
|
+
persistSettings({ planModel: "" });
|
|
672
|
+
if (planModeEnabled) await restorePrePlanModel(ctx);
|
|
673
|
+
ctx.ui.notify("Plan model cleared — plan mode follows the active model.", "info");
|
|
674
|
+
persistState();
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
if (!trimmed) {
|
|
678
|
+
ctx.ui.notify(`plan model=${settings.planModel || "-"} · thinking=${settings.planThinking || "-"} · active=${currentModelRef(ctx) ?? "-"}`, "info");
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
const find = () => ctx.modelRegistry.getAvailable().find((m) => `${m.provider}/${m.id}`.toLowerCase() === trimmed.toLowerCase());
|
|
682
|
+
let model = find();
|
|
683
|
+
if (!model) {
|
|
684
|
+
try { await ctx.modelRegistry.refresh(); } catch { /* use cached models */ }
|
|
685
|
+
model = find();
|
|
686
|
+
}
|
|
687
|
+
if (!model) return ctx.ui.notify(`No model matching "${trimmed}". Use provider/id.`, "warning");
|
|
688
|
+
settings.planModel = `${model.provider}/${model.id}`;
|
|
689
|
+
persistSettings({ planModel: settings.planModel });
|
|
690
|
+
if (planModeEnabled) await applyPlanModeConfig(ctx);
|
|
691
|
+
ctx.ui.notify(`Plan model set: ${settings.planModel}${planModeEnabled ? "" : " (applies in plan mode)"}`, "info");
|
|
692
|
+
persistState();
|
|
693
|
+
},
|
|
694
|
+
});
|
|
695
|
+
|
|
696
|
+
pi.registerCommand("plan-thinking", {
|
|
697
|
+
description: "Set the plan-mode thinking level (global); normal mode follows Pi's own /thinking",
|
|
698
|
+
getArgumentCompletions: (prefix) => {
|
|
699
|
+
const items = [...THINKING_LEVELS, "clear"].filter((k) => k.startsWith(prefix.trim().toLowerCase())).map((k) => ({ value: k, label: k }));
|
|
700
|
+
return items.length > 0 ? items : null;
|
|
701
|
+
},
|
|
702
|
+
handler: async (args, ctx) => {
|
|
703
|
+
refreshSettings(ctx);
|
|
704
|
+
const trimmed = args.trim();
|
|
705
|
+
if (trimmed.toLowerCase() === "clear") {
|
|
706
|
+
if (!settings.planThinking) return ctx.ui.notify("No plan thinking level configured.", "info");
|
|
707
|
+
settings.planThinking = "";
|
|
708
|
+
persistSettings({ planThinking: "" });
|
|
709
|
+
ctx.ui.notify("Plan thinking level cleared.", "info");
|
|
710
|
+
persistState();
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
if (!trimmed) {
|
|
714
|
+
ctx.ui.notify(`plan thinking=${settings.planThinking || "-"} · active=${pi.getThinkingLevel()}`, "info");
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
if (!isThinkingLevel(trimmed)) {
|
|
718
|
+
ctx.ui.notify(`Invalid thinking level: ${trimmed}. Levels: ${THINKING_LEVELS.join(", ")}.`, "warning");
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
settings.planThinking = trimmed;
|
|
722
|
+
persistSettings({ planThinking: trimmed });
|
|
723
|
+
if (planModeEnabled) applyThinking(trimmed);
|
|
724
|
+
ctx.ui.notify(`Plan thinking level set: ${trimmed}${planModeEnabled ? "" : " (applies in plan mode)"}`, "info");
|
|
725
|
+
persistState();
|
|
726
|
+
},
|
|
727
|
+
});
|
|
728
|
+
|
|
729
|
+
pi.registerCommand("plan-auto", {
|
|
730
|
+
description: "Arm autonomous approval: /plan-auto [on|off|status] — a written plan executes without a keypress",
|
|
731
|
+
getArgumentCompletions: (prefix) => {
|
|
732
|
+
const items = ["on", "off", "status"].filter((k) => k.startsWith(prefix.trim().toLowerCase())).map((k) => ({ value: k, label: k }));
|
|
733
|
+
return items.length > 0 ? items : null;
|
|
734
|
+
},
|
|
735
|
+
handler: async (args, ctx) => {
|
|
736
|
+
refreshSettings(ctx);
|
|
737
|
+
const arg = args.trim().toLowerCase();
|
|
738
|
+
if (arg && arg !== "on" && arg !== "off" && arg !== "status") {
|
|
739
|
+
ctx.ui.notify("Usage: /plan-auto [on|off|status]", "warning");
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (arg === "status") {
|
|
743
|
+
ctx.ui.notify(`auto-approve: ${settings.autoApprove ? "on" : "off"} · save plans: ${settings.savePlans} · dir: ${expandPlansDir(settings.plansDir)}`, "info");
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
settings.autoApprove = arg !== "off";
|
|
747
|
+
persistSettings({ autoApprove: settings.autoApprove });
|
|
748
|
+
// Bare /plan-auto arms and enters plan mode — the practical entry point.
|
|
749
|
+
if (!arg && settings.autoApprove && !planModeEnabled) {
|
|
750
|
+
await enterPlanMode(ctx);
|
|
751
|
+
ctx.ui.notify("Autonomous approval armed. Describe the task — the plan is executed without a keypress.", "info");
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
ctx.ui.notify(settings.autoApprove ? "Autonomous approval armed: the next written plan executes without a keypress." : "Autonomous approval disarmed.", "info");
|
|
755
|
+
},
|
|
756
|
+
});
|
|
757
|
+
|
|
758
|
+
pi.registerShortcut("ctrl+alt+p", {
|
|
759
|
+
description: "Toggle ceulen plan mode",
|
|
760
|
+
handler: async (ctx) => togglePlanMode(ctx),
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
// ── Events ──────────────────────────────────────────────────
|
|
764
|
+
|
|
765
|
+
pi.on("session_start", async (event, ctx) => {
|
|
766
|
+
sessionAllows.clear();
|
|
767
|
+
refreshSettings(ctx);
|
|
768
|
+
setPlanRegistry(ctx.modelRegistry);
|
|
769
|
+
void probeDiffDrivers(ctx.cwd); // best-effort: textconv-aware bash gating
|
|
770
|
+
restoreStateFromBranch(ctx);
|
|
771
|
+
|
|
772
|
+
// The plan tools must always be visible (unless per-tool kill-switched).
|
|
773
|
+
const active = pi.getActiveTools();
|
|
774
|
+
const additions = planToolsAvailable().filter((t) => !active.includes(t));
|
|
775
|
+
if (additions.length) pi.setActiveTools([...active, ...additions]);
|
|
776
|
+
|
|
777
|
+
if (event.reason === "startup" && pi.getFlag("plan") === true) planModeEnabled = true;
|
|
778
|
+
if (planModeEnabled) {
|
|
779
|
+
enablePlanTools();
|
|
780
|
+
await applyPlanModeConfig(ctx);
|
|
781
|
+
}
|
|
782
|
+
updateStatus(ctx);
|
|
783
|
+
});
|
|
784
|
+
|
|
785
|
+
pi.on("session_tree", async (_event, ctx) => {
|
|
786
|
+
const previousToolsBeforePlan = toolsBeforePlan;
|
|
787
|
+
const wasPlan = planModeEnabled;
|
|
788
|
+
const preModel = prePlanModel;
|
|
789
|
+
const preThinking = prePlanThinking;
|
|
790
|
+
restoreStateFromBranch(ctx);
|
|
791
|
+
sessionAllows.clear();
|
|
792
|
+
if (planModeEnabled) {
|
|
793
|
+
toolsBeforePlan ??= previousToolsBeforePlan ?? pi.getActiveTools();
|
|
794
|
+
enablePlanTools();
|
|
795
|
+
await applyPlanModeConfig(ctx);
|
|
796
|
+
} else {
|
|
797
|
+
if (previousToolsBeforePlan) pi.setActiveTools(previousToolsBeforePlan);
|
|
798
|
+
toolsBeforePlan = undefined;
|
|
799
|
+
if (wasPlan) {
|
|
800
|
+
prePlanModel = preModel;
|
|
801
|
+
prePlanThinking = preThinking;
|
|
802
|
+
await restorePrePlan(ctx);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
updateStatus(ctx);
|
|
806
|
+
persistState();
|
|
807
|
+
});
|
|
808
|
+
|
|
809
|
+
pi.on("model_select", async (event, ctx) => {
|
|
810
|
+
if (applyingStoredModel || event.source === "restore") return;
|
|
811
|
+
setPlanRegistry(ctx.modelRegistry);
|
|
812
|
+
updateStatus(ctx);
|
|
813
|
+
});
|
|
814
|
+
|
|
815
|
+
/** Tool gating in plan mode:
|
|
816
|
+
* blocked mutators → hard error; bash writers → hard-block; bash reads →
|
|
817
|
+
* auto-allow; unknown executables + non-read tools → confirm tier. */
|
|
818
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
819
|
+
if (!planModeEnabled) return;
|
|
820
|
+
if (BLOCKED_TOOLS.has(event.toolName)) {
|
|
821
|
+
return { block: true, reason: `plan mode: ${event.toolName} is not available while planning. Use ${PLAN_TOOL} to write the plan file.` };
|
|
822
|
+
}
|
|
823
|
+
if (event.toolName === ASK_USER_QUESTION_TOOL || event.toolName === PLAN_TOOL) return;
|
|
824
|
+
|
|
825
|
+
if (isToolCallEventType("bash", event)) {
|
|
826
|
+
const command = String(event.input.command || "");
|
|
827
|
+
const disposition = classifyCommand(command);
|
|
828
|
+
if (disposition === "read") return;
|
|
829
|
+
if (disposition === "write") {
|
|
830
|
+
return {
|
|
831
|
+
block: true,
|
|
832
|
+
reason: `plan mode: writing to the filesystem is not allowed while planning. "${command}" may modify files. Exit plan mode to run this command, or use ${PLAN_TOOL} to add file content to the plan.`,
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
if (!ctx.hasUI) return { block: true, reason: `plan mode: this command requires confirmation but UI is not available.\nCommand: ${command}` };
|
|
836
|
+
const firstToken = command.trim().split(/\s+/)[0] || "bash";
|
|
837
|
+
const allowKey = INTERPRETER_TOKENS.has(firstToken) ? `bash-cmd:${command.trim()}` : `bash:${firstToken}`;
|
|
838
|
+
if (sessionAllows.has(allowKey)) return;
|
|
839
|
+
const rememberNote = INTERPRETER_TOKENS.has(firstToken)
|
|
840
|
+
? '"Allow for this session" remembers only this exact command until plan mode toggles.'
|
|
841
|
+
: `"Allow for this session" remembers \`${clip(firstToken)}\` commands until plan mode toggles.`;
|
|
842
|
+
const reason = await planApprovalPrompt(
|
|
843
|
+
ctx,
|
|
844
|
+
"Allow command with possible side effects in plan mode?",
|
|
845
|
+
`This command may execute repository-controlled code or modify files.\n\nCommand: ${clip(command)}\n\n${rememberNote}`,
|
|
846
|
+
allowKey,
|
|
847
|
+
);
|
|
848
|
+
if (reason) return { block: true, reason: `plan mode: bash command ${reason}\nCommand: ${command}` };
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// Subagent delegation is auto-allowed only when every named agent is read-only.
|
|
853
|
+
if (event.toolName === "subagent") {
|
|
854
|
+
const names = extractSubagentNames(event.input);
|
|
855
|
+
// .pi/agents (project) + ~/.pi/agent/agents (user): the approval scope is "both".
|
|
856
|
+
if (names.length > 0 && subagentsReadOnly(names, ctx.cwd)) return;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
if (!READ_ONLY_TOOLS.has(event.toolName)) {
|
|
860
|
+
if (!ctx.hasUI) return { block: true, reason: `plan mode: ${event.toolName} requires confirmation but UI is not available.` };
|
|
861
|
+
const key = event.toolName === "subagent"
|
|
862
|
+
? `subagent:${[...extractSubagentNames(event.input)].sort().join(",")}`
|
|
863
|
+
: event.toolName;
|
|
864
|
+
if (sessionAllows.has(key)) return;
|
|
865
|
+
const reason = await planApprovalPrompt(ctx, `Allow ${event.toolName} in plan mode?`, `Tool: ${event.toolName}`, key);
|
|
866
|
+
if (reason) return { block: true, reason: `plan mode: ${reason}` };
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
});
|
|
870
|
+
|
|
871
|
+
/** Inject the planning contract via systemPrompt chaining (composes with
|
|
872
|
+
* ponytail/advisor/subagent; steering stays the last prompt rewriter). */
|
|
873
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
874
|
+
if (!planModeEnabled) return;
|
|
875
|
+
refreshSettings(ctx);
|
|
876
|
+
const base = typeof event?.systemPrompt === "string" ? event.systemPrompt : "";
|
|
877
|
+
const relativePlan = lastPlanPath
|
|
878
|
+
? relativeToCwd(ctx.cwd, lastPlanPath)
|
|
879
|
+
: `${expandPlansDir(settings.plansDir)}/<timestamp>-<title>.md`;
|
|
880
|
+
return {
|
|
881
|
+
systemPrompt: base + buildPlanModePrompt({
|
|
882
|
+
plansDir: expandPlansDir(settings.plansDir),
|
|
883
|
+
relativePlan,
|
|
884
|
+
deferredSave: settings.savePlans === "approved",
|
|
885
|
+
noSave: settings.savePlans === "none",
|
|
886
|
+
autoApprove: settings.autoApprove,
|
|
887
|
+
}),
|
|
888
|
+
};
|
|
889
|
+
});
|
|
890
|
+
|
|
891
|
+
/** Plan written → prefill /plan-approve, or execute immediately under
|
|
892
|
+
* auto-approve. */
|
|
893
|
+
pi.on("agent_settled", async (_event, ctx) => {
|
|
894
|
+
if (!planModeEnabled || !planReadyForReview) return;
|
|
895
|
+
planReadyForReview = false;
|
|
896
|
+
persistState();
|
|
897
|
+
if (settings.autoApprove && ctx.mode !== "print") {
|
|
898
|
+
ctx.ui.notify("Autonomous approval: plan approved, executing.", "info");
|
|
899
|
+
await executeInCurrentSession(ctx);
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
if (!ctx.hasUI) return;
|
|
903
|
+
ctx.ui.setEditorText("/plan-approve");
|
|
904
|
+
ctx.ui.notify("Plan ready for approval. Press Enter to run /plan-approve.", "info");
|
|
905
|
+
});
|
|
906
|
+
|
|
907
|
+
// ── /config bridge ──────────────────────────────────────────
|
|
908
|
+
|
|
909
|
+
const bridge: PlanBridge = {
|
|
910
|
+
read: () => readPlanSettings({ cwd: liveCwd, isProjectTrusted: () => liveTrusted }),
|
|
911
|
+
apply: (next) => { settings = next; },
|
|
912
|
+
};
|
|
913
|
+
setPlanBridge(bridge);
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// Config contribution factory (registry wires it).
|
|
917
|
+
export { planConfig };
|