@agimon-ai/doompi-plan 0.0.1-alpha.16 → 0.0.1-alpha.18
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 +8 -16
- package/dist/services/plan/planMode.cjs +2 -2
- package/dist/services/plan/planMode.cjs.map +1 -1
- package/dist/services/plan/planMode.d.cts.map +1 -1
- package/dist/services/plan/planMode.d.mts.map +1 -1
- package/dist/services/plan/planMode.mjs +1 -1
- package/dist/services/plan/planMode.mjs.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -10,8 +10,8 @@ read-only rather than pretending everything is fine.
|
|
|
10
10
|
Plan is a minor mode. It can be turned on halfway through a session, stacks with the other
|
|
11
11
|
modes, and reports its state on the shared `MODES` line.
|
|
12
12
|
|
|
13
|
-
This is part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi).
|
|
14
|
-
|
|
13
|
+
This is part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi). Doompi includes
|
|
14
|
+
it as a battery-provided minor mode in every major mode; it stays inactive until requested.
|
|
15
15
|
|
|
16
16
|
## Install
|
|
17
17
|
|
|
@@ -21,21 +21,13 @@ npm install @agimon-ai/doompi-plan
|
|
|
21
21
|
|
|
22
22
|
## How it loads
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
Doompi loads the Doom adapter as part of its battery-included minor-mode closure. Do not add
|
|
25
|
+
Plan to `.doom/modes.yaml`: major modes select always-active capabilities, while Plan is
|
|
26
|
+
available on demand and contributes no active model tools until Plan mode starts.
|
|
25
27
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
packages: ['@agimon-ai/doompi-plan']
|
|
30
|
-
|
|
31
|
-
majorMode:
|
|
32
|
-
dev:
|
|
33
|
-
description: Development mode with structured planning support.
|
|
34
|
-
layers: [plan-mode]
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
The package's Pi manifest selects the Doom adapter. Use `/extensions/pi` for the plain Pi
|
|
38
|
-
adapter or `/extensions/doom` when choosing the Doom integration explicitly.
|
|
28
|
+
When embedding the package outside Doompi, its Pi manifest selects the Doom adapter. Use
|
|
29
|
+
`/extensions/pi` for the plain Pi adapter or `/extensions/doom` when choosing the Doom
|
|
30
|
+
integration explicitly.
|
|
39
31
|
|
|
40
32
|
## Leader
|
|
41
33
|
|
|
@@ -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 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.
|
|
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,...h.VOICE_MODE_TOOL_NAMES,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_MODE_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 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(`
|
|
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_MODE_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_MODE_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
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
|