fix(coding-agent): stop questionnaire from entering plan mode prematurely

Only submit_plan enters the planning phase; asking questions never
locks writes. Rewrite plan prompt with complex/small criteria,
widen planning shell allowlist to verification commands, and update
tests and docs.
This commit is contained in:
yilv committed 2026-10-05 10:27:45 +08:00
1 parent c1724a2af9
commit 1307b087e2
9 files changed
+128 -62

No files matched your search

+1
View File
@@ -28,6 +28,7 @@
- Fixed the subagent status line crashing the TUI with `Rendered line exceeds terminal width` because it did not reserve space for the `subagents ` prefix; the hint is now dropped when the terminal is too narrow for it, and the expanded header and output label are truncated or wrapped to the terminal width.
- Improved crash diagnostics with hints identifying loaded extensions that appear in the stack trace.
- Fixed clipboard image paste (`Ctrl+V`, `Alt+V` on Windows) sending only the temp file path as text instead of attaching the image to the prompt.
- Fixed plan mode locking writes prematurely: asking clarifying questions with `questionnaire` no longer enters the planning phase, only an explicit `submit_plan` does. Rewrote the plan prompt with clear complex/small criteria (default to acting directly), and widened the planning shell allowlist to read-only verification commands (`npm test/run/exec`, `npx`, `pytest`, `go test`, `cargo test`, `tsc --noEmit`, …).
### Removed
+1 -1
View File
@@ -503,7 +503,7 @@ Pi is aggressively extensible so it doesn't have to dictate your workflow. Featu
**No permission popups.** Run in a container, or build your own confirmation flow with [extensions](#extensions) inline with your environment and security requirements.
**Plan mode.** For complex tasks the model investigates read-only, asks clarifying questions with the built-in `questionnaire` tool, and submits a numbered plan with `submit_plan`. Edits and non-read-only shell commands stay blocked until you approve the plan in the dialog. Small tasks skip the plan; disable the whole workflow with `--exclude-tools submit_plan`.
**Plan mode.** For complex tasks the model investigates read-only, optionally asks clarifying questions with the built-in `questionnaire` tool (which never locks editing on its own), and submits a numbered plan with `submit_plan` only when confirmation is needed. Edits and non-read-only shell commands stay blocked only after a plan is submitted and needs revision, until you approve it in the dialog. Small tasks skip the plan; disable the whole workflow with `--exclude-tools submit_plan`.
**No built-in to-dos.** They confuse models. Use a TODO.md file, or build your own with [extensions](#extensions).
+4 -4
View File
@@ -312,11 +312,11 @@ pi --exclude-tools ask_question
Plan mode is built in and needs no toggle. For complex tasks the model follows a plan workflow instead of editing right away:
1. Investigate the task read-only.
2. If requirements are unclear, ask the user with the built-in `questionnaire` tool.
3. Submit a numbered plan with the built-in `submit_plan` tool. The call opens a dialog where you approve, revise, or reject the plan.
4. Until a plan is approved, `edit` and `write` are blocked and `bash`/`powershell` accept read-only commands only. Blocked tool results tell the model what to do next.
2. If requirements are genuinely unclear, ask the user with the built-in `questionnaire` tool. Asking questions never locks editing on its own.
3. Submit a numbered plan with the built-in `submit_plan` tool, only for complex multi-step tasks that need confirmation. The call opens a dialog where you approve, revise, or reject the plan.
4. Only after a plan is submitted and needs revision does the lock apply: until the revised plan is approved, `edit` and `write` are blocked and `bash`/`powershell` accept read-only commands only (including verification commands like `npm test` or `npm run check`). Blocked tool results tell the model what to do next.
Small, unambiguous tasks skip the plan. The workflow needs `submit_plan`: exclude it (`--exclude-tools submit_plan`, `--no-builtin-tools`, or `--no-tools`) to turn plan mode off.
Small, unambiguous tasks skip the plan entirely: no questions, no `submit_plan`. The workflow needs `submit_plan`: exclude it (`--exclude-tools submit_plan`, `--no-builtin-tools`, or `--no-tools`) to turn plan mode off.
## Design Principles
@@ -558,13 +558,9 @@ export class AgentSession {
// be overridden by them.
const planBlock = this._planMode.checkToolCall(toolCall.name, args as Record<string, unknown>);
if (planBlock) return planBlock;
if (toolCall.name === "questionnaire" && this.getActiveToolNames().includes("submit_plan")) {
// Asking the user means the model is planning; writes stay blocked until a
// plan is approved in the submit_plan tool call. Without submit_plan there
// is no way to approve, so the phase must not change.
this._planMode.noteQuestionsAsked();
this._syncPlanStatus();
}
// Questionnaire answers never enter plan mode on their own: only an explicit
// submit_plan call enters the planning phase. This keeps small tasks that
// just need one clarifying question from locking writes prematurely.
const runner = this._extensionRunner;
if (!runner.hasHandlers("tool_call")) {
+36 -22
View File
@@ -2,18 +2,21 @@
* Built-in plan mode.
*
* Plan mode has no toggle: the system prompt tells the model to plan complex tasks on its own.
* For a complex task the model explores read-only, asks clarifying questions with the
* `questionnaire` tool, and submits a numbered plan with `submit_plan`; that tool call blocks
* until the user approves, revises, or rejects the plan.
* For a complex task the model explores read-only, optionally asks clarifying questions with
* the `questionnaire` tool, and submits a numbered plan with `submit_plan`; that tool call
* blocks until the user approves, revises, or rejects the plan.
*
* Only `submit_plan` enters the planning phase. Asking questions never locks writes on its
* own, so a small task that just needs one clarification is never blocked prematurely.
*
* `AgentSession` owns one instance per session:
* - `checkToolCall()` runs from the session's `beforeToolCall` hook and blocks writes while a
* plan is pending approval.
* - The `questionnaire` and `submit_plan` tools move the state forward through
* `noteQuestionsAsked()` / `notePlanSubmitted()` / `approvePlan()` / `keepPlanning()`.
* - The `submit_plan` tool moves the state forward through
* `notePlanSubmitted()` / `approvePlan()` / `keepPlanning()`.
*
* The phase is per run and not persisted: after a resume the session starts in `idle`, so only
* the prompt-level rules apply until the model asks a question or submits a plan again.
* the prompt-level rules apply until the model submits a plan again.
*/
import type { BeforeToolCallResult } from "@earendil-works/pi-agent-core";
@@ -30,12 +33,12 @@ export type PlanPhase =
/** Footer status key used while a plan is pending approval. */
export const PLAN_STATUS_KEY = "plan";
export const PLAN_MODE_PROMPT = `Plan workflow for complex tasks:
- Investigate before changing anything: start read-only and make sure you understand the task.
- If anything is unclear, ask the user with the questionnaire tool before writing the plan. Ask all open questions in one call.
- Then write a numbered plan with concrete steps and submit it with the submit_plan tool. The call waits for the user to approve, revise, or reject the plan and returns their decision.
- While a plan is pending approval, edit and write are blocked and bash/powershell accept read-only commands only. Blocked tool results explain how to proceed.
- For a small, unambiguous task you can act directly without a plan.`;
export const PLAN_MODE_PROMPT = `Plan workflow for complex tasks. Default to acting directly; only plan when needed.
- Complex means: multi-file or multi-step changes (more than 2-3 steps), ambiguous requirements, architectural choices, or destructive/data-loss operations. Small means: single-file fix, typo, rename, read-only question, or a clear explicit instruction. When in doubt on a trivial task, act directly.
- Investigate before changing anything: use read-only tools (read, grep, find, ls, safe bash) and make sure you understand the task.
- Use the questionnaire tool only when requirements are genuinely unclear and you cannot proceed with a reasonable default. Ask all open questions in one call. Asking questions does not lock editing; do not use it for routine confirmation on small tasks.
- Submit a numbered plan with concrete steps via submit_plan only for complex tasks that need user confirmation. Never submit a plan for small, unambiguous tasks.
- After submit_plan the call waits for the user to approve, revise, or reject it. While a submitted plan is pending (revise/reject/dismiss), edit and write are blocked and bash/powershell accept read-only commands only. If the task turned out trivial, submit a minimal plan so the user can approve and unlock.`;
// Destructive commands blocked while a plan is pending approval.
const DESTRUCTIVE_COMMAND_PATTERNS = [
@@ -113,10 +116,17 @@ const BASH_SAFE_PATTERNS = [
/^\s*free\b/,
/^\s*git\s+(status|log|diff|show|branch|remote|config\s+--get)/i,
/^\s*git\s+ls-/i,
/^\s*npm\s+(list|ls|view|info|search|outdated|audit)/i,
/^\s*yarn\s+(list|info|why|audit)/i,
/^\s*node\s+--version/i,
/^\s*npm\s+(list|ls|view|info|search|outdated|audit|test|run|exec)/i,
/^\s*npx\b/i,
/^\s*yarn\s+(list|info|why|audit|test|run|exec)/i,
/^\s*pnpm\s+(list|info|why|audit|test|run|exec)/i,
/^\s*node\s+--(version|check)/i,
/^\s*python\s+--version/i,
/^\s*python\s+-m\s+(pytest|unittest)/i,
/^\s*pytest\b/i,
/^\s*go\s+(test|list|version|vet)/i,
/^\s*cargo\s+(test|--version)/i,
/^\s*tsc\b.*--noEmit/i,
/^\s*curl\s/i,
/^\s*wget\s+-O\s*-/i,
/^\s*jq\b/,
@@ -142,7 +152,7 @@ const POWERSHELL_SAFE_PATTERNS = [
/^\s*get-/i,
/^\s*(select|where|measure|sort|group|compare|format|out-string)\b/i,
/^\s*(cd|chdir|pwd|dir|ls|cat|type|gc|gci|gl|gm|gv|gps|gcm|help|man|more|findstr|test-path|resolve-path|split-path|join-path|convertto-json|convertfrom-json|convertto-csv|convertfrom-csv|echo|write-output|printf)\b/i,
/^\s*(git\s+(status|log|diff|show|branch|remote|config\s+--get)|git\s+ls-|npm\s+(list|ls|view|info|search|outdated|audit)|yarn\s+(list|info|why|audit)|node\s+--version|python\s+--version)/i,
/^\s*(git\s+(status|log|diff|show|branch|remote|config\s+--get)|git\s+ls-|npm\s+(list|ls|view|info|search|outdated|audit|test|run|exec)|npx\b|yarn\s+(list|info|why|audit|test|run|exec)|pnpm\s+(list|info|why|audit|test|run|exec)|node\s+--(version|check)|python\s+--version|python\s+-m\s+(pytest|unittest)|pytest\b|go\s+(test|list|version|vet)|cargo\s+(test|--version)|tsc\b.*--noEmit)/i,
/^\s*(jq|rg|fd|bat|curl|wget)\b/,
/^\s*(ps|free|uname|whoami|date|uptime|du|df|wc|env|printenv|which|where)\b/i,
];
@@ -170,16 +180,17 @@ const SHELL_TOOLS = new Set(["bash", "powershell"]);
function writeBlockedReason(toolName: string): string {
return (
`Plan mode: ${toolName} is blocked while the plan is pending approval. ` +
"Submit your plan with the submit_plan tool; the user approves, revises, or rejects it, and only approval unlocks writes. " +
`Plan mode: ${toolName} is blocked while a submitted plan is pending approval. ` +
"Revise the plan and submit it again with the submit_plan tool; only approval unlocks writes. " +
"If the task turned out trivial, submit a minimal plan so the user can approve and unlock. " +
"When no interactive UI is available, submit_plan approves the plan automatically."
);
}
function commandBlockedReason(toolName: string, command: string): string {
return (
`Plan mode: only read-only shell commands are allowed while the plan is pending approval. ` +
`Blocked ${toolName} command: ${command}\nSubmit your plan with the submit_plan tool to unlock it.`
`Plan mode: only read-only shell commands are allowed while a submitted plan is pending approval. ` +
`Blocked ${toolName} command: ${command}\nRevise the plan and submit it again with the submit_plan tool to unlock it.`
);
}
@@ -205,9 +216,12 @@ export class PlanMode {
if (this._phase === "approved") this._setPhase("idle");
}
/** The model asked the user questions, so it is now in the planning phase. */
/**
* @deprecated Asking questions no longer enters plan mode; only submit_plan does.
* Kept as a no-op so existing callers keep compiling. New code should not call it.
*/
noteQuestionsAsked(): void {
if (this._phase === "idle") this._setPhase("planning");
return;
}
/** The model submitted a plan; it stays blocked until the user approves it. */
@@ -66,8 +66,12 @@ const questionnaireSchema = Type.Object({
export type QuestionnaireToolInput = Static<typeof questionnaireSchema>;
export const questionnaireToolSystemPromptContribution = {
snippet: "Ask the user one or more questions with an interactive questionnaire",
guidelines: ["Use questionnaire to clarify requirements or preferences before committing to an approach."],
snippet:
"Ask the user one or more questions with an interactive questionnaire (does not lock editing or enter plan mode)",
guidelines: [
"Use questionnaire only when requirements are genuinely unclear and you cannot proceed with a reasonable default; ask all open questions in one call.",
"Do not use questionnaire for routine confirmation on small, unambiguous tasks.",
],
} as const;
function errorResult(
@@ -20,8 +20,10 @@ export interface SubmitPlanDetails {
}
export const submitPlanToolSystemPromptContribution = {
snippet: "Submit a plan and wait for the user to approve, revise, or reject it",
guidelines: ["Submit a numbered plan with submit_plan before editing when the task is complex or ambiguous."],
snippet: "Submit a plan and wait for the user to approve, revise, or reject it (only for complex multi-step tasks)",
guidelines: [
"Submit a numbered plan with submit_plan only for complex multi-step tasks that need confirmation; never for small, unambiguous tasks.",
],
} as const;
export interface SubmitPlanToolOptions {
@@ -54,7 +56,7 @@ export function createSubmitPlanToolDefinition(
name: "submit_plan",
label: "submit_plan",
description:
"Submit a numbered plan and wait for the user to approve, revise, or reject it. Use it for complex or ambiguous tasks: while a plan is pending approval, edit and write are blocked and shell commands are read-only.",
"Submit a numbered plan and wait for the user to approve, revise, or reject it. Use it only for complex multi-step tasks that need confirmation; never for small, unambiguous tasks. While a submitted plan is pending approval, edit and write are blocked and shell commands are read-only.",
promptSnippet: submitPlanToolSystemPromptContribution.snippet,
promptGuidelines: [...submitPlanToolSystemPromptContribution.guidelines],
parameters: submitPlanSchema,
@@ -81,10 +81,13 @@ const questionnaireCall = fauxToolCall("questionnaire", {
const toolUse = (call: ReturnType<typeof fauxToolCall>) => fauxAssistantMessage([call], { stopReason: "toolUse" });
describe("built-in plan mode", () => {
test("blocks writes until the user approves the submitted plan", async () => {
test("asking questions never locks writes; only a revised plan blocks until approved", async () => {
const harness = await createHarness();
try {
const { ui, statusLog } = createMockUI({ selectAnswers: ["Option A", "Execute the plan"] });
const { ui, statusLog } = createMockUI({
selectAnswers: ["Option A", "Revise the plan", "Execute the plan"],
inputs: ["please add tests"],
});
await harness.session.bindExtensions({ uiContext: ui, mode: "rpc" });
expect(harness.session.getActiveToolNames()).toEqual([
"read",
@@ -99,24 +102,36 @@ describe("built-in plan mode", () => {
harness.setResponses([
toolUse(questionnaireCall),
toolUse(fauxToolCall("write", { path: "plan.txt", content: "blocked" })),
toolUse(fauxToolCall("write", { path: "before-plan.txt", content: "not blocked" })),
toolUse(fauxToolCall("submit_plan", { plan: "1. Do the thing" })),
toolUse(fauxToolCall("write", { path: "plan.txt", content: "blocked" })),
toolUse(fauxToolCall("submit_plan", { plan: "1. Do the thing\n2. Add tests" })),
toolUse(fauxToolCall("write", { path: "plan.txt", content: "written" })),
fauxAssistantMessage("done"),
]);
await harness.session.prompt("implement the feature");
const results = toolResults(harness);
expect(results.map((result) => result.toolName)).toEqual(["questionnaire", "write", "submit_plan", "write"]);
expect(results.map((result) => result.toolName)).toEqual([
"questionnaire",
"write",
"submit_plan",
"write",
"submit_plan",
"write",
]);
expect(results[0]?.isError).toBe(false);
expect(results[0]?.text).toContain("user selected: 1. Option A");
// The write before approval is blocked and the block reason names the next step.
expect(results[1]?.isError).toBe(true);
expect(results[1]?.text).toContain("Plan mode: write is blocked");
expect(results[1]?.text).toContain("submit_plan");
// A clarifying question alone never locks: the write right after it succeeds.
expect(results[1]?.isError).toBe(false);
// The revise outcome keeps writes blocked and names the next step.
expect(results[2]?.text).toContain("requested changes");
expect(results[3]?.isError).toBe(true);
expect(results[3]?.text).toContain("Plan mode: write is blocked");
expect(results[3]?.text).toContain("submit_plan");
// The approval dialog resolved to "Execute the plan".
expect(results[2]?.text).toContain("Plan approved by the user");
expect(results[3]?.isError).toBe(false);
expect(results[4]?.text).toContain("Plan approved by the user");
expect(results[5]?.isError).toBe(false);
expect(existsSync(join(harness.tempDir, "plan.txt"))).toBe(true);
// Planning shows a footer status; approval clears it again.
@@ -127,23 +142,30 @@ describe("built-in plan mode", () => {
}
});
test("keeps a pending plan after the user answers questions in a new prompt", async () => {
test("keeps a revised plan pending across new user turns", async () => {
const harness = await createHarness();
try {
const { ui } = createMockUI({ selectAnswers: ["Option A", "Execute the plan"] });
const { ui } = createMockUI({
selectAnswers: ["Revise the plan"],
inputs: ["add more detail"],
});
await harness.session.bindExtensions({ uiContext: ui, mode: "rpc" });
harness.setResponses([
toolUse(questionnaireCall),
toolUse(fauxToolCall("write", { path: "plan.txt", content: "blocked" })),
fauxAssistantMessage("waiting for a plan"),
toolUse(fauxToolCall("submit_plan", { plan: "1. Do the thing" })),
fauxAssistantMessage("waiting for a revised plan"),
]);
await harness.session.prompt("implement the feature");
// Replying to the questionnaire must not clear the pending plan.
await harness.session.prompt("yes, option A");
// Replying after a revise must not clear the pending plan: writes stay blocked.
harness.setResponses([
toolUse(fauxToolCall("write", { path: "plan.txt", content: "blocked" })),
fauxAssistantMessage("still waiting"),
]);
await harness.session.prompt("yes, please revise");
const results = toolResults(harness);
expect(results.map((result) => result.toolName)).toEqual(["questionnaire", "write"]);
expect(results.map((result) => result.toolName)).toEqual(["submit_plan", "write"]);
expect(results[0]?.text).toContain("requested changes");
expect(results[1]?.isError).toBe(true);
expect(results[1]?.text).toContain("Plan mode: write is blocked");
} finally {
+32 -5
View File
@@ -25,6 +25,20 @@ describe("isSafeBashCommand", () => {
expect(isSafeBashCommand("npm outdated")).toBe(true);
expect(isSafeBashCommand("yarn info react")).toBe(true);
});
it("allows read-only verification commands", () => {
expect(isSafeBashCommand("npm test")).toBe(true);
expect(isSafeBashCommand("npm run check")).toBe(true);
expect(isSafeBashCommand("npm exec tsc --noEmit")).toBe(true);
expect(isSafeBashCommand("npx tsc --noEmit")).toBe(true);
expect(isSafeBashCommand("yarn test")).toBe(true);
expect(isSafeBashCommand("pnpm run check")).toBe(true);
expect(isSafeBashCommand("pytest")).toBe(true);
expect(isSafeBashCommand("python -m pytest")).toBe(true);
expect(isSafeBashCommand("go test ./...")).toBe(true);
expect(isSafeBashCommand("cargo test")).toBe(true);
expect(isSafeBashCommand("tsc --noEmit")).toBe(true);
});
});
describe("destructive commands", () => {
@@ -91,6 +105,9 @@ describe("isSafePowerShellCommand", () => {
expect(isSafePowerShellCommand("Select-String -Path *.ts -Pattern TODO")).toBe(true);
expect(isSafePowerShellCommand("Get-ChildItem | Where-Object Name -like *.md")).toBe(true);
expect(isSafePowerShellCommand("git status")).toBe(true);
expect(isSafePowerShellCommand("npm test")).toBe(true);
expect(isSafePowerShellCommand("npm run check")).toBe(true);
expect(isSafePowerShellCommand("pytest")).toBe(true);
});
it("blocks mutation cmdlets anywhere in the command", () => {
@@ -115,7 +132,7 @@ describe("PlanMode", () => {
expect(planMode.phase).toBe("idle");
expect(planMode.checkToolCall("write", writeArgs)).toBeUndefined();
planMode.noteQuestionsAsked();
planMode.notePlanSubmitted();
expect(planMode.phase).toBe("planning");
const blocked = planMode.checkToolCall("write", writeArgs);
expect(blocked).toMatchObject({ block: true });
@@ -128,7 +145,7 @@ describe("PlanMode", () => {
it("keeps a pending plan across user turns and clears an approved one", () => {
const planMode = new PlanMode();
planMode.noteQuestionsAsked();
planMode.notePlanSubmitted();
planMode.startNewUserTurn();
expect(planMode.phase).toBe("planning");
@@ -137,8 +154,12 @@ describe("PlanMode", () => {
expect(planMode.phase).toBe("idle");
});
it("does not downgrade an approved plan when questions are asked", () => {
it("asking questions never enters plan mode (no premature lock)", () => {
const planMode = new PlanMode();
planMode.noteQuestionsAsked();
expect(planMode.phase).toBe("idle");
expect(planMode.checkToolCall("write", writeArgs)).toBeUndefined();
planMode.approvePlan();
planMode.noteQuestionsAsked();
expect(planMode.phase).toBe("approved");
@@ -155,7 +176,7 @@ describe("PlanMode", () => {
const planMode = new PlanMode();
const phases: string[] = [];
planMode.onChange = () => phases.push(planMode.phase);
planMode.noteQuestionsAsked();
planMode.notePlanSubmitted();
planMode.approvePlan();
planMode.keepPlanning();
planMode.keepPlanning();
@@ -166,8 +187,14 @@ describe("PlanMode", () => {
const planMode = new PlanMode();
planMode.notePlanSubmitted();
expect(planMode.checkToolCall("bash", { command: "ls -la" })).toBeUndefined();
expect(planMode.checkToolCall("bash", { command: "npm test" })?.block).toBe(true);
// Read-only verification commands stay allowed while planning.
expect(planMode.checkToolCall("bash", { command: "npm test" })).toBeUndefined();
expect(planMode.checkToolCall("bash", { command: "npm run check" })).toBeUndefined();
// Mutations and unknown commands stay blocked.
expect(planMode.checkToolCall("bash", { command: "npm install lodash" })?.block).toBe(true);
expect(planMode.checkToolCall("bash", { command: "node build.js" })?.block).toBe(true);
expect(planMode.checkToolCall("powershell", { command: "Get-ChildItem" })).toBeUndefined();
expect(planMode.checkToolCall("powershell", { command: "npm test" })).toBeUndefined();
expect(planMode.checkToolCall("powershell", { command: "Set-Content a b" })?.block).toBe(true);
// Tools plan mode does not manage stay untouched.
expect(planMode.checkToolCall("read", { path: "file.ts" })).toBeUndefined();