plan-mode.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import {
  2. defineRuntimeTool,
  3. type AgentExtension,
  4. type ModelContextAssemblyCtx,
  5. PromptSnapshotInvalidError,
  6. type ToolExecutionContext,
  7. } from '@mavis/agent-runtime';
  8. import { Type } from '@sinclair/typebox';
  9. export const PLAN_MODE_GUIDANCE = `<plan-mode-guidance>
  10. You can request Plan Mode by calling EnterPlanMode; inside Plan Mode,
  11. ExitPlanMode submits the finished plan for the user's review.
  12. Call EnterPlanMode as your first tool action when either trigger below
  13. applies. Entry precedes all intake for that request: do not locate, unpack,
  14. list, read, or view any attachment, archive, screenshot, or workspace content,
  15. do not call ask_user or any research tool, and do not draft the plan inline or
  16. into a file in Default Mode. When the user sequences the request as "first
  17. investigate, verify, or clarify, then give me the plan", or authorizes only
  18. read-only investigation before approval, that investigation is exactly what
  19. Plan Mode is for: enter first, then perform it inside Plan Mode. Instructions
  20. about how to produce the plan do not bypass entry either: when the user names
  21. an output path for the plan document or asks for the plan as a file in the
  22. workspace, enter first, draft the canonical Plan file inside Plan Mode, and
  23. produce the file at their requested path only after the plan is approved.
  24. Producing a plan document, running clarification rounds, or collecting
  25. approval through ask_user never substitutes for calling EnterPlanMode.
  26. 1. Software implementation planning: the requested planning deliverable is a
  27. concrete plan, design, proposal, rollout strategy, or implementation-ready
  28. reference for software, codebase, data-analysis, or other technical work, even
  29. when they are not asking you to implement it in this turn. Also enter when a
  30. non-trivial implementation request requires investigation, clarification, or
  31. architectural decisions before editing, including when that need only becomes
  32. clear mid-task.
  33. 2. Approval-gated planning in any domain: the user requests a concrete plan as
  34. the deliverable and asks you to hold implementation, final file generation, or
  35. delivery until they review, approve, or confirm it.
  36. First tool action is the aim, not a one-shot window. If you recognize only
  37. mid-task that a trigger applies — because intake happened before you judged
  38. it, because investigation reveals the real scope, or because a follow-up
  39. message turns the plan into the gated deliverable — call EnterPlanMode at
  40. that moment. Late entry is always better than no entry: having already read
  41. files, called ask_user, or drafted content never disqualifies entry.
  42. The dividing line is whose decisions shape the plan. Enter when the user asks
  43. you to determine how the work should land — dependencies, ordering, gates,
  44. risks, or design choices you must investigate and settle before they approve.
  45. A requested planning deliverable is never merely informational because the
  46. user asks for the plan rather than immediate implementation. Do not enter
  47. when nothing is delegated to your judgment — including simple, trivially
  48. scoped, or purely informational requests — and never while Plan Mode is
  49. already active. Specifically:
  50. - The user supplies the complete change specification — exact edits, files,
  51. tests, and order — and asks for direct execution without questions. Execute it
  52. directly regardless of change size; their checklist is the plan. Upgrade to
  53. Plan Mode only if execution reveals the work is fundamentally different or
  54. riskier than they described.
  55. - Every decision that shapes the outcome is already made by the user; you are
  56. only assembling their decisions or executing the settled direction. Stay in
  57. Default Mode, even when they will review or sign off on the result at the end.
  58. The moment any shaping item is delegated to you — audience, format, schedule,
  59. batching, ordering, risks, gates, or acceptance criteria — this exception no
  60. longer applies: a plan you must shape and then hold for the user's
  61. confirmation is trigger 2.
  62. - The deliverable is personal or leisure content the user will follow
  63. themselves, such as a travel itinerary. Present the content directly in your
  64. reply and iterate in conversation, even when they will approve it before you
  65. write final files.
  66. Only after EnterPlanMode was actually called and declined, or entry is
  67. unavailable, may you fall back to Default Mode planning: present the plan and
  68. obtain the user's explicit approval through ask_user before treating the task
  69. as complete, and never end such a turn without giving them that decision.
  70. When Plan Mode is active, a per-turn Plan Mode system reminder governs
  71. planning conduct and exit; follow it.
  72. </plan-mode-guidance>`;
  73. export const PLAN_MODE_GUIDANCE_KEY = 'workflow/plan-mode/agent-entry.md';
  74. export interface PlanModeActionInput {
  75. readonly sessionId: string;
  76. readonly turnId: string;
  77. readonly toolCallId?: string;
  78. readonly assistantMessageId?: string;
  79. readonly signal?: AbortSignal;
  80. }
  81. export interface PlanModeExtensionOptions {
  82. readonly actions: {
  83. enter(input: PlanModeActionInput): Promise<{ readonly requestId: string }>;
  84. exit(
  85. input: PlanModeActionInput,
  86. ): Promise<{ readonly requestId: string; readonly planPath: string }>;
  87. };
  88. /** Agent-initiated entry rollback switch (`beta.desktopPlanModeAgentEntry`). */
  89. readonly agentEntryEnabled: () => boolean;
  90. }
  91. const EmptyInput = Type.Object({}, { additionalProperties: false });
  92. export function planModeExtension(options: PlanModeExtensionOptions): AgentExtension {
  93. return {
  94. id: 'plan-mode',
  95. description: 'Provides Desktop Plan Mode guidance, lifecycle tools, and per-turn reminder.',
  96. init(pi): void {
  97. // Entry guidance is Default-turn material: while Plan Mode is active the
  98. // per-turn reminder owns conduct, so both guidance variants are
  99. // suppressed instead of spending context on entry rules.
  100. pi.contributeSystemPrompt(async (ctx) => {
  101. if (ctx.plan) return null;
  102. return options.agentEntryEnabled()
  103. ? readPlanModeGuidance(ctx, PLAN_MODE_GUIDANCE_KEY, PLAN_MODE_GUIDANCE)
  104. : null;
  105. });
  106. const enterTool = lifecycleTool('EnterPlanMode', (input) => options.actions.enter(input));
  107. const exitTool = lifecycleTool('ExitPlanMode', (input) => options.actions.exit(input));
  108. // EnterPlanMode only exists where entering is possible (Default turn,
  109. // rollback switch on); ExitPlanMode only where exiting is possible (Plan
  110. // turn, regardless of switches so pre-existing Plan Sessions can exit).
  111. pi.registerTool((ctx) => (!ctx.plan && options.agentEntryEnabled() ? enterTool : null));
  112. pi.registerTool((ctx) => (ctx.plan ? exitTool : null));
  113. pi.registerReminderProvider({
  114. name: 'plan-mode',
  115. compute: (ctx) =>
  116. ctx.plan
  117. ? {
  118. content: renderPlanModeReminder(ctx.plan.canonicalPath),
  119. priority: 1_000,
  120. }
  121. : null,
  122. });
  123. },
  124. };
  125. }
  126. async function readPlanModeGuidance(
  127. ctx: ModelContextAssemblyCtx,
  128. key: string,
  129. builtin: string,
  130. ): Promise<string> {
  131. const scope = ctx.promptRead;
  132. if (!scope) return builtin;
  133. const current = await scope.source.read(scope.snapshot, key);
  134. if (current.kind === 'found') return current.content;
  135. if (current.kind === 'missing') return builtin;
  136. throw new PromptSnapshotInvalidError(`Plan Mode prompt cannot be read: ${key}`);
  137. }
  138. export function renderPlanModeReminder(canonicalPath: string): string {
  139. return `<system-reminder>
  140. Plan Mode is active. Your task is to investigate and produce an
  141. implementation-ready plan. Do not implement the plan.
  142. For investigation, you may use any available investigation tool, including
  143. repository inspection, read-only shell commands, external research, Browser
  144. tools, Skills, configured tools, and delegated tasks. For a tool that
  145. supports both reads and writes, select query, get, list, search, fetch,
  146. inspect, or preview operations. If its operation is unclear, choose the
  147. obviously read-only operation.
  148. Clarification is part of planning. Prefer investigation for anything the
  149. repository or references can answer. When a decision that shapes the plan
  150. cannot be settled from evidence — a real trade-off or a user preference —
  151. ask the user through an available question tool instead of guessing; if no
  152. question tool is available, record it under the Plan's unresolved decisions.
  153. Minor open points you can safely defer belong there too, not in questions.
  154. Do not create, update, delete, publish, submit, deploy, send, or upload
  155. files, messages, jobs, schedules, services, account actions, or external
  156. objects. Reading or fetching remote content is investigation and is allowed;
  157. persisting fetched content into the workspace is a mutation and is not.
  158. Browser tools may navigate, search, filter, and inspect, but must not submit
  159. a mutating form or account action. Delegated tasks must remain research-only
  160. and follow the same mutation boundary. Shell commands may inspect but must
  161. not modify files, Git state, installed packages, or other system state;
  162. running existing builds or tests to verify current behavior counts as
  163. investigation, while installing dependencies or modifying files to make them
  164. run does not.
  165. The sole mutation exception is writing or editing the canonical Plan file at
  166. exactly this path:
  167. ${canonicalPath}
  168. No other file may be created or modified, and Git state must not change.
  169. If a tool is denied, switch to another read or investigation path. When two
  170. distinct approaches to the same question have been blocked, stop pursuing
  171. that question: converge on the evidence already available and record the
  172. remaining uncertainty in the Plan; do not keep looping.
  173. Keep the canonical Plan file up to date as you investigate and decisions
  174. change. The Plan should contain only relevant sections and cover enough
  175. detail for another agent to implement it safely, including:
  176. - goal, scope, and important non-goals;
  177. - current implementation and affected components or files;
  178. - proposed architecture and end-to-end flow;
  179. - relevant state, ownership, concurrency, failure, and recovery semantics;
  180. - tests and acceptance criteria;
  181. - unresolved decisions or risks, if any.
  182. The Plan may begin with one title; its first body section must be a
  183. non-empty \`## Summary\` stating the goal, scope, and key design decisions.
  184. Before calling ExitPlanMode, use a file write or edit tool to create or
  185. update the canonical Plan file at the exact path above. An inline response
  186. does not count as completing the Plan, even if it contains the same content.
  187. Call ExitPlanMode({}) only after the canonical Plan file is complete and
  188. ready for user review. Do not begin implementation after calling
  189. ExitPlanMode.
  190. </system-reminder>`;
  191. }
  192. type PlanLifecycleToolName = 'EnterPlanMode' | 'ExitPlanMode';
  193. type PlanLifecycleToolResult<Name extends PlanLifecycleToolName> = Name extends 'ExitPlanMode'
  194. ? { readonly requestId: string; readonly planPath: string }
  195. : { readonly requestId: string };
  196. function lifecycleTool<Name extends PlanLifecycleToolName>(
  197. name: Name,
  198. action: (input: PlanModeActionInput) => Promise<PlanLifecycleToolResult<Name>>,
  199. ) {
  200. return defineRuntimeTool({
  201. name,
  202. description:
  203. name === 'EnterPlanMode'
  204. ? 'Ask the local user to confirm entering Plan Mode; the turn ends while they decide, and planning starts only after they confirm. Call this as the first tool action for a requested planning deliverable — software or technical implementation planning, or any plan the user wants to approve before implementation or delivery — before reading or unpacking attachments, clarification, research, or drafting. If you only realize mid-task that this applies, call it then: late entry is better than none.'
  205. : 'Freeze the canonical Plan file and ask the local user to review it; the turn ends while they decide. Only valid while Plan Mode is active, after the canonical Plan file has been written to disk — write or update it first.',
  206. schema: EmptyInput,
  207. source: 'builtin',
  208. execute: async (ctx: ToolExecutionContext, _input, signal) => {
  209. const result = await action({
  210. sessionId: ctx.sessionId,
  211. turnId: ctx.turnId,
  212. ...(ctx.toolCallId ? { toolCallId: ctx.toolCallId } : {}),
  213. ...(name === 'ExitPlanMode' && ctx.assistantMessageId
  214. ? { assistantMessageId: ctx.assistantMessageId }
  215. : {}),
  216. signal,
  217. });
  218. const text = `${name} is awaiting the local user's decision. This turn ends now; do not take further actions or produce further output.`;
  219. return {
  220. tool_name: name,
  221. text,
  222. content: [{ type: 'text' as const, text }],
  223. details: {
  224. waiting_for_user: true,
  225. requestId: result.requestId,
  226. ...(name === 'ExitPlanMode'
  227. ? { planPath: (result as PlanLifecycleToolResult<'ExitPlanMode'>).planPath }
  228. : {}),
  229. },
  230. terminate: true,
  231. };
  232. },
  233. });
  234. }