@agimon-ai/doompi-plan 0.0.1-alpha.49 → 0.0.1-alpha.50
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/dist/services/planMode.cjs +2 -2
- package/dist/services/planMode.cjs.map +1 -1
- package/dist/services/planMode.mjs +2 -2
- package/dist/services/planMode.mjs.map +1 -1
- package/dist/types/planSettings.cjs +1 -1
- package/dist/types/planSettings.cjs.map +1 -1
- package/dist/types/planSettings.mjs +1 -1
- package/dist/types/planSettings.mjs.map +1 -1
- package/package.json +6 -6
- package/src/types/planSettings.ts +5 -5
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../schemas/plan/config.cjs"),n=require("./fableFlow.cjs"),r=require("../adapters/node/planPointer.cjs"),i=require("../adapters/telemetry/logSinkTelemetry.cjs"),a=require("../schemas/plan/planConfig.cjs"),o=require("../types/planApi.cjs"),s=require("./prompts.cjs");let c=require("@agimon-ai/doompi-config"),ee=require("node:buffer"),l=require("node:crypto"),u=require("node:fs");u=e.__toESM(u,1);let te=require("node:os");te=e.__toESM(te,1);let ne=require("node:path");ne=e.__toESM(ne,1);let d=require("@agimon-ai/doompi-config/configWriter"),re=require("@agimon-ai/doompi-extension-contracts/config"),f=require("@agimon-ai/doompi-extension-contracts/fable-plan"),p=require("@agimon-ai/doompi-extension-contracts/mode"),m=require("@agimon-ai/doompi-extension-contracts/narration"),ie=require("@agimon-ai/doompi-extension-contracts/subagent-policy"),h=require("@agimon-ai/doompi-extension-contracts/subagent-tool"),g=require("@agimon-ai/doompi-extension-contracts/voice-tools"),_=require("@agimon-ai/doompi-extension-contracts/ui-hub");const ae=`agent-harness-plan-mode`,oe=`agent-harness-plan-document`,v=`complete_plan`,y=`write_plan`,b=`ask_user_question`,x=`bash`,S=`find`,C=`grep`,se=`read`,ce=`subagent`,le=`task`,ue=`record_debug_evidence`,de=`run_fable_plan`,w=`implementation-plan`,T=`@agimon-ai/doompi-plan`,fe=`activate`,pe=`deactivate`,E=`warning`,me=`info`,he=`Refused to write the plan because its destination is not a regular file.`,ge=`plan.trigger`,_e=`plan.model`,D=`plan.flavor`,ve=`not_found`,ye=`unauthenticated`,be=`restore_failed`,xe=new Set,Se=5e3,Ce=`Exit plan mode and start implementation`,we=`Continue planning`,O=`exit`,Te=`continue`,Ee=[`Plan complete. What would you like to do?`,` 1. ${Ce}`,` 2. ${we}`,` Type something.`].join(`
|
|
2
2
|
`),De=(0,m.createNarrationRequest)(`Plan complete. What would you like to do? Options: 1, ${Ce}; 2, ${we}. Please choose one option. You may also answer in your own words.`),Oe=new Set([`add_directory`,b,x,v,S,C,`intercom`,`ls`,p.MINOR_MODE_TOOL_NAME,...g.VOICE_MODE_TOOL_NAMES,se,`search_external_files`,ce,`subagent_supervisor`,`subagent_wait`,le,y]),k=new Set([`edit`,`write`,`mcp`]),A=[se,x,C,S,`ls`],ke=[...A,`mcp`],j=`leader`,Ae=`voice_tool`,M=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],je=[`idle`,`draft`,`review`,`completed`,`failed`,`cancelled`,`interrupted`],Me=`@agimon-ai/doompi-plan`,Ne={type:`string`,enum:[`normal`,`debug`,`fable`]},Pe={type:`object`,properties:{flavor:Ne},required:[`flavor`],additionalProperties:!1},Fe={type:`object`,properties:{},additionalProperties:!1},Ie={type:`object`,properties:{active:{type:`boolean`},flavor:{anyOf:[{...Ne},{type:`null`}]},changed:{type:`boolean`}},required:[`active`,`flavor`,`changed`],additionalProperties:!1},Le=new Set([v,y,ue,de,p.MINOR_MODE_TOOL_NAME,...g.VOICE_MODE_TOOL_NAMES]);function Re(e){return(e.match(/^#\s+(.+?)\s*$/m)?.[1]??w).normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64)||w}function ze(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function Be(e){return`${encodeURIComponent(e).slice(0,48)||`session`}--${(0,l.createHash)(`sha256`).update(e).digest(`hex`)}`}function Ve(e=new Date,t=(0,l.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===y});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(`
|
|
3
3
|
|
|
4
|
-
`).trim()||void 0}}function Ue(e){return e.reason instanceof Error?e.reason:Error(`Plan write cancelled.`)}async function N(e,t){if(t.aborted)throw Ue(t);let n,r=new Promise((e,r)=>{n=()=>r(Ue(t)),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return typeof e==`string`}function I(e){if(!(!P(e)||!F(e.provider)||!F(e.id))&&!(!e.provider||!e.id||e.provider.length>128||e.id.length>128))return{provider:e.provider,id:e.id}}function L(e){return F(e)&&M.includes(e)?e:void 0}function R(e){return F(e)&&je.includes(e)?e:void 0}function z(e){if(!(!Array.isArray(e)||e.some(e=>!F(e))))return e.map(e=>e)}function We(e){if(!P(e))return;let t=z(e.tools),n=L(e.thinking);if(!t||n===void 0)return;let r=e.model===void 0?void 0:I(e.model);if(!(e.model!==void 0&&!r))return{tools:t,...r?{model:r}:{},thinking:n}}function Ge(e){return e===`normal`||e===`debug`||e===`fable`?e:void 0}function B(e){if(e.version!==2)return;let t=e.activeFlavor===void 0?void 0:Ge(e.activeFlavor);if(e.activeFlavor!==void 0&&!t)return;let n=e.originalSnapshot===void 0?void 0:We(e.originalSnapshot);if(e.originalSnapshot!==void 0&&!n)return;let r=e.planId===void 0?void 0:F(e.planId)?e.planId:void 0;if(e.planId!==void 0&&r===void 0)return;let i=e.interruptedFableStage===void 0?void 0:R(e.interruptedFableStage);if(!(e.interruptedFableStage!==void 0&&!i))return{version:2,...t?{activeFlavor:t}:{},...n?{originalSnapshot:n}:{},...r?{planId:r}:{},...i?{interruptedFableStage:i}:{}}}function V(e){if(e.enabled!==!0&&e.enabled!==!1)return;let t=e.toolsBeforePlanMode===void 0?void 0:z(e.toolsBeforePlanMode);if(e.toolsBeforePlanMode!==void 0&&!t)return;let n=e.modelBeforePlanMode===void 0?void 0:I(e.modelBeforePlanMode);if(e.modelBeforePlanMode!==void 0&&!n)return;let r=e.thinkingBeforePlanMode===void 0?void 0:L(e.thinkingBeforePlanMode);if(e.thinkingBeforePlanMode!==void 0&&r===void 0)return;let i=e.planId===void 0?void 0:F(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 Ke(e){if(P(e))return B(e)??V(e)}function qe(e){if(!P(e)||!F(e.content)||!F(e.path)||!F(e.sessionId)||!F(e.title)||!F(e.writtenAt))return;let t=e.planId===void 0?void 0:F(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 H(e,t,n){if(!F(e))throw Error(`${t} must be a string.`);let r=e.trim();if(n&&!r)throw Error(`${t} must not be empty.`);if(ee.Buffer.byteLength(r,`utf8`)>4096)throw Error(`${t} exceeds the bounded debug evidence limit.`);return r}function U(e,t){if(!Array.isArray(e)||e.length>32)throw Error(`${t} must be a bounded string array.`);return e.map((e,n)=>H(e,`${t}[${n}]`,!1))}function W(e,t){return e===void 0?``:H(e,t,!1)}function G(e,t){return e===void 0?[]:U(e,t)}function Je(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 Ye(e){if(!P(e))throw Error(`Debug evidence must be an object.`);Je(e,[`issue`,`expectedBehavior`,`reproductionAttempt`,`actualBehavior`,`logs`,`correlatedTraceEvidence`,`processOutput`,`browserConsoleEvidence`,`correlationIds`,`timestamps`,`verifiedFacts`,`hypotheses`,`unavailableEvidence`],`Debug evidence`);let t={issue:H(e.issue,`issue`,!0),expectedBehavior:W(e.expectedBehavior,`expectedBehavior`),reproductionAttempt:W(e.reproductionAttempt,`reproductionAttempt`),actualBehavior:W(e.actualBehavior,`actualBehavior`),logs:G(e.logs,`logs`),correlatedTraceEvidence:G(e.correlatedTraceEvidence,`correlatedTraceEvidence`),processOutput:G(e.processOutput,`processOutput`),browserConsoleEvidence:G(e.browserConsoleEvidence,`browserConsoleEvidence`),correlationIds:G(e.correlationIds,`correlationIds`),timestamps:G(e.timestamps,`timestamps`),verifiedFacts:G(e.verifiedFacts,`verifiedFacts`),hypotheses:G(e.hypotheses,`hypotheses`),unavailableEvidence:G(e.unavailableEvidence,`unavailableEvidence`)};if(ee.Buffer.byteLength(JSON.stringify(t),`utf8`)>32768)throw Error(`Debug evidence exceeds the bounded packet size.`);return t}function Xe(e,t){let n=new Set(t),r=e.filter(e=>Oe.has(e)&&n.has(e)),i=e.filter(e=>!Oe.has(e)&&!k.has(e)&&!Le.has(e)&&n.has(e)),a=A.filter(e=>n.has(e)),o=[v,le,y].filter(e=>n.has(e));return[...new Set([...r,...i,...a,...o])]}function Ze(e,t,n,r,i){let a=new Set(n),o=t.filter(e=>!Oe.has(e)&&!k.has(e)&&!Le.has(e)),s=Xe([...new Set([...e,...o])].filter(e=>!Le.has(e)),n),c=r===`debug`?[ue,...i].filter(e=>a.has(e)):[];r===`fable`&&a.has(de)&&c.push(de);for(let e of[p.MINOR_MODE_TOOL_NAME,...g.VOICE_MODE_TOOL_NAMES])t.includes(e)&&a.has(e)&&c.push(e);return[...new Set([...s,...c])]}function Qe(e,t,n){let r=new Set(n),i=new Set(t),a=e.filter(e=>!Le.has(e)&&r.has(e)&&(e!==b||i.has(e))),o=t.filter(e=>!Oe.has(e)&&!k.has(e)&&!Le.has(e)&&r.has(e)),s=[p.MINOR_MODE_TOOL_NAME,...g.VOICE_MODE_TOOL_NAMES].filter(e=>i.has(e)&&r.has(e));return[...new Set([...a,...o,...s])]}function K(e){if(e.output=!1,e.progress=!1,e.worktree=!1,Array.isArray(e.parallel))for(let t of e.parallel)K(t);else e.parallel&&K(e.parallel)}function $e(e){if(e.action!==void 0){(0,h.isSubagentAction)(e.action)&&(0,h.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??[])K(t);for(let t of e.chain??[])K(t)}function et(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 tt(e,t){if(e.action===`run`)for(let n of e.requests??[])n.model=t}function nt(e,t){if(e.action===`assign`)for(let n of e.assignments??[])n.model=t}function rt(e){return new Set([`append-step`,`create`,`delete`,`disable`,`eject`,`enable`,`grant-spawn-budget`,`reset`,`schedule`,`schedule-cancel`,`update`,`watchdog.configure`]).has(e??``)}function it(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 at(e=process.env,n=process.cwd()){return t.loadDoomConfig((0,c.loadHarnessState)(e).state.root??n).modes?.planning}function ot(e){let t={key:`p`,label:`plan`,detail:`read-only planning modes`,order:60};return[e?{id:`plan.exit`,path:[t,{key:`e`,label:`exit`,detail:`restore and exit`,tone:`exit`}],action:{name:`plan.exit`}}:{id:`plan.normal`,path:[t,{key:`e`,label:`enter`,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`}}]}function q(e,t,l=at,h=i.createPlanTelemetry(),b={}){let S=!0,C=0,se,w,k,A,M,je,Ne,Le=()=>{let e=Ne?.modelRegistry;return e?e.getAvailable().filter(t=>e.hasConfiguredAuth(t)).map(e=>({provider:e.provider,id:e.id})):[]},F=!1,I,L,R,z,We,B,V,H,U=!1,W=!1,G=!1,Je,Xe,K=`idle`,q,J,Y,st,ct=Promise.resolve(),lt=b.doomIntegrations??!0,ut=b.planPointers??new r.NodePlanPointerAdapter,dt=new Set(b.debugDiagnosticTools??xe),ft=new AbortController;e.effect(()=>()=>_t(),`${T}/runtime`);let pt=b.fableBroker??{start:(e,t)=>{let n=B;if(!n)throw Error(`The session-bound Fable broker is unavailable.`);return n.start(e,t)},cancel:(e,t)=>{B?.cancel({requester:f.FABLE_PLAN_REQUESTER,operationId:e,reason:t})}},mt=()=>b.fableBroker!==void 0||B!==void 0;e.inject([f.DOOM_FABLE_PLAN_SERVICE],e=>{let t=(0,f.readDoomFablePlanService)(e);if(t)return B=t,()=>{B===t&&(B=void 0,Y&&st?.cancel(`The Team Fable service was unloaded.`))}}),e.inject([ie.DOOM_SUBAGENT_POLICY_SERVICE],e=>{let t=(0,ie.readDoomSubagentPolicyService)(e);if(t)return We=t,St(),()=>{We===t&&(z?.dispose(),z=void 0,We=void 0)}}),lt&&(e.inject([p.DOOM_MINOR_MODE_CATALOG_SERVICE,m.DOOM_NARRATION_SERVICE],e=>{let t={modes:(0,p.requireMinorModeCatalog)(e),narration:(0,m.requireDoomNarrationService)(e)};return Je=t,()=>{Je===t&&(Je=void 0)}}),e.inject([p.DOOM_MINOR_MODE_CATALOG_SERVICE],e=>{let t=(0,p.registerMinorModeOwner)((0,p.requireMinorModeCatalog)(e),{descriptor:{source:T,id:`plan`,label:`Plan`,description:`Read-only planning with normal, debug, and Fable flavors.`,order:40,actions:[{id:fe,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:pe,label:`Deactivate`,description:`Exit plan mode and restore the previous agent configuration.`,contexts:[`tui`,`headless`],parameters:[]}]},initialState:yt(),async handleAction(e,t,n){if(!S)throw Error(`Plan runtime is disposed.`);if(e===fe){let e=t.flavor;if(e!==`normal`&&e!==`debug`&&e!==`fable`)throw Error(`A valid plan flavor is required.`);return await $(()=>Ot(n.context,e,j,!1)),{message:`Plan mode is active with the ${e} flavor.`}}if(e===pe)return{message:await $(()=>kt(n.context,j))?`Plan mode deactivated.`:`Plan mode remains active.`};throw Error(`Unknown plan mode action: ${e}`)},onError:e=>void h.recordError(i.PLAN_EVENT.configLoadFailed,e)});return w=t,()=>{t.dispose(),w===t&&(w=void 0)}}),e.inject([_.DOOM_UI_HUB_SERVICE],e=>{let t=(0,_.requireDoomUiHub)(e),n=t.registerLeader({source:T,bindings:ot(F)}),r=t.registerConfig({source:T,listSections:()=>{let e=Le();try{return a.planConfigSections(l(),je,e)}catch(t){return a.planConfigSections(void 0,t instanceof Error?t.message:String(t),e)}},handlers:{[re.CONFIG_ACTION.set]:async({fieldId:e,value:t})=>{let n=a.planSettingByFieldId(e);!n||!t||(je=void 0,await(0,d.setDoomConfigValue)((0,c.globalDoomConfigPath)(),[...n.keyPath],t))},[re.CONFIG_ACTION.clear]:async({fieldId:e})=>{let t=a.planSettingByFieldId(e);t&&(je=void 0,await(0,d.unsetDoomConfigValue)((0,c.globalDoomConfigPath)(),[...t.keyPath]))}},onError:e=>{S&&(je=e instanceof Error?e.message:String(e))}});return k=n,A=r,()=>{r.dispose(),n.dispose(),A===r&&(A=void 0),k===n&&(k=void 0)}}));function X(e=C){if(!S||e!==C)throw Error(`Plan runtime is disposed or stale.`)}async function ht(){let e=Je;if(!e||!e.modes.list().some(e=>e.descriptor.source===m.DOOM_VOICE_SOURCE&&e.descriptor.id===m.DOOM_VOICE_AUTO_MODE_ID&&e.state.activation===`active`))return!1;try{return await e.narration.request(De),!0}catch(e){return h.recordWarning(i.PLAN_EVENT.planReviewCompleted,e,{"plan.outcome":`narration_failed`}),!1}}function gt(){return{content:[{type:`text`,text:`${Ee}\n\nThe choices were spoken through autonomous voice. Stop now and wait for the user's next message; it will arrive as an ordinary user message.`}],details:{answers:[],awaitingResponse:!0,cancelled:!1,delivery:`voice`,voicePrompt:Ee},terminate:!0}}function _t(){return se??=(async()=>{S=!1,C+=1,ft.abort(Error(`Plan runtime is shutting down.`));let e=J,n=L,r=[];st?.cancel(`Plan runtime is shutting down.`);let i=[ct,...Y?[Y]:[]],a=await Promise.allSettled(i);for(let e of a)e.status===`rejected`&&r.push(e.reason);if(F&&n&&e)try{await Tt(e,n,!0)&&t.setActiveTools(Qe(n.tools,t.getActiveTools(),t.getAllTools().map(e=>e.name)))}catch(e){r.push(e)}let o=[()=>xt(e),()=>z?.dispose(),()=>M?.(),()=>A?.dispose(),()=>k?.dispose(),()=>w?.dispose()];for(let e of o)try{e()}catch(e){r.push(e)}z=void 0,Je=void 0,M=void 0,A=void 0,k=void 0,w=void 0,Y=void 0,J=void 0,G=!1,F=!1,I=void 0,L=void 0,R=void 0;try{await h.shutdown()}catch(e){r.push(e)}if(r.length>0)throw AggregateError(r,`Plan runtime cleanup failed.`)})(),se}function vt(){S&&k?.update(ot(F))}function yt(){let e=I,t=e===`fable`&&K!==`idle`?` · ${K}`:``;return{activation:F?`active`:`inactive`,condition:K===`failed`?`failed`:K===`interrupted`?`degraded`:`ready`,...F&&e?{detail:`${e}${t} - read only`,color:E,modelContextVariant:e}:{},actions:[{id:fe,enabled:!0},...F?[{id:pe,enabled:!0}]:[{id:pe,enabled:!1,disabledReason:`Plan mode is inactive.`}]]}}function Z(e){if(!S)return;vt();let t=I,n=F&&t?`plan:${t}`:void 0;e.ui.setStatus(`plan-mode`,n?e.ui.theme.fg(E,n):void 0),w?.publish(yt())}function bt(e,t){try{ut.write(e.sessionManager.getSessionId(),{path:t.path,title:t.title,writtenAt:t.writtenAt,...t.planId===void 0?{}:{planId:t.planId}})}catch(e){h.recordWarning(i.PLAN_EVENT.planPointerFailed,`The plan pointer was not recorded.`,{"plan.reason":e instanceof Error?e.name:`unknown`})}e.hasUI&&(e.ui.setStatus(o.PLAN_STATUS_KEY,o.formatPlanStatus(t.title,ze(t.writtenAt))),W=!0)}function xt(e){if(e){try{ut.clear(e.sessionManager.getSessionId())}catch{}W&&(W=!1,e.hasUI&&e.ui.setStatus(o.PLAN_STATUS_KEY,void 0))}}function St(){if(!S||!lt||!F||!I||!J)return;let e=[...ke],t={owner:T,allowedTools:e,requiredTools:[x,`mcp`],allowMcpTools:!0,allowedExternalProfiles:I===`fable`?[n.FABLE_PLAN_PROFILE]:[],denyExtensions:!1};z?z.update(t):z=We?.register(t)}function Q(){S&&t.appendEntry(ae,{version:2,...F&&I?{activeFlavor:I}:{},...L?{originalSnapshot:{tools:[...L.tools],...L.model?{model:{...L.model}}:{},thinking:L.thinking}}:{},...H?{planId:H}:{},...q?{interruptedFableStage:q}:{}})}function Ct(e,t,n){h.recordWarning(i.PLAN_EVENT.modelResolveFailed,`Planning model ${n}: ${t}`,{[_e]:t,"plan.model.phase":e,"plan.model.reason":n})}async function wt(e){let n=C;X(n);let r=R?.main;if(r){if(r.model){let i=it(r.model,e);if(!i)e.ui.notify(`Planning model not found: ${r.model}`,E),Ct(`apply`,r.model,ve);else{let a=await t.setModel(i);X(n),a||(e.ui.notify(`Planning model is unavailable without authentication: ${r.model}`,E),Ct(`apply`,r.model,ye))}}X(n),r.thinking&&t.setThinkingLevel(r.thinking)}}async function Tt(e,n,r=!1){let a=C;if(r||X(a),!n)return!1;if(n.model){let o=`${n.model.provider}/${n.model.id}`,s=e.modelRegistry.find(n.model.provider,n.model.id);if(!s)return e.ui.notify(`Previous model not found: ${o}`,E),Ct(`restore`,o,ve),!1;try{let n=await t.setModel(s);if(r||X(a),!n)return e.ui.notify(`Previous model is unavailable without authentication: ${o}`,E),Ct(`restore`,o,ye),!1}catch(t){return r||X(a),e.ui.notify(`Previous model could not be restored: ${o}`,E),Ct(`restore`,o,be),h.recordError(i.PLAN_EVENT.modelResolveFailed,t,{[_e]:o,"plan.model.phase":`restore`,"plan.model.reason":be}),!1}}return r||X(a),t.setThinkingLevel(n.thinking),!0}function Et(e){F&&I?e.ui.notify(`Already in plan:${I}.`,me):e.ui.notify(`Plan mode is inactive.`,me)}function $(e){let t=C,n=async()=>{X(t);let n=await e();return X(t),n},r=ct.then(n,n);return ct=r.then(()=>void 0,()=>void 0),r}async function Dt(e){let t=C;if(X(t),!Y&&!K.match(/^(draft|review)$/u))return;(K===`draft`||K===`review`)&&(q=K),st?.cancel(e);let n=Y;if(n)try{await n,X(t)}catch(e){X(t),h.recordError(i.PLAN_EVENT.modeDisabled,e,{[D]:`fable`,"plan.fable.reason":`cancel_failed`})}X(t),Y=void 0,q&&(K=`interrupted`),J&&Z(J),Q()}async function Ot(e,n,r,a){let o=C;if(X(o),J=e,F){if(I===n){Et(e);return}I===`fable`&&await Dt(`Leaving Fable for plan:${n}.`),X(o),I=n,St(),t.setActiveTools(Ze(L?.tools??[],t.getActiveTools(),t.getAllTools().map(e=>e.name),n,dt)),Z(e),Q(),h.recordEvent(i.PLAN_EVENT.modeEnabled,{[ge]:r,[D]:n,"plan.tool.count":t.getActiveTools().length});return}let s;try{s=l()}catch(e){throw h.recordError(i.PLAN_EVENT.configLoadFailed,e,{[ge]:r}),e}a?H??=Ve():(V=void 0,U=!1,G=!1,H=Ve(),q=void 0,K=`idle`),R=s,L??={tools:[...t.getActiveTools()],...e.model?{model:{provider:e.model.provider,id:e.model.id}}:{},thinking:t.getThinkingLevel()},F=!0,I=n,t.setActiveTools(Ze(L.tools,t.getActiveTools(),t.getAllTools().map(e=>e.name),n,dt)),St(),await wt(e),X(o),Z(e),Q(),h.recordEvent(i.PLAN_EVENT.modeEnabled,{[ge]:r,[D]:n,"plan.tool.count":t.getActiveTools().length,...R?.main?.model?{[_e]:R.main.model}:{},...R?.main?.thinking?{"plan.thinking":R.main.thinking}:{}})}async function kt(e,n){let r=C;if(X(r),!F)return Et(e),!1;await Dt(`Plan mode is exiting.`),X(r);let a=L,o=await Tt(e,a);if(X(r),!o)return e.ui.notify(`Previous model was not restored. Plan mode remains read-only.`,E),Z(e),Q(),h.recordWarning(i.PLAN_EVENT.modeDisabled,`Plan mode restoration failed.`,{[ge]:n,[D]:I??`unknown`,"plan.restored":!1}),!1;let s=!!V;return t.setActiveTools(Qe(a?.tools??[],t.getActiveTools(),t.getAllTools().map(e=>e.name))),z?.dispose(),z=void 0,F=!1,I=void 0,R=void 0,G=!1,L=void 0,Xe=void 0,K=`idle`,q=void 0,Z(e),Q(),h.recordEvent(i.PLAN_EVENT.modeDisabled,{[ge]:n,[D]:`normal`,"plan.written":s,"plan.restored":!0}),!0}if(lt){let t=e=>{if(X(),e.aborted)throw e.reason instanceof Error?e.reason:Error(`Plan voice transition was cancelled.`)},n={descriptor:{source:Me,id:`plan-activate`,name:`activate_plan`,label:`Activate Plan`,description:`Activate or switch the serialized read-only planning mode flavor.`,order:10,inputSchema:Pe,resultSchema:Ie},execute(e,n){let r=Ge(P(e)?e.flavor:void 0);if(!r)throw Error(`A valid plan flavor is required.`);return t(n.signal),$(async()=>{t(n.signal);let e=F,i=I;return await Ot(n.context,r,Ae,!1),{active:F,flavor:I??r,changed:e!==F||i!==I}})}},r={descriptor:{source:Me,id:`plan-exit`,name:`exit_plan`,label:`Exit Plan`,description:`Exit read-only planning mode and restore the previous agent configuration.`,order:20,inputSchema:Fe,resultSchema:Ie},execute(e,n){return t(n.signal),$(async()=>{t(n.signal);let e=F,r=await kt(n.context,Ae);return{active:F,flavor:I??null,changed:e!==F||r}})}};e.inject([g.DOOM_VOICE_TOOLS_SERVICE],e=>{let t=(0,g.requireDoomVoiceToolsService)(e),i=t.register(n),a=t.register(r);return()=>{a.dispose(),i.dispose()}})}st=n.createFablePlanFlow({broker:pt,isAuthorized:()=>S&&F&&I===`fable`&&mt(),onStage:e=>{S&&(K=e,(e===`completed`||e===`failed`||e===`cancelled`)&&(q=void 0),J&&Z(J),F&&Q())},onError:e=>{S&&h.recordError(i.PLAN_EVENT.modeEnabled,e,{[D]:`fable`,"plan.fable.reason":`flow_error`})}}),t.registerTool({name:ue,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(),!F||I!==`debug`)return{content:[{type:`text`,text:`Debug planning is not active.`}],details:{recorded:!1}};try{Xe=Ye(t)}catch(e){throw h.recordWarning(i.PLAN_EVENT.modeEnabled,e,{[D]:`debug`,"plan.debug.reason":`invalid_evidence`}),e}return J&&Z(J),{content:[{type:`text`,text:`Debug evidence recorded as optional planning context.`}],details:{recorded:!0}}}}),t.registerTool({name:de,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){let r=C;if(X(r),!F||I!==`fable`)return{content:[{type:`text`,text:`Fable planning is not active.`}],details:{started:!1}};if(!mt())return{content:[{type:`text`,text:`The local Fable broker is unavailable. Fable planning remains disabled.`}],details:{started:!1,errorCode:`broker_unavailable`}};let i=st;if(!i)throw Error(`Fable planning flow is unavailable.`);let a=i.run(t,n);Y=a;try{let e=await a;return X(r),{content:[{type:`text`,text:e.draft?`Fable draft:\n${e.draft}`:`Fable planning ${e.status}: ${e.errorCode??`no output`}.`}],details:{...e,started:!0}}}finally{S&&r===C&&Y===a&&(Y=void 0)}}}),t.registerTool({name:y,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(e,n,r,a,o){let s=C;if(X(s),!F)return{content:[{type:`text`,text:`Plan mode is disabled. Use normal file tools instead.`}],details:{written:!1}};let l=He(o.sessionManager.getBranch(),e);if(!l){let e=Error(`Present the complete implementation plan as visible Markdown in chat before calling write_plan.`);throw h.recordError(i.PLAN_EVENT.writePlanFailed,e,{"plan.reason":`missing_visible_plan`}),e}let d=Date.now(),re=(0,c.getHarnessState)().root??o.cwd,f=(0,c.resolvePlanningPlansDirectory)(R?.plansDirectory,re,te.default.homedir()),p=Be(o.sessionManager.getSessionId());H??=Ve();let m=V?.planId===H&&ne.default.dirname(V.path)===f?V.path:void 0,ie=Re(l),g=H,_=m??ne.default.join(f,`${ie}--${g}.md`),ae=new AbortController,v=Error(`Writing ${_} timed out after ${Se}ms.`),y=setTimeout(()=>ae.abort(v),Se),b=AbortSignal.any([ae.signal,ft.signal,...r?[r]:[]]),x=`checking`,se=()=>{a?.({content:[{type:`text`,text:`${x===`checking`?`Checking`:`Writing`} ${_}...`}],details:{phase:x,path:_,startedAt:d}})},ce=(e,t)=>{h.recordWarning(i.PLAN_EVENT.writePlanUnsafePath,t,{"plan.phase":x,"plan.refusal":e})};try{se();try{await N(()=>u.default.promises.mkdir(f,{recursive:!0,mode:448}),b)}catch(e){throw b.aborted?Ue(b):Error(`Could not create the configured plans directory ${f}.`,{cause:e})}let e=await N(()=>u.default.promises.lstat(f),b),n=await N(()=>u.default.promises.realpath(f),b);if(e.isSymbolicLink()||!e.isDirectory())return ce(`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:_,phase:x,durationMs:Date.now()-d}};X(s),x=`writing`,se();let r;try{for(let e=0;e<3;e+=1)try{let e=m?0:u.default.constants.O_EXCL;r=await N(()=>u.default.promises.open(_,u.default.constants.O_CREAT|u.default.constants.O_WRONLY|u.default.constants.O_NONBLOCK|u.default.constants.O_NOFOLLOW|e,384),b);break}catch(t){if(!(!m&&t instanceof Error&&`code`in t&&String(t.code)===`EEXIST`)||e===2)throw t;g=Ve(),H=g,_=ne.default.join(f,`${ie}--${g}.md`),Q()}if(!r)throw Error(`Could not allocate a unique plan filename in ${f}.`);let e=await N(()=>u.default.promises.realpath(f),b),t=await N(()=>r.stat(),b);if(e!==n||!t.isFile()||t.nlink!==1)return ce(`invalid_destination`,he),{content:[{type:`text`,text:he}],details:{written:!1,path:_,phase:x,durationMs:Date.now()-d}};await N(()=>r.truncate(0),b),await N(()=>r.writeFile(l,{encoding:`utf8`,signal:b}),b)}catch(e){if(e instanceof Error&&`code`in e&&[`EISDIR`,`ELOOP`,`ENXIO`].includes(String(e.code)))return ce(`invalid_destination`,he),{content:[{type:`text`,text:he}],details:{written:!1,path:_,phase:x,durationMs:Date.now()-d}};throw e}finally{await r?.close()}return X(s),V={content:l,path:_,sessionId:p,planId:g,title:ie,writtenAt:new Date().toISOString()},t.appendEntry(oe,V),bt(o,V),U=!0,G=!1,h.recordEvent(i.PLAN_EVENT.planWritten,{"plan.written":!0,"plan.bytes":ee.Buffer.byteLength(l,`utf8`),"plan.duration_ms":Date.now()-d,"plan.revised":!!m}),{content:[{type:`text`,text:`Wrote implementation plan to ${_}.`}],details:{written:!0,path:_,phase:x,durationMs:Date.now()-d}}}catch(e){if(!S||s!==C)throw Ue(ft.signal);let t={"plan.phase":x,"plan.duration_ms":Date.now()-d};if(ae.signal.aborted&&!r?.aborted){let n=Error(`write_plan timed out during ${x} for ${_}.`,{cause:e});throw h.recordError(i.PLAN_EVENT.writePlanTimedOut,n,{...t,"plan.timeout_ms":Se}),n}throw h.recordError(i.PLAN_EVENT.writePlanFailed,e,{...t,"plan.cancelled":r?.aborted??!1}),e}finally{clearTimeout(y)}}});async function At(e,t){if(X(),h.recordEvent(i.PLAN_EVENT.planReviewCompleted,{"plan.outcome":e===O?`exited`:`continued`}),e===O){let e=await $(()=>kt(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 U=!1,{content:[{type:`text`,text:`The user chose to continue planning. Remain read-only and refine the plan.`}],details:{exited:!1}}}t.registerTool({name:v,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 "${O}" without the user explicitly choosing "${Ce}".`],parameters:{type:`object`,properties:{decision:{type:`string`,enum:[O,Te]}},additionalProperties:!1},async execute(e,t,n,r,a){let o=C;if(X(o),!F)return{content:[{type:`text`,text:`Plan mode is already disabled.`}],details:{exited:!1}};if(!U)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 h.recordEvent(i.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 s=P(t)?t.decision:void 0,c=s===O||s===Te;if(G){if(!c)throw Error(`The narrated plan review is waiting for an explicit exit or continue decision.`);return G=!1,At(s,a)}if(s!==void 0)throw Error(`Call complete_plan without a decision before submitting a narrated plan-review answer.`);if(await ht())return X(o),G=!0,gt();let ee=await a.ui.select(`Plan complete. What would you like to do?`,[Ce,we]);return X(o),At(ee===Ce?O:Te,a)}}),lt&&e.inject([_.DOOM_UI_HUB_SERVICE],e=>{let t=(0,_.requireDoomUiHub)(e).registerLeaderActions({source:T,handlers:{"plan.normal":()=>{let e=S?J:void 0;return e?$(()=>Ot(e,`normal`,j,!1)):void 0},"plan.exit":()=>{let e=S?J:void 0;return e?$(async()=>{await kt(e,j)}):void 0},"plan.debug":()=>{let e=S?J:void 0;return e?$(()=>Ot(e,`debug`,j,!1)):void 0},"plan.fable":()=>{let e=S?J:void 0;return e?$(()=>Ot(e,`fable`,j,!1)):void 0}},onError:(e,t)=>{S&&(J?.hasUI&&J.ui.notify(`Leader action ${t} failed. Plan mode remains read-only.`,E),h.recordError(i.PLAN_EVENT.modeEnabled,e,{[ge]:j,"plan.action":t}))}});return M=t,()=>{t(),M===t&&(M=void 0)}}),t.on(`tool_call`,async(e,t)=>{if(!S||!F)return;let n=I===`debug`&&(e.toolName===ue||dt.has(e.toolName))||I===`fable`&&e.toolName===de;if(!Oe.has(e.toolName)&&!n)return{block:!0,reason:`Plan mode blocks the ${e.toolName} tool. Use SPC p e to restore access.`};let r=et(R?.subagents,t.model);if(e.toolName===le){r&&nt(e.input,r);return}if(e.toolName!==ce)return;let i=e.input;if(rt(i.action))return{block:!0,reason:`Plan mode blocks subagent management action '${i.action}'. Use SPC p e first.`};$e(i),r&&tt(i,r)}),t.on(`before_agent_start`,async(e,t)=>{if(!S)return;let n=[];if(F){let e=(0,c.getHarnessState)().root??t.cwd,r=(0,c.resolvePlanningPlansDirectory)(R?.plansDirectory,e,te.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.`,s.buildFlavorPlanningPrompt(I,r,Xe,K))}if(V){let e=V.content;try{e=await u.default.promises.readFile(V.path,`utf8`)}catch{e=V.content}n.push(`[CURRENT PLAN]\nSource: ${V.path}\n\n${e}`)}if(n.length!==0)return{systemPrompt:`${e.systemPrompt}\n\n${n.join(`
|
|
4
|
+
`).trim()||void 0}}function Ue(e){return e.reason instanceof Error?e.reason:Error(`Plan write cancelled.`)}async function N(e,t){if(t.aborted)throw Ue(t);let n,r=new Promise((e,r)=>{n=()=>r(Ue(t)),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return typeof e==`string`}function I(e){if(!(!P(e)||!F(e.provider)||!F(e.id))&&!(!e.provider||!e.id||e.provider.length>128||e.id.length>128))return{provider:e.provider,id:e.id}}function L(e){return F(e)&&M.includes(e)?e:void 0}function R(e){return F(e)&&je.includes(e)?e:void 0}function z(e){if(!(!Array.isArray(e)||e.some(e=>!F(e))))return e.map(e=>e)}function We(e){if(!P(e))return;let t=z(e.tools),n=L(e.thinking);if(!t||n===void 0)return;let r=e.model===void 0?void 0:I(e.model);if(!(e.model!==void 0&&!r))return{tools:t,...r?{model:r}:{},thinking:n}}function Ge(e){return e===`normal`||e===`debug`||e===`fable`?e:void 0}function B(e){if(e.version!==2)return;let t=e.activeFlavor===void 0?void 0:Ge(e.activeFlavor);if(e.activeFlavor!==void 0&&!t)return;let n=e.originalSnapshot===void 0?void 0:We(e.originalSnapshot);if(e.originalSnapshot!==void 0&&!n)return;let r=e.planId===void 0?void 0:F(e.planId)?e.planId:void 0;if(e.planId!==void 0&&r===void 0)return;let i=e.interruptedFableStage===void 0?void 0:R(e.interruptedFableStage);if(!(e.interruptedFableStage!==void 0&&!i))return{version:2,...t?{activeFlavor:t}:{},...n?{originalSnapshot:n}:{},...r?{planId:r}:{},...i?{interruptedFableStage:i}:{}}}function V(e){if(e.enabled!==!0&&e.enabled!==!1)return;let t=e.toolsBeforePlanMode===void 0?void 0:z(e.toolsBeforePlanMode);if(e.toolsBeforePlanMode!==void 0&&!t)return;let n=e.modelBeforePlanMode===void 0?void 0:I(e.modelBeforePlanMode);if(e.modelBeforePlanMode!==void 0&&!n)return;let r=e.thinkingBeforePlanMode===void 0?void 0:L(e.thinkingBeforePlanMode);if(e.thinkingBeforePlanMode!==void 0&&r===void 0)return;let i=e.planId===void 0?void 0:F(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 Ke(e){if(P(e))return B(e)??V(e)}function qe(e){if(!P(e)||!F(e.content)||!F(e.path)||!F(e.sessionId)||!F(e.title)||!F(e.writtenAt))return;let t=e.planId===void 0?void 0:F(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 H(e,t,n){if(!F(e))throw Error(`${t} must be a string.`);let r=e.trim();if(n&&!r)throw Error(`${t} must not be empty.`);if(ee.Buffer.byteLength(r,`utf8`)>4096)throw Error(`${t} exceeds the bounded debug evidence limit.`);return r}function U(e,t){if(!Array.isArray(e)||e.length>32)throw Error(`${t} must be a bounded string array.`);return e.map((e,n)=>H(e,`${t}[${n}]`,!1))}function W(e,t){return e===void 0?``:H(e,t,!1)}function G(e,t){return e===void 0?[]:U(e,t)}function Je(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 Ye(e){if(!P(e))throw Error(`Debug evidence must be an object.`);Je(e,[`issue`,`expectedBehavior`,`reproductionAttempt`,`actualBehavior`,`logs`,`correlatedTraceEvidence`,`processOutput`,`browserConsoleEvidence`,`correlationIds`,`timestamps`,`verifiedFacts`,`hypotheses`,`unavailableEvidence`],`Debug evidence`);let t={issue:H(e.issue,`issue`,!0),expectedBehavior:W(e.expectedBehavior,`expectedBehavior`),reproductionAttempt:W(e.reproductionAttempt,`reproductionAttempt`),actualBehavior:W(e.actualBehavior,`actualBehavior`),logs:G(e.logs,`logs`),correlatedTraceEvidence:G(e.correlatedTraceEvidence,`correlatedTraceEvidence`),processOutput:G(e.processOutput,`processOutput`),browserConsoleEvidence:G(e.browserConsoleEvidence,`browserConsoleEvidence`),correlationIds:G(e.correlationIds,`correlationIds`),timestamps:G(e.timestamps,`timestamps`),verifiedFacts:G(e.verifiedFacts,`verifiedFacts`),hypotheses:G(e.hypotheses,`hypotheses`),unavailableEvidence:G(e.unavailableEvidence,`unavailableEvidence`)};if(ee.Buffer.byteLength(JSON.stringify(t),`utf8`)>32768)throw Error(`Debug evidence exceeds the bounded packet size.`);return t}function Xe(e,t){let n=new Set(t),r=e.filter(e=>Oe.has(e)&&n.has(e)),i=e.filter(e=>!Oe.has(e)&&!k.has(e)&&!Le.has(e)&&n.has(e)),a=A.filter(e=>n.has(e)),o=[v,le,y].filter(e=>n.has(e));return[...new Set([...r,...i,...a,...o])]}function Ze(e,t,n,r,i){let a=new Set(n),o=t.filter(e=>!Oe.has(e)&&!k.has(e)&&!Le.has(e)),s=Xe([...new Set([...e,...o])].filter(e=>!Le.has(e)),n),c=r===`debug`?[ue,...i].filter(e=>a.has(e)):[];r===`fable`&&a.has(de)&&c.push(de);for(let e of[p.MINOR_MODE_TOOL_NAME,...g.VOICE_MODE_TOOL_NAMES])t.includes(e)&&a.has(e)&&c.push(e);return[...new Set([...s,...c])]}function Qe(e,t,n){let r=new Set(n),i=new Set(t),a=e.filter(e=>!Le.has(e)&&r.has(e)&&(e!==b||i.has(e))),o=t.filter(e=>!Oe.has(e)&&!k.has(e)&&!Le.has(e)&&r.has(e)),s=[p.MINOR_MODE_TOOL_NAME,...g.VOICE_MODE_TOOL_NAMES].filter(e=>i.has(e)&&r.has(e));return[...new Set([...a,...o,...s])]}function K(e){if(e.output=!1,e.progress=!1,e.worktree=!1,Array.isArray(e.parallel))for(let t of e.parallel)K(t);else e.parallel&&K(e.parallel)}function $e(e){if(e.action!==void 0){(0,h.isSubagentAction)(e.action)&&(0,h.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??[])K(t);for(let t of e.chain??[])K(t)}function et(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 tt(e,t){if(e.action===`run`)for(let n of e.requests??[])n.model=t}function nt(e,t){if(e.action===`assign`)for(let n of e.assignments??[])n.model=t}function rt(e){return new Set([`append-step`,`create`,`delete`,`disable`,`eject`,`enable`,`grant-spawn-budget`,`reset`,`schedule`,`schedule-cancel`,`update`,`watchdog.configure`]).has(e??``)}function it(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 at(e=process.env,n=process.cwd()){return t.loadDoomConfig((0,c.loadHarnessState)(e).state.root??n).modes?.planning}function ot(e){let t={key:`p`,label:`plan`,detail:`read-only planning modes`,order:60};return[e?{id:`plan.exit`,path:[t,{key:`e`,label:`exit`,detail:`restore and exit`,tone:`exit`}],action:{name:`plan.exit`}}:{id:`plan.normal`,path:[t,{key:`e`,label:`enter`,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`}}]}function q(e,t,l=at,h=i.createPlanTelemetry(),b={}){let S=!0,C=0,se,w,k,A,M,je,Ne,Le=()=>{let e=Ne?.modelRegistry;return e?e.getAvailable().filter(t=>e.hasConfiguredAuth(t)).map(e=>({provider:e.provider,id:e.id})):[]},F=!1,I,L,R,z,We,B,V,H,U=!1,W=!1,G=!1,Je,Xe,K=`idle`,q,J,Y,st,ct=Promise.resolve(),lt=b.doomIntegrations??!0,ut=b.planPointers??new r.NodePlanPointerAdapter,dt=new Set(b.debugDiagnosticTools??xe),ft=new AbortController;e.effect(()=>()=>_t(),`${T}/runtime`);let pt=b.fableBroker??{start:(e,t)=>{let n=B;if(!n)throw Error(`The session-bound Fable broker is unavailable.`);return n.start(e,t)},cancel:(e,t)=>{B?.cancel({requester:f.FABLE_PLAN_REQUESTER,operationId:e,reason:t})}},mt=()=>b.fableBroker!==void 0||B!==void 0;e.inject([f.DOOM_FABLE_PLAN_SERVICE],e=>{let t=(0,f.readDoomFablePlanService)(e);if(t)return B=t,()=>{B===t&&(B=void 0,Y&&st?.cancel(`The Team Fable service was unloaded.`))}}),e.inject([ie.DOOM_SUBAGENT_POLICY_SERVICE],e=>{let t=(0,ie.readDoomSubagentPolicyService)(e);if(t)return We=t,Ct(),()=>{We===t&&(z?.dispose(),z=void 0,We=void 0)}}),lt&&(e.inject([p.DOOM_MINOR_MODE_CATALOG_SERVICE,m.DOOM_NARRATION_SERVICE],e=>{let t={modes:(0,p.requireMinorModeCatalog)(e),narration:(0,m.requireDoomNarrationService)(e)};return Je=t,()=>{Je===t&&(Je=void 0)}}),e.inject([p.DOOM_MINOR_MODE_CATALOG_SERVICE],e=>{let t=(0,p.registerMinorModeOwner)((0,p.requireMinorModeCatalog)(e),{descriptor:{source:T,id:`plan`,label:`Plan`,description:`Read-only planning with normal, debug, and Fable flavors.`,order:40,actions:[{id:fe,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:pe,label:`Deactivate`,description:`Exit plan mode and restore the previous agent configuration.`,contexts:[`tui`,`headless`],parameters:[]}]},initialState:yt(),async handleAction(e,t,n){if(!S)throw Error(`Plan runtime is disposed.`);if(e===fe){let e=t.flavor;if(e!==`normal`&&e!==`debug`&&e!==`fable`)throw Error(`A valid plan flavor is required.`);return await $(()=>kt(n.context,e,j,!1)),{message:`Plan mode is active with the ${e} flavor.`}}if(e===pe)return{message:await $(()=>At(n.context,j))?`Plan mode deactivated.`:`Plan mode remains active.`};throw Error(`Unknown plan mode action: ${e}`)},onError:e=>void h.recordError(i.PLAN_EVENT.configLoadFailed,e)});return w=t,()=>{t.dispose(),w===t&&(w=void 0)}}),e.inject([_.DOOM_UI_HUB_SERVICE],e=>{let t=(0,_.requireDoomUiHub)(e),n=t.registerLeader({source:T,bindings:ot(F)}),r=t.registerConfig({source:T,listSections:()=>{let e=Le();try{return a.planConfigSections(l(),je,e)}catch(t){return a.planConfigSections(void 0,t instanceof Error?t.message:String(t),e)}},handlers:{[re.CONFIG_ACTION.set]:async({fieldId:e,value:t})=>{let n=a.planSettingByFieldId(e);!n||!t||(je=void 0,await(0,d.setDoomConfigValue)((0,c.globalDoomConfigPath)(),[...n.keyPath],t))},[re.CONFIG_ACTION.clear]:async({fieldId:e})=>{let t=a.planSettingByFieldId(e);t&&(je=void 0,await(0,d.unsetDoomConfigValue)((0,c.globalDoomConfigPath)(),[...t.keyPath]))}},onError:e=>{S&&(je=e instanceof Error?e.message:String(e))}});return k=n,A=r,()=>{r.dispose(),n.dispose(),A===r&&(A=void 0),k===n&&(k=void 0)}}));function X(e=C){if(!S||e!==C)throw Error(`Plan runtime is disposed or stale.`)}async function ht(){let e=Je;if(!e||!e.modes.list().some(e=>e.descriptor.source===m.DOOM_VOICE_SOURCE&&e.descriptor.id===m.DOOM_VOICE_AUTO_MODE_ID&&e.state.activation===`active`))return!1;try{return await e.narration.request(De),!0}catch(e){return h.recordWarning(i.PLAN_EVENT.planReviewCompleted,e,{"plan.outcome":`narration_failed`}),!1}}function gt(){return{content:[{type:`text`,text:`${Ee}\n\nThe choices were spoken through autonomous voice. Stop now and wait for the user's next message; it will arrive as an ordinary user message.`}],details:{answers:[],awaitingResponse:!0,cancelled:!1,delivery:`voice`,voicePrompt:Ee},terminate:!0}}function _t(){return se??=(async()=>{S=!1,C+=1,ft.abort(Error(`Plan runtime is shutting down.`));let e=J,n=L,r=[];st?.cancel(`Plan runtime is shutting down.`);let i=[ct,...Y?[Y]:[]],a=await Promise.allSettled(i);for(let e of a)e.status===`rejected`&&r.push(e.reason);if(F&&n&&e)try{await Et(e,n,!0)&&t.setActiveTools(Qe(n.tools,t.getActiveTools(),t.getAllTools().map(e=>e.name)))}catch(e){r.push(e)}let o=[()=>St(e),()=>z?.dispose(),()=>M?.(),()=>A?.dispose(),()=>k?.dispose(),()=>w?.dispose()];for(let e of o)try{e()}catch(e){r.push(e)}z=void 0,Je=void 0,M=void 0,A=void 0,k=void 0,w=void 0,Y=void 0,J=void 0,G=!1,F=!1,I=void 0,L=void 0,R=void 0;try{await h.shutdown()}catch(e){r.push(e)}if(r.length>0)throw AggregateError(r,`Plan runtime cleanup failed.`)})(),se}function vt(){S&&k?.update(ot(F))}function yt(){let e=I,t=e===`fable`&&K!==`idle`?` · ${K}`:``;return{activation:F?`active`:`inactive`,condition:K===`failed`?`failed`:K===`interrupted`?`degraded`:`ready`,...F&&e?{detail:`${e}${t} - read only`,color:E,modelContextVariant:e}:{},actions:[{id:fe,enabled:!0},...F?[{id:pe,enabled:!0}]:[{id:pe,enabled:!1,disabledReason:`Plan mode is inactive.`}]]}}function bt(e,t){try{return e.ui.theme.fg(E,t)}catch{return t}}function Z(e){if(!S)return;vt();let t=I,n=F&&t?`plan:${t}`:void 0;e.ui.setStatus(`plan-mode`,n?bt(e,n):void 0),w?.publish(yt())}function xt(e,t){try{ut.write(e.sessionManager.getSessionId(),{path:t.path,title:t.title,writtenAt:t.writtenAt,...t.planId===void 0?{}:{planId:t.planId}})}catch(e){h.recordWarning(i.PLAN_EVENT.planPointerFailed,`The plan pointer was not recorded.`,{"plan.reason":e instanceof Error?e.name:`unknown`})}e.hasUI&&(e.ui.setStatus(o.PLAN_STATUS_KEY,o.formatPlanStatus(t.title,ze(t.writtenAt))),W=!0)}function St(e){if(e){try{ut.clear(e.sessionManager.getSessionId())}catch{}W&&(W=!1,e.hasUI&&e.ui.setStatus(o.PLAN_STATUS_KEY,void 0))}}function Ct(){if(!S||!lt||!F||!I||!J)return;let e=[...ke],t={owner:T,allowedTools:e,requiredTools:[x,`mcp`],allowMcpTools:!0,allowedExternalProfiles:I===`fable`?[n.FABLE_PLAN_PROFILE]:[],denyExtensions:!1};z?z.update(t):z=We?.register(t)}function Q(){S&&t.appendEntry(ae,{version:2,...F&&I?{activeFlavor:I}:{},...L?{originalSnapshot:{tools:[...L.tools],...L.model?{model:{...L.model}}:{},thinking:L.thinking}}:{},...H?{planId:H}:{},...q?{interruptedFableStage:q}:{}})}function wt(e,t,n){h.recordWarning(i.PLAN_EVENT.modelResolveFailed,`Planning model ${n}: ${t}`,{[_e]:t,"plan.model.phase":e,"plan.model.reason":n})}async function Tt(e){let n=C;X(n);let r=R?.main;if(r){if(r.model){let i=it(r.model,e);if(!i)e.ui.notify(`Planning model not found: ${r.model}`,E),wt(`apply`,r.model,ve);else{let a=await t.setModel(i);X(n),a||(e.ui.notify(`Planning model is unavailable without authentication: ${r.model}`,E),wt(`apply`,r.model,ye))}}X(n),r.thinking&&t.setThinkingLevel(r.thinking)}}async function Et(e,n,r=!1){let a=C;if(r||X(a),!n)return!1;if(n.model){let o=`${n.model.provider}/${n.model.id}`,s=e.modelRegistry.find(n.model.provider,n.model.id);if(!s)return e.ui.notify(`Previous model not found: ${o}`,E),wt(`restore`,o,ve),!1;try{let n=await t.setModel(s);if(r||X(a),!n)return e.ui.notify(`Previous model is unavailable without authentication: ${o}`,E),wt(`restore`,o,ye),!1}catch(t){return r||X(a),e.ui.notify(`Previous model could not be restored: ${o}`,E),wt(`restore`,o,be),h.recordError(i.PLAN_EVENT.modelResolveFailed,t,{[_e]:o,"plan.model.phase":`restore`,"plan.model.reason":be}),!1}}return r||X(a),t.setThinkingLevel(n.thinking),!0}function Dt(e){F&&I?e.ui.notify(`Already in plan:${I}.`,me):e.ui.notify(`Plan mode is inactive.`,me)}function $(e){let t=C,n=async()=>{X(t);let n=await e();return X(t),n},r=ct.then(n,n);return ct=r.then(()=>void 0,()=>void 0),r}async function Ot(e){let t=C;if(X(t),!Y&&!K.match(/^(draft|review)$/u))return;(K===`draft`||K===`review`)&&(q=K),st?.cancel(e);let n=Y;if(n)try{await n,X(t)}catch(e){X(t),h.recordError(i.PLAN_EVENT.modeDisabled,e,{[D]:`fable`,"plan.fable.reason":`cancel_failed`})}X(t),Y=void 0,q&&(K=`interrupted`),J&&Z(J),Q()}async function kt(e,n,r,a){let o=C;if(X(o),J=e,F){if(I===n){Dt(e);return}I===`fable`&&await Ot(`Leaving Fable for plan:${n}.`),X(o),I=n,Ct(),t.setActiveTools(Ze(L?.tools??[],t.getActiveTools(),t.getAllTools().map(e=>e.name),n,dt)),Z(e),Q(),h.recordEvent(i.PLAN_EVENT.modeEnabled,{[ge]:r,[D]:n,"plan.tool.count":t.getActiveTools().length});return}let s;try{s=l()}catch(e){throw h.recordError(i.PLAN_EVENT.configLoadFailed,e,{[ge]:r}),e}a?H??=Ve():(V=void 0,U=!1,G=!1,H=Ve(),q=void 0,K=`idle`),R=s,L??={tools:[...t.getActiveTools()],...e.model?{model:{provider:e.model.provider,id:e.model.id}}:{},thinking:t.getThinkingLevel()},F=!0,I=n,t.setActiveTools(Ze(L.tools,t.getActiveTools(),t.getAllTools().map(e=>e.name),n,dt)),Ct(),await Tt(e),X(o),Z(e),Q(),h.recordEvent(i.PLAN_EVENT.modeEnabled,{[ge]:r,[D]:n,"plan.tool.count":t.getActiveTools().length,...R?.main?.model?{[_e]:R.main.model}:{},...R?.main?.thinking?{"plan.thinking":R.main.thinking}:{}})}async function At(e,n){let r=C;if(X(r),!F)return Dt(e),!1;await Ot(`Plan mode is exiting.`),X(r);let a=L,o=await Et(e,a);if(X(r),!o)return e.ui.notify(`Previous model was not restored. Plan mode remains read-only.`,E),Z(e),Q(),h.recordWarning(i.PLAN_EVENT.modeDisabled,`Plan mode restoration failed.`,{[ge]:n,[D]:I??`unknown`,"plan.restored":!1}),!1;let s=!!V;return t.setActiveTools(Qe(a?.tools??[],t.getActiveTools(),t.getAllTools().map(e=>e.name))),z?.dispose(),z=void 0,F=!1,I=void 0,R=void 0,G=!1,L=void 0,Xe=void 0,K=`idle`,q=void 0,Z(e),Q(),h.recordEvent(i.PLAN_EVENT.modeDisabled,{[ge]:n,[D]:`normal`,"plan.written":s,"plan.restored":!0}),!0}if(lt){let t=e=>{if(X(),e.aborted)throw e.reason instanceof Error?e.reason:Error(`Plan voice transition was cancelled.`)},n={descriptor:{source:Me,id:`plan-activate`,name:`activate_plan`,label:`Activate Plan`,description:`Activate or switch the serialized read-only planning mode flavor.`,order:10,inputSchema:Pe,resultSchema:Ie},execute(e,n){let r=Ge(P(e)?e.flavor:void 0);if(!r)throw Error(`A valid plan flavor is required.`);return t(n.signal),$(async()=>{t(n.signal);let e=F,i=I;return await kt(n.context,r,Ae,!1),{active:F,flavor:I??r,changed:e!==F||i!==I}})}},r={descriptor:{source:Me,id:`plan-exit`,name:`exit_plan`,label:`Exit Plan`,description:`Exit read-only planning mode and restore the previous agent configuration.`,order:20,inputSchema:Fe,resultSchema:Ie},execute(e,n){return t(n.signal),$(async()=>{t(n.signal);let e=F,r=await At(n.context,Ae);return{active:F,flavor:I??null,changed:e!==F||r}})}};e.inject([g.DOOM_VOICE_TOOLS_SERVICE],e=>{let t=(0,g.requireDoomVoiceToolsService)(e),i=t.register(n),a=t.register(r);return()=>{a.dispose(),i.dispose()}})}st=n.createFablePlanFlow({broker:pt,isAuthorized:()=>S&&F&&I===`fable`&&mt(),onStage:e=>{S&&(K=e,(e===`completed`||e===`failed`||e===`cancelled`)&&(q=void 0),J&&Z(J),F&&Q())},onError:e=>{S&&h.recordError(i.PLAN_EVENT.modeEnabled,e,{[D]:`fable`,"plan.fable.reason":`flow_error`})}}),t.registerTool({name:ue,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(),!F||I!==`debug`)return{content:[{type:`text`,text:`Debug planning is not active.`}],details:{recorded:!1}};try{Xe=Ye(t)}catch(e){throw h.recordWarning(i.PLAN_EVENT.modeEnabled,e,{[D]:`debug`,"plan.debug.reason":`invalid_evidence`}),e}return J&&Z(J),{content:[{type:`text`,text:`Debug evidence recorded as optional planning context.`}],details:{recorded:!0}}}}),t.registerTool({name:de,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){let r=C;if(X(r),!F||I!==`fable`)return{content:[{type:`text`,text:`Fable planning is not active.`}],details:{started:!1}};if(!mt())return{content:[{type:`text`,text:`The local Fable broker is unavailable. Fable planning remains disabled.`}],details:{started:!1,errorCode:`broker_unavailable`}};let i=st;if(!i)throw Error(`Fable planning flow is unavailable.`);let a=i.run(t,n);Y=a;try{let e=await a;return X(r),{content:[{type:`text`,text:e.draft?`Fable draft:\n${e.draft}`:`Fable planning ${e.status}: ${e.errorCode??`no output`}.`}],details:{...e,started:!0}}}finally{S&&r===C&&Y===a&&(Y=void 0)}}}),t.registerTool({name:y,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(e,n,r,a,o){let s=C;if(X(s),!F)return{content:[{type:`text`,text:`Plan mode is disabled. Use normal file tools instead.`}],details:{written:!1}};let l=He(o.sessionManager.getBranch(),e);if(!l){let e=Error(`Present the complete implementation plan as visible Markdown in chat before calling write_plan.`);throw h.recordError(i.PLAN_EVENT.writePlanFailed,e,{"plan.reason":`missing_visible_plan`}),e}let d=Date.now(),re=(0,c.getHarnessState)().root??o.cwd,f=(0,c.resolvePlanningPlansDirectory)(R?.plansDirectory,re,te.default.homedir()),p=Be(o.sessionManager.getSessionId());H??=Ve();let m=V?.planId===H&&ne.default.dirname(V.path)===f?V.path:void 0,ie=Re(l),g=H,_=m??ne.default.join(f,`${ie}--${g}.md`),ae=new AbortController,v=Error(`Writing ${_} timed out after ${Se}ms.`),y=setTimeout(()=>ae.abort(v),Se),b=AbortSignal.any([ae.signal,ft.signal,...r?[r]:[]]),x=`checking`,se=()=>{a?.({content:[{type:`text`,text:`${x===`checking`?`Checking`:`Writing`} ${_}...`}],details:{phase:x,path:_,startedAt:d}})},ce=(e,t)=>{h.recordWarning(i.PLAN_EVENT.writePlanUnsafePath,t,{"plan.phase":x,"plan.refusal":e})};try{se();try{await N(()=>u.default.promises.mkdir(f,{recursive:!0,mode:448}),b)}catch(e){throw b.aborted?Ue(b):Error(`Could not create the configured plans directory ${f}.`,{cause:e})}let e=await N(()=>u.default.promises.lstat(f),b),n=await N(()=>u.default.promises.realpath(f),b);if(e.isSymbolicLink()||!e.isDirectory())return ce(`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:_,phase:x,durationMs:Date.now()-d}};X(s),x=`writing`,se();let r;try{for(let e=0;e<3;e+=1)try{let e=m?0:u.default.constants.O_EXCL;r=await N(()=>u.default.promises.open(_,u.default.constants.O_CREAT|u.default.constants.O_WRONLY|u.default.constants.O_NONBLOCK|u.default.constants.O_NOFOLLOW|e,384),b);break}catch(t){if(!(!m&&t instanceof Error&&`code`in t&&String(t.code)===`EEXIST`)||e===2)throw t;g=Ve(),H=g,_=ne.default.join(f,`${ie}--${g}.md`),Q()}if(!r)throw Error(`Could not allocate a unique plan filename in ${f}.`);let e=await N(()=>u.default.promises.realpath(f),b),t=await N(()=>r.stat(),b);if(e!==n||!t.isFile()||t.nlink!==1)return ce(`invalid_destination`,he),{content:[{type:`text`,text:he}],details:{written:!1,path:_,phase:x,durationMs:Date.now()-d}};await N(()=>r.truncate(0),b),await N(()=>r.writeFile(l,{encoding:`utf8`,signal:b}),b)}catch(e){if(e instanceof Error&&`code`in e&&[`EISDIR`,`ELOOP`,`ENXIO`].includes(String(e.code)))return ce(`invalid_destination`,he),{content:[{type:`text`,text:he}],details:{written:!1,path:_,phase:x,durationMs:Date.now()-d}};throw e}finally{await r?.close()}return X(s),V={content:l,path:_,sessionId:p,planId:g,title:ie,writtenAt:new Date().toISOString()},t.appendEntry(oe,V),xt(o,V),U=!0,G=!1,h.recordEvent(i.PLAN_EVENT.planWritten,{"plan.written":!0,"plan.bytes":ee.Buffer.byteLength(l,`utf8`),"plan.duration_ms":Date.now()-d,"plan.revised":!!m}),{content:[{type:`text`,text:`Wrote implementation plan to ${_}.`}],details:{written:!0,path:_,phase:x,durationMs:Date.now()-d}}}catch(e){if(!S||s!==C)throw Ue(ft.signal);let t={"plan.phase":x,"plan.duration_ms":Date.now()-d};if(ae.signal.aborted&&!r?.aborted){let n=Error(`write_plan timed out during ${x} for ${_}.`,{cause:e});throw h.recordError(i.PLAN_EVENT.writePlanTimedOut,n,{...t,"plan.timeout_ms":Se}),n}throw h.recordError(i.PLAN_EVENT.writePlanFailed,e,{...t,"plan.cancelled":r?.aborted??!1}),e}finally{clearTimeout(y)}}});async function jt(e,t){if(X(),h.recordEvent(i.PLAN_EVENT.planReviewCompleted,{"plan.outcome":e===O?`exited`:`continued`}),e===O){let e=await $(()=>At(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 U=!1,{content:[{type:`text`,text:`The user chose to continue planning. Remain read-only and refine the plan.`}],details:{exited:!1}}}t.registerTool({name:v,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 "${O}" without the user explicitly choosing "${Ce}".`],parameters:{type:`object`,properties:{decision:{type:`string`,enum:[O,Te]}},additionalProperties:!1},async execute(e,t,n,r,a){let o=C;if(X(o),!F)return{content:[{type:`text`,text:`Plan mode is already disabled.`}],details:{exited:!1}};if(!U)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 h.recordEvent(i.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 s=P(t)?t.decision:void 0,c=s===O||s===Te;if(G){if(!c)throw Error(`The narrated plan review is waiting for an explicit exit or continue decision.`);return G=!1,jt(s,a)}if(s!==void 0)throw Error(`Call complete_plan without a decision before submitting a narrated plan-review answer.`);if(await ht())return X(o),G=!0,gt();let ee=await a.ui.select(`Plan complete. What would you like to do?`,[Ce,we]);return X(o),jt(ee===Ce?O:Te,a)}}),lt&&e.inject([_.DOOM_UI_HUB_SERVICE],e=>{let t=(0,_.requireDoomUiHub)(e).registerLeaderActions({source:T,handlers:{"plan.normal":()=>{let e=S?J:void 0;return e?$(()=>kt(e,`normal`,j,!1)):void 0},"plan.exit":()=>{let e=S?J:void 0;return e?$(async()=>{await At(e,j)}):void 0},"plan.debug":()=>{let e=S?J:void 0;return e?$(()=>kt(e,`debug`,j,!1)):void 0},"plan.fable":()=>{let e=S?J:void 0;return e?$(()=>kt(e,`fable`,j,!1)):void 0}},onError:(e,t)=>{S&&(J?.hasUI&&J.ui.notify(`Leader action ${t} failed. Plan mode remains read-only.`,E),h.recordError(i.PLAN_EVENT.modeEnabled,e,{[ge]:j,"plan.action":t}))}});return M=t,()=>{t(),M===t&&(M=void 0)}}),t.on(`tool_call`,async(e,t)=>{if(!S||!F)return;let n=I===`debug`&&(e.toolName===ue||dt.has(e.toolName))||I===`fable`&&e.toolName===de;if(!Oe.has(e.toolName)&&!n)return{block:!0,reason:`Plan mode blocks the ${e.toolName} tool. Use SPC p e to restore access.`};let r=et(R?.subagents,t.model);if(e.toolName===le){r&&nt(e.input,r);return}if(e.toolName!==ce)return;let i=e.input;if(rt(i.action))return{block:!0,reason:`Plan mode blocks subagent management action '${i.action}'. Use SPC p e first.`};$e(i),r&&tt(i,r)}),t.on(`before_agent_start`,async(e,t)=>{if(!S)return;let n=[];if(F){let e=(0,c.getHarnessState)().root??t.cwd,r=(0,c.resolvePlanningPlansDirectory)(R?.plansDirectory,e,te.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.`,s.buildFlavorPlanningPrompt(I,r,Xe,K))}if(V){let e=V.content;try{e=await u.default.promises.readFile(V.path,`utf8`)}catch{e=V.content}n.push(`[CURRENT PLAN]\nSource: ${V.path}\n\n${e}`)}if(n.length!==0)return{systemPrompt:`${e.systemPrompt}\n\n${n.join(`
|
|
5
5
|
|
|
6
|
-
`)}`}}),t.on(`context`,async e=>{if(S)return{messages:e.messages.filter(e=>e.customType!==`agent-harness-plan-mode-context`)}}),t.on(`session_start`,async(e,n)=>{if(!S)return;Ne=n;let r=++C,i=n.sessionManager.getEntries(),a=i.flatMap(e=>e.type===`custom`&&e.customType===ae?[Ke(e.data)]:[]).filter(e=>e!==void 0).at(-1),o=Be(n.sessionManager.getSessionId()),s=i.flatMap(e=>e.type===`custom`&&e.customType===oe?[qe(e.data)]:[]).filter(e=>e!==void 0).at(-1),c=L;if(z?.dispose(),z=void 0,V=s?.sessionId===o?s:void 0,V?
|
|
6
|
+
`)}`}}),t.on(`context`,async e=>{if(S)return{messages:e.messages.filter(e=>e.customType!==`agent-harness-plan-mode-context`)}}),t.on(`session_start`,async(e,n)=>{if(!S)return;Ne=n;let r=++C,i=n.sessionManager.getEntries(),a=i.flatMap(e=>e.type===`custom`&&e.customType===ae?[Ke(e.data)]:[]).filter(e=>e!==void 0).at(-1),o=Be(n.sessionManager.getSessionId()),s=i.flatMap(e=>e.type===`custom`&&e.customType===oe?[qe(e.data)]:[]).filter(e=>e!==void 0).at(-1),c=L;if(z?.dispose(),z=void 0,V=s?.sessionId===o?s:void 0,V?xt(n,V):St(n),H=a?.planId??V?.planId,U=!1,G=!1,R=void 0,Xe=void 0,F=!1,I=void 0,vt(),L=a?.originalSnapshot,q=a?.interruptedFableStage,K=q?`interrupted`:`idle`,J=n,a?.activeFlavor)await kt(n,a.activeFlavor,`session_restore`,!0),X(r);else{let e=a?.originalSnapshot??c;if(e){let i=await Et(n,e);X(r),i&&t.setActiveTools(Qe(e.tools,t.getActiveTools(),t.getAllTools().map(e=>e.name)))}else t.setActiveTools(t.getActiveTools().filter(e=>e!==v&&e!==y&&e!==ue&&e!==de));X(r),L=void 0,Z(n)}})}exports.WRITE_PLAN_TIMEOUT_MS=Se,exports.configurePlanningSubagentInput=tt,exports.configurePlanningTaskInput=nt,exports.constrainSubagentInput=$e,exports.createPlanIdentifier=Ve,exports.isBlockedSubagentManagementAction=rt,exports.loadPlanningModeConfig=at,exports.parseDebugEvidencePacket=Ye,exports.parsePersistedPlanState=Ke,exports.planModeExtension=q,exports.planModeTools=Xe,exports.planSessionIdentifier=Be,exports.planTitleSlug=Re,exports.planningSubagentModel=et,exports.visiblePlanForToolCall=He;
|
|
7
7
|
//# sourceMappingURL=planMode.cjs.map
|