@agimon-ai/doompi-plan 0.0.1-alpha.13 → 0.0.1-alpha.15

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/README.md CHANGED
@@ -1,13 +1,17 @@
1
1
  # @agimon-ai/doompi-plan
2
2
 
3
- Reusable Pi read-only planning mode extension.
3
+ **Planning mode should be a permission boundary, not a polite request.**
4
4
 
5
- Repository read-only planning, plan persistence, and approval handoff. Plan is a minor mode:
6
- it toggles mid-session and reports itself on the shared `MODES` line.
5
+ This package makes the repository read-only while the agent explores, writes a plan to
6
+ disk, and waits for approval. It snapshots the active tools, model, and thinking level on
7
+ the way in and restores them on the way out. If restoration fails, the session stays
8
+ read-only rather than pretending everything is fine.
7
9
 
8
- Part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi), a coding agent that loads
9
- only the skills and tools you name. This package is composed by Doompi and is not usually
10
- installed on its own.
10
+ Plan is a minor mode. It can be turned on halfway through a session, stacks with the other
11
+ modes, and reports its state on the shared `MODES` line.
12
+
13
+ This is part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi). Load it in the
14
+ major modes where read-only planning should be available.
11
15
 
12
16
  ## Install
13
17
 
@@ -17,25 +21,52 @@ npm install @agimon-ai/doompi-plan
17
21
 
18
22
  ## How it loads
19
23
 
20
- Name it in a layer in `.doom/modes.yaml`, then add that layer to a major mode:
24
+ Put the bare package name in a layer, then add that layer to a major mode:
21
25
 
22
26
  ```yaml
23
27
  layers:
24
28
  plan-mode:
25
- packages: ['@agimon-ai/doompi-plan/extensions/doom']
29
+ packages: ['@agimon-ai/doompi-plan']
26
30
 
27
31
  majorMode:
28
32
  dev: [plan-mode]
29
33
  ```
30
34
 
35
+ The package's Pi manifest selects the Doom adapter. Use `/extensions/pi` for the plain Pi
36
+ adapter or `/extensions/doom` when choosing the Doom integration explicitly.
37
+
31
38
  ## Leader
32
39
 
33
- `SPC p p` plans, `SPC p c` cancels, `SPC p d` debugs, `SPC p f` runs the fable flow, once
34
- the extension is loaded.
40
+ - `SPC p p` starts normal read-only planning.
41
+ - `SPC p d` starts debug planning with diagnostic evidence.
42
+ - `SPC p f` starts the repository-aware Fable flow.
43
+ - `SPC p e` exits Plan mode and restores the previous session state.
44
+
45
+ The exit binding appears only while Plan mode is active.
46
+
47
+ ## Plan review
48
+
49
+ When the selected major mode already has a live `ask_user_question` tool, Plan mode keeps
50
+ it available beside the read-only exploration tools. It does not activate an omitted
51
+ `ask-user` layer, and it removes a stale questionnaire name when no live registration
52
+ exists.
53
+
54
+ After `write_plan`, `complete_plan` asks whether to exit or keep planning. In autonomous
55
+ Voice mode the choices are narrated instead of shown in a modal, the turn ends, and the
56
+ next user message carries the decision. Plan mode exits only on an explicit `exit`;
57
+ `continue` keeps the repository read-only for another revision.
58
+
59
+ ## Voice
60
+
61
+ The Doom adapter contributes `activate_plan` and `exit_plan` to the session-scoped Voice
62
+ catalog. They run through the same serialized transitions as the leader bindings and are
63
+ not registered as direct Pi tools. The plain Pi adapter does not publish these Doom
64
+ capabilities.
35
65
 
36
- ## Entry points
66
+ ## Public API
37
67
 
38
- 9 subpaths are declared in the `exports` field of `package.json`.
68
+ Supported subpaths expose the Plan mode, plan storage, tools, flavors, and Pi/Doom adapters.
69
+ See `package.json` for the complete export list.
39
70
 
40
71
  ## License
41
72
 
@@ -1,6 +1,6 @@
1
- const e=require(`../../_virtual/_rolldown/runtime.cjs`),t=require(`../../schemas/plan/config.cjs`),n=require(`./fableFlow.cjs`),r=require(`../../adapters/telemetry/logSinkTelemetry.cjs`),i=require(`../../schemas/plan/planConfig.cjs`),a=require(`./prompts.cjs`);let o=require(`@agimon-ai/doompi-config`),s=require(`node:buffer`),c=require(`node:crypto`),l=require(`node:fs`);l=e.__toESM(l,1);let ee=require(`node:os`);ee=e.__toESM(ee,1);let u=require(`node:path`);u=e.__toESM(u,1);let d=require(`@agimon-ai/doompi-config/configWriter`),f=require(`@agimon-ai/doompi-extension-contracts/fable-plan`),p=require(`@agimon-ai/doompi-extension-contracts/protocol`),te=require(`@agimon-ai/doompi-extension-contracts/subagent-policy`),m=require(`@agimon-ai/doompi-extension-contracts/subagent-tool`),h=require(`@agimon-ai/doompi-ui/config`),g=require(`@agimon-ai/doompi-ui/leader`),_=require(`@agimon-ai/doompi-ui/mode`);const v=`agent-harness-plan-mode`,ne=`agent-harness-plan-document`,y=`complete_plan`,b=`write_plan`,x=`ask_user_question`,S=`bash`,C=`find`,w=`grep`,T=`read`,E=`subagent`,D=`task`,O=`record_debug_evidence`,k=`run_fable_plan`,A=`implementation-plan`,j=`@agimon-ai/doompi-plan`,M=`warning`,re=`info`,N=`Refused to write the plan because its destination is not a regular file.`,P=`plan.trigger`,ie=`plan.model`,F=`plan.flavor`,ae=`not_found`,oe=`unauthenticated`,se=`restore_failed`,ce=new Set,le=5e3,ue=`Exit plan mode and start implementation`,de=new Set([`add_directory`,x,S,y,C,w,`intercom`,`ls`,T,`search_external_files`,E,`subagent_supervisor`,`subagent_wait`,D,b]),I=[T,S,w,C,`ls`],fe=[...I,`mcp`],L=`leader`,R=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],z=[`idle`,`draft`,`review`,`completed`,`failed`,`cancelled`,`interrupted`];function pe(e){return(e.match(/^#\s+(.+?)\s*$/m)?.[1]??A).normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64)||A}function me(e){return`${encodeURIComponent(e).slice(0,48)||`session`}--${(0,c.createHash)(`sha256`).update(e).digest(`hex`)}`}function B(e=new Date,t=(0,c.randomUUID)()){return`${e.toISOString().replace(/[-:]/g,``).replace(/\.\d{3}Z$/,`Z`)}--${t}`}function he(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(!r||typeof r!=`object`)continue;let i=r;if(i.type!==`message`||i.message?.role!==`assistant`||!Array.isArray(i.message.content))continue;let a=i.message.content.findIndex(e=>{if(!e||typeof e!=`object`)return!1;let n=e;return n.type===`toolCall`&&n.id===t&&n.name===b});if(!(a<0))return i.message.content.slice(0,a).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return t.type===`text`&&typeof t.text==`string`?[t.text]:[]}).join(`
1
+ const e=require(`../../_virtual/_rolldown/runtime.cjs`),t=require(`../../schemas/plan/config.cjs`),n=require(`./fableFlow.cjs`),r=require(`../../adapters/telemetry/logSinkTelemetry.cjs`),i=require(`../../schemas/plan/planConfig.cjs`),a=require(`./prompts.cjs`);let o=require(`@agimon-ai/doompi-config`),s=require(`node:buffer`),c=require(`node:crypto`),l=require(`node:fs`);l=e.__toESM(l,1);let ee=require(`node:os`);ee=e.__toESM(ee,1);let te=require(`node:path`);te=e.__toESM(te,1);let u=require(`@agimon-ai/doompi-config/configWriter`),d=require(`@agimon-ai/doompi-extension-contracts/fable-plan`),f=require(`@agimon-ai/doompi-extension-contracts/mode`),ne=require(`@agimon-ai/doompi-extension-contracts/protocol`),p=require(`@agimon-ai/doompi-extension-contracts/subagent-policy`),m=require(`@agimon-ai/doompi-extension-contracts/subagent-tool`),h=require(`@agimon-ai/doompi-extension-contracts/voice-tools`),g=require(`@agimon-ai/doompi-ui/config`),_=require(`@agimon-ai/doompi-ui/leader`),v=require(`@agimon-ai/doompi-user-feedback/voice-question-handoff`);const y=`agent-harness-plan-mode`,re=`agent-harness-plan-document`,b=`complete_plan`,x=`write_plan`,S=`ask_user_question`,C=`bash`,w=`find`,T=`grep`,E=`read`,ie=`subagent`,ae=`task`,oe=`record_debug_evidence`,D=`run_fable_plan`,O=`implementation-plan`,k=`@agimon-ai/doompi-plan`,se=`activate`,ce=`deactivate`,A=`warning`,le=`info`,ue=`Refused to write the plan because its destination is not a regular file.`,j=`plan.trigger`,de=`plan.model`,M=`plan.flavor`,fe=`not_found`,pe=`unauthenticated`,me=`restore_failed`,he=new Set,ge=5e3,_e=`Exit plan mode and start implementation`,ve=`Continue planning`,N=`exit`,ye=`continue`,be={questions:[{question:`Plan complete. What would you like to do?`,header:`Plan review`,options:[{label:_e,description:`Leave read-only plan mode and begin implementing the approved plan.`},{label:ve,description:`Remain in read-only plan mode and refine the implementation plan.`}]}]},xe=new Set([`add_directory`,S,C,b,w,T,`intercom`,`ls`,f.MINOR_MODE_TOOL_NAME,E,`search_external_files`,ie,`subagent_supervisor`,`subagent_wait`,ae,x]),P=new Set([`edit`,`write`,`mcp`]),F=[E,C,T,w,`ls`],Se=[...F,`mcp`],I=`leader`,Ce=`voice_tool`,L=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],R=[`idle`,`draft`,`review`,`completed`,`failed`,`cancelled`,`interrupted`],we=`@agimon-ai/doompi-plan`,z={type:`string`,enum:[...[`normal`,`debug`,`fable`]]},Te={type:`object`,properties:{flavor:z},required:[`flavor`],additionalProperties:!1},Ee={type:`object`,properties:{},additionalProperties:!1},De={type:`object`,properties:{active:{type:`boolean`},flavor:{anyOf:[{...z},{type:`null`}]},changed:{type:`boolean`}},required:[`active`,`flavor`,`changed`],additionalProperties:!1},B=new Set([b,x,oe,D,f.MINOR_MODE_TOOL_NAME,...h.VOICE_FACADE_TOOL_NAMES]);function Oe(e){return(e.match(/^#\s+(.+?)\s*$/m)?.[1]??O).normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64)||O}function ke(e){return`${encodeURIComponent(e).slice(0,48)||`session`}--${(0,c.createHash)(`sha256`).update(e).digest(`hex`)}`}function Ae(e=new Date,t=(0,c.randomUUID)()){return`${e.toISOString().replace(/[-:]/g,``).replace(/\.\d{3}Z$/,`Z`)}--${t}`}function je(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(!r||typeof r!=`object`)continue;let i=r;if(i.type!==`message`||i.message?.role!==`assistant`||!Array.isArray(i.message.content))continue;let a=i.message.content.findIndex(e=>{if(!e||typeof e!=`object`)return!1;let n=e;return n.type===`toolCall`&&n.id===t&&n.name===x});if(!(a<0))return i.message.content.slice(0,a).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return t.type===`text`&&typeof t.text==`string`?[t.text]:[]}).join(`
2
2
 
3
- `).trim()||void 0}}function ge(e){return e.reason instanceof Error?e.reason:Error(`Plan write cancelled.`)}async function V(e,t){if(t.aborted)throw ge(t);let n,r=new Promise((e,r)=>{n=()=>r(ge(t)),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e){return typeof e==`string`}function W(e){if(!(!H(e)||!U(e.provider)||!U(e.id))&&!(!e.provider||!e.id||e.provider.length>128||e.id.length>128))return{provider:e.provider,id:e.id}}function G(e){return U(e)&&R.includes(e)?e:void 0}function K(e){return U(e)&&z.includes(e)?e:void 0}function _e(e){if(!(!Array.isArray(e)||e.some(e=>!U(e))))return e.map(e=>e)}function q(e){if(!H(e))return;let t=_e(e.tools),n=G(e.thinking);if(!t||n===void 0)return;let r=e.model===void 0?void 0:W(e.model);if(!(e.model!==void 0&&!r))return{tools:t,...r?{model:r}:{},thinking:n}}function ve(e){return e===`normal`||e===`debug`||e===`fable`?e:void 0}function ye(e){if(e.version!==2)return;let t=e.activeFlavor===void 0?void 0:ve(e.activeFlavor);if(e.activeFlavor!==void 0&&!t)return;let n=e.originalSnapshot===void 0?void 0:q(e.originalSnapshot);if(e.originalSnapshot!==void 0&&!n)return;let r=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(e.planId!==void 0&&r===void 0)return;let i=e.interruptedFableStage===void 0?void 0:K(e.interruptedFableStage);if(!(e.interruptedFableStage!==void 0&&!i))return{version:2,...t?{activeFlavor:t}:{},...n?{originalSnapshot:n}:{},...r?{planId:r}:{},...i?{interruptedFableStage:i}:{}}}function be(e){if(e.enabled!==!0&&e.enabled!==!1)return;let t=e.toolsBeforePlanMode===void 0?void 0:_e(e.toolsBeforePlanMode);if(e.toolsBeforePlanMode!==void 0&&!t)return;let n=e.modelBeforePlanMode===void 0?void 0:W(e.modelBeforePlanMode);if(e.modelBeforePlanMode!==void 0&&!n)return;let r=e.thinkingBeforePlanMode===void 0?void 0:G(e.thinkingBeforePlanMode);if(e.thinkingBeforePlanMode!==void 0&&r===void 0)return;let i=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(e.planId!==void 0&&i===void 0)return;let a=t&&r!==void 0?{tools:t,...n?{model:n}:{},thinking:r}:void 0;return{version:2,...e.enabled?{activeFlavor:`normal`}:{},...a?{originalSnapshot:a}:{},...i?{planId:i}:{}}}function xe(e){if(H(e))return ye(e)??be(e)}function Se(e){if(!H(e)||!U(e.content)||!U(e.path)||!U(e.sessionId)||!U(e.title)||!U(e.writtenAt))return;let t=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(!(e.planId!==void 0&&t===void 0))return{content:e.content,path:e.path,sessionId:e.sessionId,...t?{planId:t}:{},title:e.title,writtenAt:e.writtenAt}}function J(e,t,n){if(!U(e))throw Error(`${t} must be a string.`);let r=e.trim();if(n&&!r)throw Error(`${t} must not be empty.`);if(s.Buffer.byteLength(r,`utf8`)>4096)throw Error(`${t} exceeds the bounded debug evidence limit.`);return r}function Ce(e,t){if(!Array.isArray(e)||e.length>32)throw Error(`${t} must be a bounded string array.`);return e.map((e,n)=>J(e,`${t}[${n}]`,!1))}function we(e,t){return e===void 0?``:J(e,t,!1)}function Y(e,t){return e===void 0?[]:Ce(e,t)}function Te(e,t,n){let r=new Set(t),i=Object.keys(e).find(e=>!r.has(e));if(i)throw Error(`${n} contains unsupported field '${i}'.`)}function Ee(e){if(!H(e))throw Error(`Debug evidence must be an object.`);Te(e,[`issue`,`expectedBehavior`,`reproductionAttempt`,`actualBehavior`,`logs`,`correlatedTraceEvidence`,`processOutput`,`browserConsoleEvidence`,`correlationIds`,`timestamps`,`verifiedFacts`,`hypotheses`,`unavailableEvidence`],`Debug evidence`);let t={issue:J(e.issue,`issue`,!0),expectedBehavior:we(e.expectedBehavior,`expectedBehavior`),reproductionAttempt:we(e.reproductionAttempt,`reproductionAttempt`),actualBehavior:we(e.actualBehavior,`actualBehavior`),logs:Y(e.logs,`logs`),correlatedTraceEvidence:Y(e.correlatedTraceEvidence,`correlatedTraceEvidence`),processOutput:Y(e.processOutput,`processOutput`),browserConsoleEvidence:Y(e.browserConsoleEvidence,`browserConsoleEvidence`),correlationIds:Y(e.correlationIds,`correlationIds`),timestamps:Y(e.timestamps,`timestamps`),verifiedFacts:Y(e.verifiedFacts,`verifiedFacts`),hypotheses:Y(e.hypotheses,`hypotheses`),unavailableEvidence:Y(e.unavailableEvidence,`unavailableEvidence`)};if(s.Buffer.byteLength(JSON.stringify(t),`utf8`)>32768)throw Error(`Debug evidence exceeds the bounded packet size.`);return t}function De(e,t){let n=new Set(t),r=e.filter(e=>de.has(e)),i=I.filter(e=>n.has(e)),a=[x,y,D,b].filter(e=>n.has(e));return[...new Set([...r,...i,...a])]}function Oe(e,t,n,r){let i=new Set(t),a=De(e,t),o=n===`debug`?[O,...r].filter(e=>i.has(e)):[];return n===`fable`&&i.has(k)&&o.push(k),[...new Set([...a,...o])]}function X(e){if(e.output=!1,e.progress=!1,e.worktree=!1,Array.isArray(e.parallel))for(let t of e.parallel)X(t);else e.parallel&&X(e.parallel)}function ke(e){if(e.action!==void 0){(0,m.isSubagentAction)(e.action)&&(0,m.subagentActionAcceptsField)(e.action,`artifacts`)&&(e.artifacts=!1);return}e.artifacts=!1,e.output=!1,e.share=!1,e.progress=!1,e.worktree=!1,delete e.chainDir,delete e.outputSchema,delete e.sessionDir;for(let t of e.tasks??[])X(t);for(let t of e.chain??[])X(t)}function Ae(e,t){if(!e?.model&&!e?.thinking)return;let n=e.model??(t?`${t.provider}/${t.id}`:void 0);if(n)return e.thinking?`${n.replace(/:(?:off|minimal|low|medium|high|xhigh|max)$/,``)}:${e.thinking}`:n}function je(e,t){if(e.action===`run`)for(let n of e.requests??[])n.model=t}function Me(e,t){e.action===`assign`&&(e.model=t)}function Ne(e){return new Set([`append-step`,`create`,`delete`,`disable`,`eject`,`enable`,`grant-spawn-budget`,`reset`,`schedule`,`schedule-cancel`,`update`,`watchdog.configure`]).has(e??``)}function Pe(e,t){let n=e.indexOf(`/`);if(n>0)return t.modelRegistry.find(e.slice(0,n),e.slice(n+1));let r=t.modelRegistry.getAvailable().filter(t=>t.id===e);return r.find(e=>e.provider===t.model?.provider)??(r.length===1?r[0]:void 0)}function Fe(e=process.env,n=process.cwd()){return t.loadDoomConfig((0,o.loadHarnessState)(e).state.root??n).modes?.planning}function Ie(e){let t={key:`p`,label:`plan`,order:60};return[{id:`plan.normal`,path:[t,{key:`p`,label:`normal`,detail:`read-only planning`}],action:{name:`plan.normal`}},{id:`plan.debug`,path:[t,{key:`d`,label:`debug`,detail:`adaptive debug planning`}],action:{name:`plan.debug`}},{id:`plan.fable`,path:[t,{key:`f`,label:`fable`,detail:`repository-aware draft`}],action:{name:`plan.fable`}},...e?[{id:`plan.exit`,path:[t,{key:`e`,label:`exit`,detail:`restore and exit`}],action:{name:`plan.exit`}}]:[]]}function Le(e,t=Fe,c=r.createPlanTelemetry(),m={}){let x=!1,C,w,T,A,I,R,z=!1,H,U=`idle`,W,G,K,_e=Promise.resolve(),q=m.doomIntegrations??!0,ve=new Set(m.debugDiagnosticTools??ce),ye=(0,f.createFablePlanBrokerClient)(()=>G?.sessionManager.getSessionId()),be=m.fableBroker??{start:(e,t)=>ye.start(e,t),cancel:(e,t)=>ye.cancel({requester:f.FABLE_PLAN_REQUESTER,operationId:e,reason:t})},J=()=>m.fableBroker!==void 0||ye.isAvailable(),Ce=q?(0,_.registerDoomModeContribution)(e,{source:j,id:`plan`,order:40}):{update:()=>void 0},we=q?(0,g.createDoomLeaderContribution)(e,{source:j,bindings:Ie(!1)}):{update:()=>void 0},Y,Te=q?(0,h.registerDoomConfigContribution)(e,{source:j,listSections:()=>{try{return i.planConfigSections(t(),Y)}catch(e){return i.planConfigSections(void 0,e instanceof Error?e.message:String(e))}},handlers:{[h.CONFIG_ACTION.set]:async({fieldId:e,value:t})=>{let n=i.planSettingByFieldId(e);!n||!t||(Y=void 0,await(0,d.setDoomConfigValue)((0,o.globalDoomConfigPath)(),[...n.keyPath],t))},[h.CONFIG_ACTION.clear]:async({fieldId:e})=>{let t=i.planSettingByFieldId(e);t&&(Y=void 0,await(0,d.unsetDoomConfigValue)((0,o.globalDoomConfigPath)(),[...t.keyPath]))}},onError:e=>{Y=e instanceof Error?e.message:String(e)}}):{dispose:()=>void 0,update:()=>void 0};function De(){we.update(Ie(x))}function X(e){De();let t=C,n=x&&t?`plan:${t}`:void 0,r=t===`fable`&&U!==`idle`?` · ${U}`:``;e.ui.setStatus(`plan-mode`,n?e.ui.theme.fg(M,n):void 0),Ce.update(x&&t?{label:`PLAN`,detail:`${t}${r} - read only`,color:M}:void 0)}function Le(){if(!q||!x||!C||!G)return;let t={owner:j,allowedTools:[...fe],requiredTools:[S,`mcp`],allowMcpTools:!0,allowedExternalProfiles:C===`fable`?[n.FABLE_PLAN_PROFILE]:[],denyExtensions:!1};A?A.update(t):A=(0,te.registerSubagentPolicy)((0,p.createProtocolRuntime)({bus:e.events,source:j,sessionId:G.sessionManager.getSessionId()}),t)}function Z(){e.appendEntry(v,{version:2,...x&&C?{activeFlavor:C}:{},...w?{originalSnapshot:{tools:[...w.tools],...w.model?{model:{...w.model}}:{},thinking:w.thinking}}:{},...R?{planId:R}:{},...W?{interruptedFableStage:W}:{}})}function Q(e,t,n){c.recordWarning(r.PLAN_EVENT.modelResolveFailed,`Planning model ${n}: ${t}`,{[ie]:t,"plan.model.phase":e,"plan.model.reason":n})}async function Re(t){let n=T?.main;if(n){if(n.model){let r=Pe(n.model,t);r?await e.setModel(r)||(t.ui.notify(`Planning model is unavailable without authentication: ${n.model}`,M),Q(`apply`,n.model,oe)):(t.ui.notify(`Planning model not found: ${n.model}`,M),Q(`apply`,n.model,ae))}n.thinking&&e.setThinkingLevel(n.thinking)}}async function ze(t,n){if(!n)return!1;if(n.model){let i=`${n.model.provider}/${n.model.id}`,a=t.modelRegistry.find(n.model.provider,n.model.id);if(!a)return t.ui.notify(`Previous model not found: ${i}`,M),Q(`restore`,i,ae),!1;try{if(!await e.setModel(a))return t.ui.notify(`Previous model is unavailable without authentication: ${i}`,M),Q(`restore`,i,oe),!1}catch(e){return t.ui.notify(`Previous model could not be restored: ${i}`,M),Q(`restore`,i,se),c.recordError(r.PLAN_EVENT.modelResolveFailed,e,{[ie]:i,"plan.model.phase":`restore`,"plan.model.reason":se}),!1}}return e.setThinkingLevel(n.thinking),!0}function Be(e){x&&C?e.ui.notify(`Already in plan:${C}.`,re):e.ui.notify(`Plan mode is inactive.`,re)}function $(e){let t=_e.then(e,e);return _e=t.then(()=>void 0,()=>void 0),t}async function Ve(e){if(!K&&!U.match(/^(draft|review)$/u))return;(U===`draft`||U===`review`)&&(W=U),We.cancel(e);let t=K;if(t)try{await t}catch(e){c.recordError(r.PLAN_EVENT.modeDisabled,e,{[F]:`fable`,"plan.fable.reason":`cancel_failed`})}K=void 0,W&&(U=`interrupted`),G&&X(G),Z()}async function He(n,i,a,o){if(G=n,x){if(C===i){Be(n);return}C===`fable`&&await Ve(`Leaving Fable for plan:${i}.`),C=i,Le(),e.setActiveTools(Oe(w?.tools??[],e.getAllTools().map(e=>e.name),i,ve)),X(n),Z(),c.recordEvent(r.PLAN_EVENT.modeEnabled,{[P]:a,[F]:i,"plan.tool.count":e.getActiveTools().length});return}let s;try{s=t()}catch(e){throw c.recordError(r.PLAN_EVENT.configLoadFailed,e,{[P]:a}),e}o?R??=B():(I=void 0,z=!1,R=B(),W=void 0,U=`idle`),T=s,w??={tools:[...e.getActiveTools()],...n.model?{model:{provider:n.model.provider,id:n.model.id}}:{},thinking:e.getThinkingLevel()},x=!0,C=i,e.setActiveTools(Oe(w.tools,e.getAllTools().map(e=>e.name),i,ve)),Le(),await Re(n),X(n),Z(),c.recordEvent(r.PLAN_EVENT.modeEnabled,{[P]:a,[F]:i,"plan.tool.count":e.getActiveTools().length,...T?.main?.model?{[ie]:T.main.model}:{},...T?.main?.thinking?{"plan.thinking":T.main.thinking}:{}})}async function Ue(t,n){if(!x)return Be(t),!1;await Ve(`Plan mode is exiting.`);let i=w;if(!await ze(t,i))return t.ui.notify(`Previous model was not restored. Plan mode remains read-only.`,M),X(t),Z(),c.recordWarning(r.PLAN_EVENT.modeDisabled,`Plan mode restoration failed.`,{[P]:n,[F]:C??`unknown`,"plan.restored":!1}),!1;let a=!!I;return e.setActiveTools([...i?.tools??[]]),A?.dispose(),A=void 0,x=!1,C=void 0,T=void 0,w=void 0,H=void 0,U=`idle`,W=void 0,X(t),Z(),c.recordEvent(r.PLAN_EVENT.modeDisabled,{[P]:n,[F]:`normal`,"plan.written":a,"plan.restored":!0}),!0}let We=n.createFablePlanFlow({broker:be,isAuthorized:()=>x&&C===`fable`&&J(),onStage:e=>{U=e,(e===`completed`||e===`failed`||e===`cancelled`)&&(W=void 0),G&&X(G),x&&Z()},onError:e=>{c.recordError(r.PLAN_EVENT.modeEnabled,e,{[F]:`fable`,"plan.fable.reason":`flow_error`})}});e.registerTool({name:O,label:`Record Debug Evidence`,description:`Record optional bounded debug evidence while planning a repository fix.`,promptSnippet:`Record the issue and any relevant reproduction, logs, traces, process output, or browser evidence`,parameters:{type:`object`,properties:{issue:{type:`string`},expectedBehavior:{type:`string`},reproductionAttempt:{type:`string`},actualBehavior:{type:`string`},logs:{type:`array`,items:{type:`string`}},correlatedTraceEvidence:{type:`array`,items:{type:`string`}},processOutput:{type:`array`,items:{type:`string`}},browserConsoleEvidence:{type:`array`,items:{type:`string`}},correlationIds:{type:`array`,items:{type:`string`}},timestamps:{type:`array`,items:{type:`string`}},verifiedFacts:{type:`array`,items:{type:`string`}},hypotheses:{type:`array`,items:{type:`string`}},unavailableEvidence:{type:`array`,items:{type:`string`}}},required:[`issue`],additionalProperties:!1},async execute(e,t){if(!x||C!==`debug`)return{content:[{type:`text`,text:`Debug planning is not active.`}],details:{recorded:!1}};try{H=Ee(t)}catch(e){throw c.recordWarning(r.PLAN_EVENT.modeEnabled,e,{[F]:`debug`,"plan.debug.reason":`invalid_evidence`}),e}return G&&X(G),{content:[{type:`text`,text:`Debug evidence recorded as optional planning context.`}],details:{recorded:!0}}}}),e.registerTool({name:k,label:`Run Fable Plan`,description:`Send a bounded, sanitized planning packet to the local Fable broker for one repository-aware draft.`,promptSnippet:`Run the local Fable draft with the bounded planning packet`,parameters:{type:`object`,properties:{goal:{type:`array`,items:{type:`string`}},constraints:{type:`array`,items:{type:`string`}},decisions:{type:`array`,items:{type:`string`}},verifiedFindings:{type:`array`,items:{type:`object`}},inferredFindings:{type:`array`,items:{type:`string`}},unresolvedQuestions:{type:`array`,items:{type:`string`}},currentPlan:{type:`string`}},additionalProperties:!1},async execute(e,t,n){if(!x||C!==`fable`)return{content:[{type:`text`,text:`Fable planning is not active.`}],details:{started:!1}};if(!J())return{content:[{type:`text`,text:`The local Fable broker is unavailable. Fable planning remains disabled.`}],details:{started:!1,errorCode:`broker_unavailable`}};let r=We.run(t,n);K=r;try{let e=await r;return{content:[{type:`text`,text:e.draft?`Fable draft:\n${e.draft}`:`Fable planning ${e.status}: ${e.errorCode??`no output`}.`}],details:{...e,started:!0}}}finally{K===r&&(K=void 0)}}}),e.registerTool({name:b,label:`Write Plan`,description:`After presenting the complete implementation plan as Markdown in chat, save that visible plan to a unique Markdown file in the configured plans directory.`,promptSnippet:`Save the implementation plan already presented in chat to the configured plans directory`,parameters:{type:`object`,properties:{},additionalProperties:!1},async execute(t,n,i,a,d){if(!x)return{content:[{type:`text`,text:`Plan mode is disabled. Use normal file tools instead.`}],details:{written:!1}};let f=he(d.sessionManager.getBranch(),t);if(!f){let e=Error(`Present the complete implementation plan as visible Markdown in chat before calling write_plan.`);throw c.recordError(r.PLAN_EVENT.writePlanFailed,e,{"plan.reason":`missing_visible_plan`}),e}let p=Date.now(),te=(0,o.getHarnessState)().root??d.cwd,m=(0,o.resolvePlanningPlansDirectory)(T?.plansDirectory,te,ee.default.homedir()),h=me(d.sessionManager.getSessionId());R??=B();let g=I?.planId===R&&u.default.dirname(I.path)===m?I.path:void 0,_=pe(f),v=R,y=g??u.default.join(m,`${_}--${v}.md`),b=new AbortController,S=Error(`Writing ${y} timed out after ${le}ms.`),C=setTimeout(()=>b.abort(S),le),w=i?AbortSignal.any([i,b.signal]):b.signal,E=`checking`,D=()=>{a?.({content:[{type:`text`,text:`${E===`checking`?`Checking`:`Writing`} ${y}...`}],details:{phase:E,path:y,startedAt:p}})},O=(e,t)=>{c.recordWarning(r.PLAN_EVENT.writePlanUnsafePath,t,{"plan.phase":E,"plan.refusal":e})};try{D();try{await V(()=>l.default.promises.mkdir(m,{recursive:!0,mode:448}),w)}catch(e){throw w.aborted?ge(w):Error(`Could not create the configured plans directory ${m}.`,{cause:e})}let t=await V(()=>l.default.promises.lstat(m),w),n=await V(()=>l.default.promises.realpath(m),w);if(t.isSymbolicLink()||!t.isDirectory())return O(`unsafe_plans_directory`,`Refused to write the plan because the configured path is unsafe.`),{content:[{type:`text`,text:`Refused to write the plan because the configured path is unsafe.`}],details:{written:!1,path:y,phase:E,durationMs:Date.now()-p}};E=`writing`,D();let i;try{for(let e=0;e<3;e+=1)try{let e=g?0:l.default.constants.O_EXCL;i=await V(()=>l.default.promises.open(y,l.default.constants.O_CREAT|l.default.constants.O_WRONLY|l.default.constants.O_NONBLOCK|l.default.constants.O_NOFOLLOW|e,384),w);break}catch(t){if(!(!g&&t instanceof Error&&`code`in t&&String(t.code)===`EEXIST`)||e===2)throw t;v=B(),R=v,y=u.default.join(m,`${_}--${v}.md`),Z()}if(!i)throw Error(`Could not allocate a unique plan filename in ${m}.`);let e=await V(()=>l.default.promises.realpath(m),w),t=await V(()=>i.stat(),w);if(e!==n||!t.isFile()||t.nlink!==1)return O(`invalid_destination`,N),{content:[{type:`text`,text:N}],details:{written:!1,path:y,phase:E,durationMs:Date.now()-p}};await V(()=>i.truncate(0),w),await V(()=>i.writeFile(f,{encoding:`utf8`,signal:w}),w)}catch(e){if(e instanceof Error&&`code`in e&&[`EISDIR`,`ELOOP`,`ENXIO`].includes(String(e.code)))return O(`invalid_destination`,N),{content:[{type:`text`,text:N}],details:{written:!1,path:y,phase:E,durationMs:Date.now()-p}};throw e}finally{await i?.close()}return I={content:f,path:y,sessionId:h,planId:v,title:_,writtenAt:new Date().toISOString()},e.appendEntry(ne,I),z=!0,c.recordEvent(r.PLAN_EVENT.planWritten,{"plan.written":!0,"plan.bytes":s.Buffer.byteLength(f,`utf8`),"plan.duration_ms":Date.now()-p,"plan.revised":!!g}),{content:[{type:`text`,text:`Wrote implementation plan to ${y}.`}],details:{written:!0,path:y,phase:E,durationMs:Date.now()-p}}}catch(e){let t={"plan.phase":E,"plan.duration_ms":Date.now()-p};if(b.signal.aborted&&!i?.aborted){let n=Error(`write_plan timed out during ${E} for ${y}.`,{cause:e});throw c.recordError(r.PLAN_EVENT.writePlanTimedOut,n,{...t,"plan.timeout_ms":le}),n}throw c.recordError(r.PLAN_EVENT.writePlanFailed,e,{...t,"plan.cancelled":i?.aborted??!1}),e}finally{clearTimeout(C)}}}),e.registerTool({name:y,label:`Complete Plan`,description:`Use only after presenting a concrete implementation plan. Ask the user whether to exit plan mode and begin implementation or continue planning.`,promptSnippet:`Ask the user whether to exit plan mode after the implementation plan is complete`,parameters:{type:`object`,properties:{},additionalProperties:!1},async execute(e,t,n,i,a){if(!x)return{content:[{type:`text`,text:`Plan mode is already disabled.`}],details:{exited:!1}};if(!z)return{content:[{type:`text`,text:`Present the complete plan in chat and save it with write_plan before requesting approval.`}],details:{exited:!1}};if(!a.hasUI)return c.recordEvent(r.PLAN_EVENT.planReviewCompleted,{"plan.outcome":`no_ui`}),{content:[{type:`text`,text:`The plan is complete, but this run cannot ask the user interactively. Remain in plan mode until the user uses SPC p e.`}],details:{exited:!1}};let o=await a.ui.select(`Plan complete. What would you like to do?`,[ue,`Continue planning`]);if(c.recordEvent(r.PLAN_EVENT.planReviewCompleted,{"plan.outcome":o===ue?`exited`:`continued`}),o===ue){let e=await $(()=>Ue(a,`plan_approved`));return{content:[{type:`text`,text:e?`The user approved exiting plan mode. Full tool access is restored. Begin implementing the approved plan.`:`The previous model could not be restored. Plan mode remains read-only.`}],details:{exited:e}}}return z=!1,{content:[{type:`text`,text:`The user chose to continue planning. Remain read-only and refine the plan.`}],details:{exited:!1}}}}),q&&(0,g.registerDoomLeaderActionHandlers)(e,{source:j,handlers:{"plan.normal":()=>{let e=G;return e?$(()=>He(e,`normal`,L,!1)):void 0},"plan.exit":()=>{let e=G;return e?$(async()=>{await Ue(e,L)}):void 0},"plan.debug":()=>{let e=G;return e?$(()=>He(e,`debug`,L,!1)):void 0},"plan.fable":()=>{let e=G;return e?$(()=>He(e,`fable`,L,!1)):void 0}},onError:(e,t)=>{G?.hasUI&&G.ui.notify(`Leader action ${t} failed. Plan mode remains read-only.`,M),c.recordError(r.PLAN_EVENT.modeEnabled,e,{[P]:L,"plan.action":t})}}),e.on(`tool_call`,async(e,t)=>{if(!x)return;let n=C===`debug`&&(e.toolName===O||ve.has(e.toolName))||C===`fable`&&e.toolName===k;if(!de.has(e.toolName)&&!n)return{block:!0,reason:`Plan mode blocks the ${e.toolName} tool. Use SPC p e to restore access.`};let r=Ae(T?.subagents,t.model);if(e.toolName===D){r&&Me(e.input,r);return}if(e.toolName!==E)return;let i=e.input;if(Ne(i.action))return{block:!0,reason:`Plan mode blocks subagent management action '${i.action}'. Use SPC p e first.`};ke(i),r&&je(i,r)}),e.on(`before_agent_start`,async(e,t)=>{let n=[];if(x){let e=(0,o.getHarnessState)().root??t.cwd,r=(0,o.resolvePlanningPlansDirectory)(T?.plansDirectory,e,ee.default.homedir());n.push(`[PLAN MODE ACTIVE]\nYou are in repository read-only plan mode. The dedicated write_plan tool may write one unique Markdown plan file under ${r}.\n\nExplore the codebase and produce a concrete implementation plan. For every plan, first call subagent with action "agents", cluster the exploration by independent domain, subsystem, or integration boundary, and create a provisional task graph with the task tool. Select specialized agents by matching their names and descriptions to each cluster. Assign every unblocked delegated task through the task tool, and use a one-shot inlineAgent with a focused systemPrompt when no discovered specialist fits. Treat the initial graph as provisional, not as a fixed contract. After findings arrive, review the entire graph at least once and perform one to three review passes in total. In each pass, use the evidence to add, rewrite, delete, cancel, reassign, or change blockedBy relationships for tasks when warranted. Do not keep following tasks that new information has made stale. Stop revising early when the graph is stable, or after the third pass.\n\nEvery plan must end with a delegated planning-draft stage blocked by all exploration and decision tasks. A single-boundary plan gets one planning draft. A complex plan spanning multiple subsystems, domains, packages, apps, or integration boundaries gets two planning drafts concurrently. Use three concurrent drafts instead when the work is cross-layer, migration-sensitive, security-sensitive, or similarly high risk. Assign each draft through the task tool to the discovered "planner" agent with context "fork" so it receives the conversation and gathered evidence. If the planner agent is unavailable, assign the same draft task through the task tool with a focused inlineAgent. All children receive read, Bash, grep, find, ls, and configured MCP tools with artifacts disabled. Bash and MCP tools are for read-only inspection and must not modify files, external systems, or repository state. Doom Team runs asynchronously, so do not poll. After launch, continue non-overlapping exploration or end your turn; completion notifications wake the parent session.\n\nAfter all planning drafts complete, the main agent must compare the candidates, pick the strongest draft, cross-check it against the gathered evidence and the other drafts, resolve conflicts and gaps, and ask the user only for product decisions. A child produces the draft, but the main agent owns and synthesizes the final plan. Do not modify files or repository state except through write_plan. Start the final plan with a meaningful Markdown H1 because write_plan derives the filename from it. Present the complete plan as visible Markdown in chat, then call write_plan with no arguments. After write_plan succeeds, clear the completed durable task graph and call complete_plan so the user can review the plan and choose whether to begin implementation or continue planning. Do not exit plan mode without that approval.`,a.buildFlavorPlanningPrompt(C,r,H,U))}if(I&&n.push(`[CURRENT PLAN]\nSource: ${I.path}\n\n${I.content}`),n.length!==0)return{systemPrompt:`${e.systemPrompt}\n\n${n.join(`
3
+ `).trim()||void 0}}function Me(e){return e.reason instanceof Error?e.reason:Error(`Plan write cancelled.`)}async function V(e,t){if(t.aborted)throw Me(t);let n,r=new Promise((e,r)=>{n=()=>r(Me(t)),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e){return typeof e==`string`}function W(e){if(!(!H(e)||!U(e.provider)||!U(e.id))&&!(!e.provider||!e.id||e.provider.length>128||e.id.length>128))return{provider:e.provider,id:e.id}}function G(e){return U(e)&&L.includes(e)?e:void 0}function K(e){return U(e)&&R.includes(e)?e:void 0}function Ne(e){if(!(!Array.isArray(e)||e.some(e=>!U(e))))return e.map(e=>e)}function q(e){if(!H(e))return;let t=Ne(e.tools),n=G(e.thinking);if(!t||n===void 0)return;let r=e.model===void 0?void 0:W(e.model);if(!(e.model!==void 0&&!r))return{tools:t,...r?{model:r}:{},thinking:n}}function Pe(e){return e===`normal`||e===`debug`||e===`fable`?e:void 0}function Fe(e){if(e.version!==2)return;let t=e.activeFlavor===void 0?void 0:Pe(e.activeFlavor);if(e.activeFlavor!==void 0&&!t)return;let n=e.originalSnapshot===void 0?void 0:q(e.originalSnapshot);if(e.originalSnapshot!==void 0&&!n)return;let r=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(e.planId!==void 0&&r===void 0)return;let i=e.interruptedFableStage===void 0?void 0:K(e.interruptedFableStage);if(!(e.interruptedFableStage!==void 0&&!i))return{version:2,...t?{activeFlavor:t}:{},...n?{originalSnapshot:n}:{},...r?{planId:r}:{},...i?{interruptedFableStage:i}:{}}}function Ie(e){if(e.enabled!==!0&&e.enabled!==!1)return;let t=e.toolsBeforePlanMode===void 0?void 0:Ne(e.toolsBeforePlanMode);if(e.toolsBeforePlanMode!==void 0&&!t)return;let n=e.modelBeforePlanMode===void 0?void 0:W(e.modelBeforePlanMode);if(e.modelBeforePlanMode!==void 0&&!n)return;let r=e.thinkingBeforePlanMode===void 0?void 0:G(e.thinkingBeforePlanMode);if(e.thinkingBeforePlanMode!==void 0&&r===void 0)return;let i=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(e.planId!==void 0&&i===void 0)return;let a=t&&r!==void 0?{tools:t,...n?{model:n}:{},thinking:r}:void 0;return{version:2,...e.enabled?{activeFlavor:`normal`}:{},...a?{originalSnapshot:a}:{},...i?{planId:i}:{}}}function Le(e){if(H(e))return Fe(e)??Ie(e)}function Re(e){if(!H(e)||!U(e.content)||!U(e.path)||!U(e.sessionId)||!U(e.title)||!U(e.writtenAt))return;let t=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(!(e.planId!==void 0&&t===void 0))return{content:e.content,path:e.path,sessionId:e.sessionId,...t?{planId:t}:{},title:e.title,writtenAt:e.writtenAt}}function ze(e,t,n){if(!U(e))throw Error(`${t} must be a string.`);let r=e.trim();if(n&&!r)throw Error(`${t} must not be empty.`);if(s.Buffer.byteLength(r,`utf8`)>4096)throw Error(`${t} exceeds the bounded debug evidence limit.`);return r}function Be(e,t){if(!Array.isArray(e)||e.length>32)throw Error(`${t} must be a bounded string array.`);return e.map((e,n)=>ze(e,`${t}[${n}]`,!1))}function Ve(e,t){return e===void 0?``:ze(e,t,!1)}function J(e,t){return e===void 0?[]:Be(e,t)}function He(e,t,n){let r=new Set(t),i=Object.keys(e).find(e=>!r.has(e));if(i)throw Error(`${n} contains unsupported field '${i}'.`)}function Ue(e){if(!H(e))throw Error(`Debug evidence must be an object.`);He(e,[`issue`,`expectedBehavior`,`reproductionAttempt`,`actualBehavior`,`logs`,`correlatedTraceEvidence`,`processOutput`,`browserConsoleEvidence`,`correlationIds`,`timestamps`,`verifiedFacts`,`hypotheses`,`unavailableEvidence`],`Debug evidence`);let t={issue:ze(e.issue,`issue`,!0),expectedBehavior:Ve(e.expectedBehavior,`expectedBehavior`),reproductionAttempt:Ve(e.reproductionAttempt,`reproductionAttempt`),actualBehavior:Ve(e.actualBehavior,`actualBehavior`),logs:J(e.logs,`logs`),correlatedTraceEvidence:J(e.correlatedTraceEvidence,`correlatedTraceEvidence`),processOutput:J(e.processOutput,`processOutput`),browserConsoleEvidence:J(e.browserConsoleEvidence,`browserConsoleEvidence`),correlationIds:J(e.correlationIds,`correlationIds`),timestamps:J(e.timestamps,`timestamps`),verifiedFacts:J(e.verifiedFacts,`verifiedFacts`),hypotheses:J(e.hypotheses,`hypotheses`),unavailableEvidence:J(e.unavailableEvidence,`unavailableEvidence`)};if(s.Buffer.byteLength(JSON.stringify(t),`utf8`)>32768)throw Error(`Debug evidence exceeds the bounded packet size.`);return t}function We(e,t){let n=new Set(t),r=e.filter(e=>xe.has(e)&&n.has(e)),i=e.filter(e=>!xe.has(e)&&!P.has(e)&&!B.has(e)&&n.has(e)),a=F.filter(e=>n.has(e)),o=[b,ae,x].filter(e=>n.has(e));return[...new Set([...r,...i,...a,...o])]}function Ge(e,t,n,r,i){let a=new Set(n),o=t.filter(e=>!xe.has(e)&&!P.has(e)&&!B.has(e)),s=We([...new Set([...e,...o])].filter(e=>!B.has(e)),n),c=r===`debug`?[oe,...i].filter(e=>a.has(e)):[];r===`fable`&&a.has(D)&&c.push(D);for(let e of[f.MINOR_MODE_TOOL_NAME,...h.VOICE_FACADE_TOOL_NAMES])t.includes(e)&&a.has(e)&&c.push(e);return[...new Set([...s,...c])]}function Ke(e,t,n){let r=new Set(n),i=new Set(t),a=e.filter(e=>!B.has(e)&&r.has(e)&&(e!==S||i.has(e))),o=t.filter(e=>!xe.has(e)&&!P.has(e)&&!B.has(e)&&r.has(e)),s=[f.MINOR_MODE_TOOL_NAME,...h.VOICE_FACADE_TOOL_NAMES].filter(e=>i.has(e)&&r.has(e));return[...new Set([...a,...o,...s])]}function Y(e){if(e.output=!1,e.progress=!1,e.worktree=!1,Array.isArray(e.parallel))for(let t of e.parallel)Y(t);else e.parallel&&Y(e.parallel)}function qe(e){if(e.action!==void 0){(0,m.isSubagentAction)(e.action)&&(0,m.subagentActionAcceptsField)(e.action,`artifacts`)&&(e.artifacts=!1);return}e.artifacts=!1,e.output=!1,e.share=!1,e.progress=!1,e.worktree=!1,delete e.chainDir,delete e.outputSchema,delete e.sessionDir;for(let t of e.tasks??[])Y(t);for(let t of e.chain??[])Y(t)}function Je(e,t){if(!e?.model&&!e?.thinking)return;let n=e.model??(t?`${t.provider}/${t.id}`:void 0);if(n)return e.thinking?`${n.replace(/:(?:off|minimal|low|medium|high|xhigh|max)$/,``)}:${e.thinking}`:n}function Ye(e,t){if(e.action===`run`)for(let n of e.requests??[])n.model=t}function Xe(e,t){if(e.action===`assign`)for(let n of e.assignments??[])n.model=t}function Ze(e){return new Set([`append-step`,`create`,`delete`,`disable`,`eject`,`enable`,`grant-spawn-budget`,`reset`,`schedule`,`schedule-cancel`,`update`,`watchdog.configure`]).has(e??``)}function Qe(e,t){let n=e.indexOf(`/`);if(n>0)return t.modelRegistry.find(e.slice(0,n),e.slice(n+1));let r=t.modelRegistry.getAvailable().filter(t=>t.id===e);return r.find(e=>e.provider===t.model?.provider)??(r.length===1?r[0]:void 0)}function $e(e=process.env,n=process.cwd()){return t.loadDoomConfig((0,o.loadHarnessState)(e).state.root??n).modes?.planning}function et(e){let t={key:`p`,label:`plan`,order:60};return[{id:`plan.normal`,path:[t,{key:`p`,label:`normal`,detail:`read-only planning`}],action:{name:`plan.normal`}},{id:`plan.debug`,path:[t,{key:`d`,label:`debug`,detail:`adaptive debug planning`}],action:{name:`plan.debug`}},{id:`plan.fable`,path:[t,{key:`f`,label:`fable`,detail:`repository-aware draft`}],action:{name:`plan.fable`}},...e?[{id:`plan.exit`,path:[t,{key:`e`,label:`exit`,detail:`restore and exit`}],action:{name:`plan.exit`}}]:[]]}function X(e,t=$e,c=r.createPlanTelemetry(),m={}){let S=!1,w,T,E,O,P,F,L=!1,R=!1,z,B,U=`idle`,W,G,K,Ne=Promise.resolve(),q=m.doomIntegrations??!0,Fe=new Set(m.debugDiagnosticTools??he),Ie=(0,d.createFablePlanBrokerClient)(()=>G?.sessionManager.getSessionId()),ze=m.fableBroker??{start:(e,t)=>Ie.start(e,t),cancel:(e,t)=>Ie.cancel({requester:d.FABLE_PLAN_REQUESTER,operationId:e,reason:t})},Be=()=>m.fableBroker!==void 0||Ie.isAvailable(),Ve=q?(0,f.registerMinorModeOwner)(e,{descriptor:{source:k,id:`plan`,label:`Plan`,description:`Read-only planning with normal, debug, and Fable flavors.`,order:40,actions:[{id:se,label:`Activate`,description:`Activate plan mode or switch its planning flavor.`,contexts:[`tui`,`headless`],parameters:[{name:`flavor`,label:`Flavor`,kind:`enum`,required:!0,choices:[{value:`normal`,label:`Normal`},{value:`debug`,label:`Debug`},{value:`fable`,label:`Fable`}]}]},{id:ce,label:`Deactivate`,description:`Exit plan mode and restore the previous agent configuration.`,contexts:[`tui`,`headless`],parameters:[]}]},initialState:{activation:`inactive`,condition:`ready`,actions:[{id:se,enabled:!0},{id:ce,enabled:!1,disabledReason:`Plan mode is inactive.`}]},async handleAction(e,t,n){if(e===se){let e=t.flavor;if(e!==`normal`&&e!==`debug`&&e!==`fable`)throw Error(`A valid plan flavor is required.`);return await Q(()=>$(n.context,e,I,!1)),{message:`Plan mode is active with the ${e} flavor.`}}if(e===ce)return{message:await Q(()=>st(n.context,I))?`Plan mode deactivated.`:`Plan mode remains active.`};throw Error(`Unknown plan mode action: ${e}`)},onError:e=>void c.recordError(r.PLAN_EVENT.configLoadFailed,e)}):{publish:()=>void 0},J=q?(0,_.createDoomLeaderContribution)(e,{source:k,bindings:et(!1)}):{update:()=>void 0},He,We=q?(0,g.registerDoomConfigContribution)(e,{source:k,listSections:()=>{try{return i.planConfigSections(t(),He)}catch(e){return i.planConfigSections(void 0,e instanceof Error?e.message:String(e))}},handlers:{[g.CONFIG_ACTION.set]:async({fieldId:e,value:t})=>{let n=i.planSettingByFieldId(e);!n||!t||(He=void 0,await(0,u.setDoomConfigValue)((0,o.globalDoomConfigPath)(),[...n.keyPath],t))},[g.CONFIG_ACTION.clear]:async({fieldId:e})=>{let t=i.planSettingByFieldId(e);t&&(He=void 0,await(0,u.unsetDoomConfigValue)((0,o.globalDoomConfigPath)(),[...t.keyPath]))}},onError:e=>{He=e instanceof Error?e.message:String(e)}}):{dispose:()=>void 0,update:()=>void 0};function Y(){J.update(et(S))}function X(e){Y();let t=w,n=S&&t?`plan:${t}`:void 0,r=t===`fable`&&U!==`idle`?` · ${U}`:``;e.ui.setStatus(`plan-mode`,n?e.ui.theme.fg(A,n):void 0);let i={activation:S?`active`:`inactive`,condition:U===`failed`?`failed`:U===`interrupted`?`degraded`:`ready`,...S&&t?{detail:`${t}${r} - read only`,color:A}:{},actions:[{id:se,enabled:!0},...S?[{id:ce,enabled:!0}]:[{id:ce,enabled:!1,disabledReason:`Plan mode is inactive.`}]]};Ve.publish(i)}function tt(){if(!q||!S||!w||!G)return;let t={owner:k,allowedTools:[...Se],requiredTools:[C,`mcp`],allowMcpTools:!0,allowedExternalProfiles:w===`fable`?[n.FABLE_PLAN_PROFILE]:[],denyExtensions:!1};O?O.update(t):O=(0,p.registerSubagentPolicy)((0,ne.createProtocolRuntime)({bus:e.events,source:k,sessionId:G.sessionManager.getSessionId()}),t)}function Z(){e.appendEntry(y,{version:2,...S&&w?{activeFlavor:w}:{},...T?{originalSnapshot:{tools:[...T.tools],...T.model?{model:{...T.model}}:{},thinking:T.thinking}}:{},...F?{planId:F}:{},...W?{interruptedFableStage:W}:{}})}function nt(e,t,n){c.recordWarning(r.PLAN_EVENT.modelResolveFailed,`Planning model ${n}: ${t}`,{[de]:t,"plan.model.phase":e,"plan.model.reason":n})}async function rt(t){let n=E?.main;if(n){if(n.model){let r=Qe(n.model,t);r?await e.setModel(r)||(t.ui.notify(`Planning model is unavailable without authentication: ${n.model}`,A),nt(`apply`,n.model,pe)):(t.ui.notify(`Planning model not found: ${n.model}`,A),nt(`apply`,n.model,fe))}n.thinking&&e.setThinkingLevel(n.thinking)}}async function it(t,n){if(!n)return!1;if(n.model){let i=`${n.model.provider}/${n.model.id}`,a=t.modelRegistry.find(n.model.provider,n.model.id);if(!a)return t.ui.notify(`Previous model not found: ${i}`,A),nt(`restore`,i,fe),!1;try{if(!await e.setModel(a))return t.ui.notify(`Previous model is unavailable without authentication: ${i}`,A),nt(`restore`,i,pe),!1}catch(e){return t.ui.notify(`Previous model could not be restored: ${i}`,A),nt(`restore`,i,me),c.recordError(r.PLAN_EVENT.modelResolveFailed,e,{[de]:i,"plan.model.phase":`restore`,"plan.model.reason":me}),!1}}return e.setThinkingLevel(n.thinking),!0}function at(e){S&&w?e.ui.notify(`Already in plan:${w}.`,le):e.ui.notify(`Plan mode is inactive.`,le)}function Q(e){let t=Ne.then(e,e);return Ne=t.then(()=>void 0,()=>void 0),t}async function ot(e){if(!K&&!U.match(/^(draft|review)$/u))return;(U===`draft`||U===`review`)&&(W=U),lt.cancel(e);let t=K;if(t)try{await t}catch(e){c.recordError(r.PLAN_EVENT.modeDisabled,e,{[M]:`fable`,"plan.fable.reason":`cancel_failed`})}K=void 0,W&&(U=`interrupted`),G&&X(G),Z()}async function $(n,i,a,o){if(G=n,S){if(w===i){at(n);return}w===`fable`&&await ot(`Leaving Fable for plan:${i}.`),w=i,tt(),e.setActiveTools(Ge(T?.tools??[],e.getActiveTools(),e.getAllTools().map(e=>e.name),i,Fe)),X(n),Z(),c.recordEvent(r.PLAN_EVENT.modeEnabled,{[j]:a,[M]:i,"plan.tool.count":e.getActiveTools().length});return}let s;try{s=t()}catch(e){throw c.recordError(r.PLAN_EVENT.configLoadFailed,e,{[j]:a}),e}o?F??=Ae():(P=void 0,L=!1,R=!1,F=Ae(),W=void 0,U=`idle`),E=s,T??={tools:[...e.getActiveTools()],...n.model?{model:{provider:n.model.provider,id:n.model.id}}:{},thinking:e.getThinkingLevel()},S=!0,w=i,e.setActiveTools(Ge(T.tools,e.getActiveTools(),e.getAllTools().map(e=>e.name),i,Fe)),tt(),await rt(n),X(n),Z(),c.recordEvent(r.PLAN_EVENT.modeEnabled,{[j]:a,[M]:i,"plan.tool.count":e.getActiveTools().length,...E?.main?.model?{[de]:E.main.model}:{},...E?.main?.thinking?{"plan.thinking":E.main.thinking}:{}})}async function st(t,n){if(!S)return at(t),!1;await ot(`Plan mode is exiting.`);let i=T;if(!await it(t,i))return t.ui.notify(`Previous model was not restored. Plan mode remains read-only.`,A),X(t),Z(),c.recordWarning(r.PLAN_EVENT.modeDisabled,`Plan mode restoration failed.`,{[j]:n,[M]:w??`unknown`,"plan.restored":!1}),!1;let a=!!P;return e.setActiveTools(Ke(i?.tools??[],e.getActiveTools(),e.getAllTools().map(e=>e.name))),O?.dispose(),O=void 0,S=!1,w=void 0,E=void 0,R=!1,T=void 0,B=void 0,U=`idle`,W=void 0,X(t),Z(),c.recordEvent(r.PLAN_EVENT.modeDisabled,{[j]:n,[M]:`normal`,"plan.written":a,"plan.restored":!0}),!0}let ct=[];if(q){let t=e,n=e=>{if(e.aborted)throw e.reason instanceof Error?e.reason:Error(`Plan voice transition was cancelled.`)},r={descriptor:{source:we,id:`plan-activate`,name:`activate_plan`,label:`Activate Plan`,description:`Activate or switch the serialized read-only planning mode flavor.`,order:10,inputSchema:Te,resultSchema:De},execute(e,t){let r=Pe(H(e)?e.flavor:void 0);if(!r)throw Error(`A valid plan flavor is required.`);return n(t.signal),Q(async()=>{n(t.signal);let e=S,i=w;return await $(t.context,r,Ce,!1),{active:S,flavor:w??r,changed:e!==S||i!==w}})}},i={descriptor:{source:we,id:`plan-exit`,name:`exit_plan`,label:`Exit Plan`,description:`Exit read-only planning mode and restore the previous agent configuration.`,order:20,inputSchema:Ee,resultSchema:De},execute(e,t){return n(t.signal),Q(async()=>{n(t.signal);let e=S,r=await st(t.context,Ce);return{active:S,flavor:w??null,changed:e!==S||r}})}};ct.push((0,h.registerVoiceToolContribution)(t,r)),ct.push((0,h.registerVoiceToolContribution)(t,i))}let lt=n.createFablePlanFlow({broker:ze,isAuthorized:()=>S&&w===`fable`&&Be(),onStage:e=>{U=e,(e===`completed`||e===`failed`||e===`cancelled`)&&(W=void 0),G&&X(G),S&&Z()},onError:e=>{c.recordError(r.PLAN_EVENT.modeEnabled,e,{[M]:`fable`,"plan.fable.reason":`flow_error`})}});e.registerTool({name:oe,label:`Record Debug Evidence`,description:`Record optional bounded debug evidence while planning a repository fix.`,promptSnippet:`Record the issue and any relevant reproduction, logs, traces, process output, or browser evidence`,parameters:{type:`object`,properties:{issue:{type:`string`},expectedBehavior:{type:`string`},reproductionAttempt:{type:`string`},actualBehavior:{type:`string`},logs:{type:`array`,items:{type:`string`}},correlatedTraceEvidence:{type:`array`,items:{type:`string`}},processOutput:{type:`array`,items:{type:`string`}},browserConsoleEvidence:{type:`array`,items:{type:`string`}},correlationIds:{type:`array`,items:{type:`string`}},timestamps:{type:`array`,items:{type:`string`}},verifiedFacts:{type:`array`,items:{type:`string`}},hypotheses:{type:`array`,items:{type:`string`}},unavailableEvidence:{type:`array`,items:{type:`string`}}},required:[`issue`],additionalProperties:!1},async execute(e,t){if(!S||w!==`debug`)return{content:[{type:`text`,text:`Debug planning is not active.`}],details:{recorded:!1}};try{B=Ue(t)}catch(e){throw c.recordWarning(r.PLAN_EVENT.modeEnabled,e,{[M]:`debug`,"plan.debug.reason":`invalid_evidence`}),e}return G&&X(G),{content:[{type:`text`,text:`Debug evidence recorded as optional planning context.`}],details:{recorded:!0}}}}),e.registerTool({name:D,label:`Run Fable Plan`,description:`Send a bounded, sanitized planning packet to the local Fable broker for one repository-aware draft.`,promptSnippet:`Run the local Fable draft with the bounded planning packet`,parameters:{type:`object`,properties:{goal:{type:`array`,items:{type:`string`}},constraints:{type:`array`,items:{type:`string`}},decisions:{type:`array`,items:{type:`string`}},verifiedFindings:{type:`array`,items:{type:`object`}},inferredFindings:{type:`array`,items:{type:`string`}},unresolvedQuestions:{type:`array`,items:{type:`string`}},currentPlan:{type:`string`}},additionalProperties:!1},async execute(e,t,n){if(!S||w!==`fable`)return{content:[{type:`text`,text:`Fable planning is not active.`}],details:{started:!1}};if(!Be())return{content:[{type:`text`,text:`The local Fable broker is unavailable. Fable planning remains disabled.`}],details:{started:!1,errorCode:`broker_unavailable`}};let r=lt.run(t,n);K=r;try{let e=await r;return{content:[{type:`text`,text:e.draft?`Fable draft:\n${e.draft}`:`Fable planning ${e.status}: ${e.errorCode??`no output`}.`}],details:{...e,started:!0}}}finally{K===r&&(K=void 0)}}}),e.registerTool({name:x,label:`Write Plan`,description:`After presenting the complete implementation plan as Markdown in chat, save that visible plan to a unique Markdown file in the configured plans directory.`,promptSnippet:`Save the implementation plan already presented in chat to the configured plans directory`,parameters:{type:`object`,properties:{},additionalProperties:!1},async execute(t,n,i,a,u){if(!S)return{content:[{type:`text`,text:`Plan mode is disabled. Use normal file tools instead.`}],details:{written:!1}};let d=je(u.sessionManager.getBranch(),t);if(!d){let e=Error(`Present the complete implementation plan as visible Markdown in chat before calling write_plan.`);throw c.recordError(r.PLAN_EVENT.writePlanFailed,e,{"plan.reason":`missing_visible_plan`}),e}let f=Date.now(),ne=(0,o.getHarnessState)().root??u.cwd,p=(0,o.resolvePlanningPlansDirectory)(E?.plansDirectory,ne,ee.default.homedir()),m=ke(u.sessionManager.getSessionId());F??=Ae();let h=P?.planId===F&&te.default.dirname(P.path)===p?P.path:void 0,g=Oe(d),_=F,v=h??te.default.join(p,`${g}--${_}.md`),y=new AbortController,b=Error(`Writing ${v} timed out after ${ge}ms.`),x=setTimeout(()=>y.abort(b),ge),C=i?AbortSignal.any([i,y.signal]):y.signal,w=`checking`,T=()=>{a?.({content:[{type:`text`,text:`${w===`checking`?`Checking`:`Writing`} ${v}...`}],details:{phase:w,path:v,startedAt:f}})},ie=(e,t)=>{c.recordWarning(r.PLAN_EVENT.writePlanUnsafePath,t,{"plan.phase":w,"plan.refusal":e})};try{T();try{await V(()=>l.default.promises.mkdir(p,{recursive:!0,mode:448}),C)}catch(e){throw C.aborted?Me(C):Error(`Could not create the configured plans directory ${p}.`,{cause:e})}let t=await V(()=>l.default.promises.lstat(p),C),n=await V(()=>l.default.promises.realpath(p),C);if(t.isSymbolicLink()||!t.isDirectory())return ie(`unsafe_plans_directory`,`Refused to write the plan because the configured path is unsafe.`),{content:[{type:`text`,text:`Refused to write the plan because the configured path is unsafe.`}],details:{written:!1,path:v,phase:w,durationMs:Date.now()-f}};w=`writing`,T();let i;try{for(let e=0;e<3;e+=1)try{let e=h?0:l.default.constants.O_EXCL;i=await V(()=>l.default.promises.open(v,l.default.constants.O_CREAT|l.default.constants.O_WRONLY|l.default.constants.O_NONBLOCK|l.default.constants.O_NOFOLLOW|e,384),C);break}catch(t){if(!(!h&&t instanceof Error&&`code`in t&&String(t.code)===`EEXIST`)||e===2)throw t;_=Ae(),F=_,v=te.default.join(p,`${g}--${_}.md`),Z()}if(!i)throw Error(`Could not allocate a unique plan filename in ${p}.`);let e=await V(()=>l.default.promises.realpath(p),C),t=await V(()=>i.stat(),C);if(e!==n||!t.isFile()||t.nlink!==1)return ie(`invalid_destination`,ue),{content:[{type:`text`,text:ue}],details:{written:!1,path:v,phase:w,durationMs:Date.now()-f}};await V(()=>i.truncate(0),C),await V(()=>i.writeFile(d,{encoding:`utf8`,signal:C}),C)}catch(e){if(e instanceof Error&&`code`in e&&[`EISDIR`,`ELOOP`,`ENXIO`].includes(String(e.code)))return ie(`invalid_destination`,ue),{content:[{type:`text`,text:ue}],details:{written:!1,path:v,phase:w,durationMs:Date.now()-f}};throw e}finally{await i?.close()}return P={content:d,path:v,sessionId:m,planId:_,title:g,writtenAt:new Date().toISOString()},e.appendEntry(re,P),L=!0,R=!1,c.recordEvent(r.PLAN_EVENT.planWritten,{"plan.written":!0,"plan.bytes":s.Buffer.byteLength(d,`utf8`),"plan.duration_ms":Date.now()-f,"plan.revised":!!h}),{content:[{type:`text`,text:`Wrote implementation plan to ${v}.`}],details:{written:!0,path:v,phase:w,durationMs:Date.now()-f}}}catch(e){let t={"plan.phase":w,"plan.duration_ms":Date.now()-f};if(y.signal.aborted&&!i?.aborted){let n=Error(`write_plan timed out during ${w} for ${v}.`,{cause:e});throw c.recordError(r.PLAN_EVENT.writePlanTimedOut,n,{...t,"plan.timeout_ms":ge}),n}throw c.recordError(r.PLAN_EVENT.writePlanFailed,e,{...t,"plan.cancelled":i?.aborted??!1}),e}finally{clearTimeout(x)}}});async function ut(e,t){if(c.recordEvent(r.PLAN_EVENT.planReviewCompleted,{"plan.outcome":e===N?`exited`:`continued`}),e===N){let e=await Q(()=>st(t,`plan_approved`));return{content:[{type:`text`,text:e?`The user approved exiting plan mode. Full tool access is restored. Begin implementing the approved plan.`:`The previous model could not be restored. Plan mode remains read-only.`}],details:{exited:e}}}return L=!1,{content:[{type:`text`,text:`The user chose to continue planning. Remain read-only and refine the plan.`}],details:{exited:!1}}}e.registerTool({name:b,label:`Complete Plan`,description:`Present the saved implementation plan for exit-or-continue approval. Interactive sessions use the normal selector; autonomous voice narrates a plain-text handoff and waits for the next user message.`,promptSnippet:`Request explicit exit-or-continue approval after the saved plan has been presented`,promptGuidelines:[`After write_plan succeeds, call complete_plan without a decision so it can present the review question.`,`When autonomous voice returns an awaiting-response result, stop. Interpret the next ordinary user message, then call complete_plan again with decision "exit" or "continue".`,`Never pass decision "${N}" without the user explicitly choosing "${_e}".`],parameters:{type:`object`,properties:{decision:{type:`string`,enum:[N,ye]}},additionalProperties:!1},async execute(e,t,n,i,a){if(!S)return{content:[{type:`text`,text:`Plan mode is already disabled.`}],details:{exited:!1}};if(!L)return{content:[{type:`text`,text:`Present the complete plan in chat and save it with write_plan before requesting approval.`}],details:{exited:!1}};if(!a.hasUI)return c.recordEvent(r.PLAN_EVENT.planReviewCompleted,{"plan.outcome":`no_ui`}),{content:[{type:`text`,text:`The plan is complete, but this run cannot ask the user interactively. Remain in plan mode until the user uses SPC p e.`}],details:{exited:!1}};let o=H(t)?t.decision:void 0,s=o===N||o===ye;if(R){if(!s)throw Error(`The narrated plan review is waiting for an explicit exit or continue decision.`);return R=!1,ut(o,a)}if(o!==void 0)throw Error(`Call complete_plan without a decision before submitting a narrated plan-review answer.`);let l=z?.handoff(be);return l?(R=!0,(0,v.buildVoiceToolResult)(l)):ut(await a.ui.select(`Plan complete. What would you like to do?`,[_e,ve])===_e?N:ye,a)}}),q&&(0,_.registerDoomLeaderActionHandlers)(e,{source:k,handlers:{"plan.normal":()=>{let e=G;return e?Q(()=>$(e,`normal`,I,!1)):void 0},"plan.exit":()=>{let e=G;return e?Q(async()=>{await st(e,I)}):void 0},"plan.debug":()=>{let e=G;return e?Q(()=>$(e,`debug`,I,!1)):void 0},"plan.fable":()=>{let e=G;return e?Q(()=>$(e,`fable`,I,!1)):void 0}},onError:(e,t)=>{G?.hasUI&&G.ui.notify(`Leader action ${t} failed. Plan mode remains read-only.`,A),c.recordError(r.PLAN_EVENT.modeEnabled,e,{[j]:I,"plan.action":t})}}),e.on(`tool_call`,async(e,t)=>{if(!S)return;let n=w===`debug`&&(e.toolName===oe||Fe.has(e.toolName))||w===`fable`&&e.toolName===D;if(!xe.has(e.toolName)&&!n)return{block:!0,reason:`Plan mode blocks the ${e.toolName} tool. Use SPC p e to restore access.`};let r=Je(E?.subagents,t.model);if(e.toolName===ae){r&&Xe(e.input,r);return}if(e.toolName!==ie)return;let i=e.input;if(Ze(i.action))return{block:!0,reason:`Plan mode blocks subagent management action '${i.action}'. Use SPC p e first.`};qe(i),r&&Ye(i,r)}),e.on(`before_agent_start`,async(e,t)=>{let n=[];if(S){let e=(0,o.getHarnessState)().root??t.cwd,r=(0,o.resolvePlanningPlansDirectory)(E?.plansDirectory,e,ee.default.homedir());n.push(`[PLAN MODE ACTIVE]\nYou are in repository read-only plan mode. The dedicated write_plan tool may write one unique Markdown plan file under ${r}.\n\nExplore the codebase and produce a concrete implementation plan. For every plan, first call subagent with action "agents", cluster the exploration by independent domain, subsystem, or integration boundary, and create a provisional task graph with the task tool. Select specialized agents by matching their names and descriptions to each cluster. Assign every unblocked delegated task through the task tool, and use a one-shot inlineAgent with a focused systemPrompt when no discovered specialist fits. Treat the initial graph as provisional, not as a fixed contract. After findings arrive, review the entire graph at least once and perform one to three review passes in total. In each pass, use the evidence to add, rewrite, delete, cancel, reassign, or change blockedBy relationships for tasks when warranted. Do not keep following tasks that new information has made stale. Stop revising early when the graph is stable, or after the third pass.\n\nEvery plan must end with a delegated planning-draft stage blocked by all exploration and decision tasks. A single-boundary plan gets one planning draft. A complex plan spanning multiple subsystems, domains, packages, apps, or integration boundaries gets two planning drafts concurrently. Use three concurrent drafts instead when the work is cross-layer, migration-sensitive, security-sensitive, or similarly high risk. Assign each draft through the task tool to the discovered "planner" agent with context "fork" so it receives the conversation and gathered evidence. If the planner agent is unavailable, assign the same draft task through the task tool with a focused inlineAgent. All children receive read, Bash, grep, find, ls, and configured MCP tools with artifacts disabled. Bash and MCP tools are for read-only inspection and must not modify files, external systems, or repository state. Doom Team runs asynchronously, so do not poll. After launch, continue non-overlapping exploration or end your turn; completion notifications wake the parent session.\n\nAfter all planning drafts complete, the main agent must compare the candidates, pick the strongest draft, cross-check it against the gathered evidence and the other drafts, resolve conflicts and gaps, and ask the user only for product decisions. A child produces the draft, but the main agent owns and synthesizes the final plan. Do not modify files or repository state except through write_plan. Start the final plan with a meaningful Markdown H1 because write_plan derives the filename from it. Present the complete plan as visible Markdown in chat, then call write_plan with no arguments. After write_plan succeeds, clear the completed durable task graph and call complete_plan without a decision. In an interactive text session, complete_plan uses the normal exit-or-continue selector. Under autonomous voice, it displays and narrates the choices without opening a blocking dialog, then ends the turn. Interpret the user's next ordinary message and call complete_plan again with decision "exit" or "continue". Do not exit plan mode without explicit approval.`,a.buildFlavorPlanningPrompt(w,r,B,U))}if(P&&n.push(`[CURRENT PLAN]\nSource: ${P.path}\n\n${P.content}`),n.length!==0)return{systemPrompt:`${e.systemPrompt}\n\n${n.join(`
4
4
 
5
- `)}`}}),e.on(`context`,async e=>({messages:e.messages.filter(e=>e.customType!==`agent-harness-plan-mode-context`)})),e.on(`session_start`,async(t,n)=>{let r=n.sessionManager.getEntries(),i=r.flatMap(e=>e.type===`custom`&&e.customType===v?[xe(e.data)]:[]).filter(e=>e!==void 0).at(-1),a=me(n.sessionManager.getSessionId()),o=r.flatMap(e=>e.type===`custom`&&e.customType===ne?[Se(e.data)]:[]).filter(e=>e!==void 0).at(-1),s=w;if(A?.dispose(),A=void 0,I=o?.sessionId===a?o:void 0,R=i?.planId??I?.planId,z=!1,T=void 0,H=void 0,x=!1,C=void 0,De(),w=i?.originalSnapshot,W=i?.interruptedFableStage,U=W?`interrupted`:`idle`,G=n,i?.activeFlavor)await He(n,i.activeFlavor,`session_restore`,!0);else{let t=i?.originalSnapshot??s;t?await ze(n,t)&&e.setActiveTools([...t.tools]):e.setActiveTools(e.getActiveTools().filter(e=>e!==y&&e!==b&&e!==O&&e!==k)),w=void 0,X(n)}}),e.on(`session_shutdown`,async(t,n)=>{await Ve(`Plan host session is shutting down.`),x&&w&&await ze(n,w)&&e.setActiveTools([...w.tools]),A?.dispose(),A=void 0,Te.dispose(),G=void 0,await c.shutdown()})}exports.WRITE_PLAN_TIMEOUT_MS=le,exports.configurePlanningSubagentInput=je,exports.configurePlanningTaskInput=Me,exports.constrainSubagentInput=ke,exports.createPlanIdentifier=B,exports.isBlockedSubagentManagementAction=Ne,exports.loadPlanningModeConfig=Fe,exports.parseDebugEvidencePacket=Ee,exports.parsePersistedPlanState=xe,exports.planModeExtension=Le,exports.planModeTools=De,exports.planSessionIdentifier=me,exports.planTitleSlug=pe,exports.planningSubagentModel=Ae,exports.visiblePlanForToolCall=he;
5
+ `)}`}}),e.on(`context`,async e=>({messages:e.messages.filter(e=>e.customType!==`agent-harness-plan-mode-context`)})),e.on(`session_start`,async(t,n)=>{let r=n.sessionManager.getEntries(),i=r.flatMap(e=>e.type===`custom`&&e.customType===y?[Le(e.data)]:[]).filter(e=>e!==void 0).at(-1),a=n.sessionManager.getSessionId(),o=ke(a);z?.dispose(),z=q?(0,v.createVoiceQuestionHandoff)({bus:e.events,source:k,sessionId:a}):void 0;let s=r.flatMap(e=>e.type===`custom`&&e.customType===re?[Re(e.data)]:[]).filter(e=>e!==void 0).at(-1),c=T;if(O?.dispose(),O=void 0,P=s?.sessionId===o?s:void 0,F=i?.planId??P?.planId,L=!1,R=!1,E=void 0,B=void 0,S=!1,w=void 0,Y(),T=i?.originalSnapshot,W=i?.interruptedFableStage,U=W?`interrupted`:`idle`,G=n,i?.activeFlavor)await $(n,i.activeFlavor,`session_restore`,!0);else{let t=i?.originalSnapshot??c;t?await it(n,t)&&e.setActiveTools(Ke(t.tools,e.getActiveTools(),e.getAllTools().map(e=>e.name))):e.setActiveTools(e.getActiveTools().filter(e=>e!==b&&e!==x&&e!==oe&&e!==D)),T=void 0,X(n)}}),e.on(`session_shutdown`,async(t,n)=>{await ot(`Plan host session is shutting down.`),S&&T&&await it(n,T)&&e.setActiveTools(Ke(T.tools,e.getActiveTools(),e.getAllTools().map(e=>e.name))),O?.dispose(),O=void 0,z?.dispose(),z=void 0,R=!1,We.dispose();for(let e of ct)e.dispose();G=void 0,await c.shutdown()})}exports.WRITE_PLAN_TIMEOUT_MS=ge,exports.configurePlanningSubagentInput=Ye,exports.configurePlanningTaskInput=Xe,exports.constrainSubagentInput=qe,exports.createPlanIdentifier=Ae,exports.isBlockedSubagentManagementAction=Ze,exports.loadPlanningModeConfig=$e,exports.parseDebugEvidencePacket=Ue,exports.parsePersistedPlanState=Le,exports.planModeExtension=X,exports.planModeTools=We,exports.planSessionIdentifier=ke,exports.planTitleSlug=Oe,exports.planningSubagentModel=Je,exports.visiblePlanForToolCall=je;
6
6
  //# sourceMappingURL=planMode.cjs.map