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