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