@hhsw2015/task-master-ai 0.43.25 → 0.43.28

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.
@@ -1 +1 @@
1
- import{A as e,B as t,C as n,Cn as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,R as _,S as v,T as y,U as b,V as x,W as S,_ as C,a as w,b as T,bn as E,c as D,d as O,f as k,g as A,h as j,i as M,j as N,k as P,l as F,m as I,n as L,o as R,p as z,q as B,r as V,s as H,t as U,u as W,v as G,w as K,x as q,xn as J,y as Y,z as X}from"./config-manager-sjIWkXoH.js";import"./git-utils-DllbRE35.js";export{E as ALL_PROVIDERS,J as CUSTOM_PROVIDERS,U as ConfigurationError,u as MODEL_MAP,r as VALIDATED_PROVIDERS,L as getAllProviders,V as getAnonymousTelemetryEnabled,M as getAvailableModels,w as getAzureBaseURL,R as getBaseUrlForRole,H as getBedrockBaseURL,D as getClaudeCodeSettings,F as getClaudeCodeSettingsForCommand,W as getCodebaseAnalysisMode,O as getCodexCliSettings,k as getCodexCliSettingsForCommand,z as getConfig,I as getDebugFlag,j as getDefaultNumTasks,A as getDefaultPriority,C as getDefaultSubtasks,G as getFallbackModelId,Y as getFallbackProvider,T as getGrokCliSettings,q as getGrokCliSettingsForCommand,v as getLogLevel,n as getMainModelId,K as getMainProvider,y as getMcpApiKeyStatus,a as getOllamaBaseURL,i as getOperatingMode,h as getParametersForRole,P as getProjectName,e as getProxyEnabled,N as getResearchModelId,p as getResearchProvider,m as getResponseLanguage,g as getSupportedModelsForProvider,o as getUserId,l as getVertexLocation,f as getVertexProjectId,_ as hasCodebaseAnalysis,X as isApiKeySet,t as isConfigFilePresent,x as isConfigWarningSuppressed,c as isProxyEnabled,b as setSuppressConfigWarnings,S as validateClaudeCodeSettings,s as validateCodexCliSettings,d as validateProvider,B as writeConfig};
1
+ import{A as e,B as t,C as n,Cn as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,R as _,S as v,T as y,U as b,V as x,W as S,_ as C,a as w,b as T,bn as E,c as D,d as O,f as k,g as A,h as j,i as M,j as N,k as P,l as F,m as I,n as L,o as R,p as z,q as B,r as V,s as H,t as U,u as W,v as G,w as K,x as q,xn as J,y as Y,z as X}from"./config-manager-C6naCnWC.js";import"./git-utils-DllbRE35.js";export{E as ALL_PROVIDERS,J as CUSTOM_PROVIDERS,U as ConfigurationError,u as MODEL_MAP,r as VALIDATED_PROVIDERS,L as getAllProviders,V as getAnonymousTelemetryEnabled,M as getAvailableModels,w as getAzureBaseURL,R as getBaseUrlForRole,H as getBedrockBaseURL,D as getClaudeCodeSettings,F as getClaudeCodeSettingsForCommand,W as getCodebaseAnalysisMode,O as getCodexCliSettings,k as getCodexCliSettingsForCommand,z as getConfig,I as getDebugFlag,j as getDefaultNumTasks,A as getDefaultPriority,C as getDefaultSubtasks,G as getFallbackModelId,Y as getFallbackProvider,T as getGrokCliSettings,q as getGrokCliSettingsForCommand,v as getLogLevel,n as getMainModelId,K as getMainProvider,y as getMcpApiKeyStatus,a as getOllamaBaseURL,i as getOperatingMode,h as getParametersForRole,P as getProjectName,e as getProxyEnabled,N as getResearchModelId,p as getResearchProvider,m as getResponseLanguage,g as getSupportedModelsForProvider,o as getUserId,l as getVertexLocation,f as getVertexProjectId,_ as hasCodebaseAnalysis,X as isApiKeySet,t as isConfigFilePresent,x as isConfigWarningSuppressed,c as isProxyEnabled,b as setSuppressConfigWarnings,S as validateClaudeCodeSettings,s as validateCodexCliSettings,d as validateProvider,B as writeConfig};
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,l as n,n as r,t as i}from"./ai-services-unified-BowF9Vy-.js";import{$ as a,At as o,B as s,Bt as c,C as l,Ct as u,Dn as d,En as f,Jt as p,Kt as m,Lt as h,M as g,Mt as _,O as v,Ot as y,R as b,Rt as x,T as S,Tn as C,Tt as w,X as T,Xt as E,Y as D,Yt as O,Z as k,Zt as A,_ as j,_n as M,a as N,an as P,bt as ee,cn as te,ct as ne,dn as re,dt as ie,en as ae,et as F,fn as oe,ft as se,g as ce,gn as le,gt as ue,hn as de,ht as fe,i as pe,it as me,j as he,k as ge,kn as _e,kt as ve,ln as I,lt as ye,m as be,mn as xe,mt as Se,n as Ce,nn as we,o as Te,on as Ee,p as De,pn as Oe,pt as ke,q as Ae,rt as je,sn as Me,tt as Ne,un as Pe,ut as Fe,v as Ie,vn as Le,vt as L,w as Re,wn as ze,wt as Be,xn as R,y as Ve,yn as He,yt as z,z as Ue}from"./config-manager-sjIWkXoH.js";import We,{resolve as Ge}from"node:path";import B from"chalk";import*as Ke from"fs";import V from"fs";import H from"path";import qe from"os";import Je from"node:fs";import{fileURLToPath as Ye}from"node:url";import Xe from"node:fs/promises";import Ze from"node:os";import{z as U}from"zod";import{spawn as Qe}from"child_process";import{fileURLToPath as $e}from"url";import{FastMCP as et}from"fastmcp";import{smoothStream as tt}from"ai";import W from"boxen";import nt from"readline";import{Command as G}from"commander";import rt from"figlet";import it from"gradient-string";import at from"terminal-link";import{marked as ot}from"marked";import{markedTerminal as st}from"marked-terminal";import ct from"turndown";import K from"cli-table3";import q from"inquirer";import J from"ora";import lt from"open";import ut,{Separator as dt}from"@inquirer/search";import ft from"process";import pt from"https";import mt from"cli-progress";import ht from"http";import gt from"fuse.js";import _t from"ajv";import vt from"ajv-formats";import yt from"gpt-tokens";import{LRUCache as bt}from"lru-cache";import"@streamparser/json";var xt=`@hhsw2015/task-master-ai`,St=`0.43.25`;function Ct(e,t,n){return(n?.color?B[n.color]:B.cyan)(at(e,t,{fallback:(e,t)=>`${e} (${t})`}))}function wt(e,t){return Ct(e,e,t)}const Tt=it([`#00b4d8`,`#0077b6`,`#03045e`]);function Et(){return process.env.TM_HIDE_BANNER===`true`}function Dt(){return process.stdout.columns||80}function Ot(e={}){if(Et())return;let{version:t}=e;try{let e=rt.textSync(`Task Master`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(Tt(e))}catch{console.log(Tt(`=== Task Master ===`))}let n=Ct(`x.com/eyaltoledano`,`https://x.com/eyaltoledano`),r=B.dim(`by `)+B.cyan(n),i=t?t.replace(/^v/,``):``,a=`https://github.com/eyaltoledano/claude-task-master/releases/tag/task-master-ai%40${i}`,o=t?Ct(`v${i}`,a,{color:`gray`}):``;if(o){let e=i.length+1,t=Dt(),n=Math.max(2,t-22-e-2);console.log(r+` `.repeat(n)+o)}else console.log(r);let s=Ct(`tryhamster.com`,`https://tryhamster.com`);console.log(B.dim(`Taskmaster for teams: `)+B.magenta(s)),console.log(``)}function kt(){if(Et())return;try{let e=rt.textSync(`Task Master`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(Tt(e))}catch{console.log(Tt(`=== Task Master ===`))}let e=Ct(`x.com/eyaltoledano`,`https://x.com/eyaltoledano`);console.log(B.dim(`by `)+B.cyan(e));let t=Ct(`tryhamster.com`,`https://tryhamster.com`);console.log(B.dim(`Taskmaster for teams: `)+B.magenta(t)),console.log(``)}function At(e){let{header:t,body:n,callToAction:r,footer:i,level:a=`warn`}=e,o=a===`info`?B.blue.bold:B.yellow.bold,s=a===`info`?`blue`:`yellow`,c=[o(t),...n.map(e=>B.white(e))];return r&&r.label&&r.action&&c.push(B.cyan(r.label)+`
1
+ import{a as e,i as t,l as n,n as r,t as i}from"./ai-services-unified-CA2_lqmH.js";import{$ as a,At as o,B as s,Bt as c,C as l,Ct as u,Dn as d,En as f,Jt as p,Kt as m,Lt as h,M as g,Mt as _,O as v,Ot as y,R as b,Rt as x,T as S,Tn as C,Tt as w,X as T,Xt as E,Y as D,Yt as O,Z as k,Zt as A,_ as j,_n as M,a as N,an as P,bt as ee,cn as te,ct as ne,dn as re,dt as ie,en as ae,et as F,fn as oe,ft as se,g as ce,gn as le,gt as ue,hn as de,ht as fe,i as pe,it as me,j as he,k as ge,kn as _e,kt as ve,ln as I,lt as ye,m as be,mn as xe,mt as Se,n as Ce,nn as we,o as Te,on as Ee,p as De,pn as Oe,pt as ke,q as Ae,rt as je,sn as Me,tt as Ne,un as Pe,ut as Fe,v as Ie,vn as Le,vt as L,w as Re,wn as ze,wt as Be,xn as R,y as Ve,yn as He,yt as z,z as Ue}from"./config-manager-C6naCnWC.js";import We,{resolve as Ge}from"node:path";import B from"chalk";import*as Ke from"fs";import V from"fs";import H from"path";import qe from"os";import Je from"node:fs";import{fileURLToPath as Ye}from"node:url";import Xe from"node:fs/promises";import Ze from"node:os";import{z as U}from"zod";import{spawn as Qe}from"child_process";import{fileURLToPath as $e}from"url";import{FastMCP as et}from"fastmcp";import{smoothStream as tt}from"ai";import W from"boxen";import nt from"readline";import{Command as G}from"commander";import rt from"figlet";import it from"gradient-string";import at from"terminal-link";import{marked as ot}from"marked";import{markedTerminal as st}from"marked-terminal";import ct from"turndown";import K from"cli-table3";import q from"inquirer";import J from"ora";import lt from"open";import ut,{Separator as dt}from"@inquirer/search";import ft from"process";import pt from"https";import mt from"cli-progress";import ht from"http";import gt from"fuse.js";import _t from"ajv";import vt from"ajv-formats";import yt from"gpt-tokens";import{LRUCache as bt}from"lru-cache";import"@streamparser/json";var xt=`@hhsw2015/task-master-ai`,St=`0.43.28`;function Ct(e,t,n){return(n?.color?B[n.color]:B.cyan)(at(e,t,{fallback:(e,t)=>`${e} (${t})`}))}function wt(e,t){return Ct(e,e,t)}const Tt=it([`#00b4d8`,`#0077b6`,`#03045e`]);function Et(){return process.env.TM_HIDE_BANNER===`true`}function Dt(){return process.stdout.columns||80}function Ot(e={}){if(Et())return;let{version:t}=e;try{let e=rt.textSync(`Task Master`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(Tt(e))}catch{console.log(Tt(`=== Task Master ===`))}let n=Ct(`x.com/eyaltoledano`,`https://x.com/eyaltoledano`),r=B.dim(`by `)+B.cyan(n),i=t?t.replace(/^v/,``):``,a=`https://github.com/eyaltoledano/claude-task-master/releases/tag/task-master-ai%40${i}`,o=t?Ct(`v${i}`,a,{color:`gray`}):``;if(o){let e=i.length+1,t=Dt(),n=Math.max(2,t-22-e-2);console.log(r+` `.repeat(n)+o)}else console.log(r);let s=Ct(`tryhamster.com`,`https://tryhamster.com`);console.log(B.dim(`Taskmaster for teams: `)+B.magenta(s)),console.log(``)}function kt(){if(Et())return;try{let e=rt.textSync(`Task Master`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(Tt(e))}catch{console.log(Tt(`=== Task Master ===`))}let e=Ct(`x.com/eyaltoledano`,`https://x.com/eyaltoledano`);console.log(B.dim(`by `)+B.cyan(e));let t=Ct(`tryhamster.com`,`https://tryhamster.com`);console.log(B.dim(`Taskmaster for teams: `)+B.magenta(t)),console.log(``)}function At(e){let{header:t,body:n,callToAction:r,footer:i,level:a=`warn`}=e,o=a===`info`?B.blue.bold:B.yellow.bold,s=a===`info`?`blue`:`yellow`,c=[o(t),...n.map(e=>B.white(e))];return r&&r.label&&r.action&&c.push(B.cyan(r.label)+`
2
2
  `+B.blue.underline(r.action)),i&&c.push(B.gray(i)),W(c.join(`
3
3
 
4
4
  `),{padding:1,borderColor:s,borderStyle:`round`,margin:{top:1,bottom:1}})}function jt(e,t=30,n){if(!n){let n=Math.round(e/100*t),r=t-n;return B.green(`█`).repeat(n)+B.gray(`░`).repeat(r)}let r=``,i=0;if(n.done&&n.done>0){let e=Math.round(n.done/100*t);e>0&&(r+=B.green(`█`).repeat(e),i+=e)}if(n.cancelled&&i<t){let e=Math.round(n.cancelled/100*t),a=Math.min(e,t-i);a>0&&(r+=B.gray(`█`).repeat(a),i+=a)}if(n.deferred&&i<t){let e=Math.round(n.deferred/100*t),a=Math.min(e,t-i);a>0&&(r+=B.gray(`█`).repeat(a),i+=a)}if(n[`in-progress`]&&i<t){let e=Math.round(n[`in-progress`]/100*t),a=Math.min(e,t-i);a>0&&(r+=B.blue(`█`).repeat(a),i+=a)}if(n.review&&i<t){let e=Math.round(n.review/100*t),a=Math.min(e,t-i);a>0&&(r+=B.magenta(`░`).repeat(a),i+=a)}if(n.pending&&i<t){let e=Math.round(n.pending/100*t),a=Math.min(e,t-i);a>0&&(r+=B.yellow(`░`).repeat(a),i+=a)}if(n.blocked&&i<t){let e=Math.round(n.blocked/100*t),a=Math.min(e,t-i);a>0&&(r+=B.red(`░`).repeat(a),i+=a)}return i<t&&(r+=B.yellow(`░`).repeat(t-i)),r}function Mt(e){let t={total:e.length,done:0,inProgress:0,pending:0,blocked:0,deferred:0,cancelled:0,review:0,completionPercentage:0,completedCount:0};return e.forEach(e=>{switch(e.status){case`done`:t.done++;break;case`in-progress`:t.inProgress++;break;case`pending`:t.pending++;break;case`blocked`:t.blocked++;break;case`deferred`:t.deferred++;break;case`cancelled`:t.cancelled++;break;case`review`:t.review=(t.review||0)+1;break}}),t.completedCount=e.filter(e=>He(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function Nt(e){let t={total:0,done:0,inProgress:0,pending:0,blocked:0,deferred:0,cancelled:0,review:0,completionPercentage:0,completedCount:0},n=[];return e.forEach(e=>{e.subtasks&&e.subtasks.length>0&&e.subtasks.forEach(e=>{switch(t.total++,n.push(e),e.status){case`done`:t.done++;break;case`in-progress`:t.inProgress++;break;case`pending`:t.pending++;break;case`blocked`:t.blocked++;break;case`deferred`:t.deferred++;break;case`cancelled`:t.cancelled++;break;case`review`:t.review=(t.review||0)+1;break}})}),t.completedCount=n.filter(e=>He(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function Pt(e){let t=new Set(e.filter(e=>He(e.status)).map(e=>e.id)),n=e.filter(e=>!He(e.status)&&(!e.dependencies||e.dependencies.length===0)).length,r=e.filter(e=>!He(e.status)&&e.dependencies&&e.dependencies.length>0&&e.dependencies.every(e=>t.has(e))).length,i=e.filter(e=>!He(e.status)&&e.dependencies&&e.dependencies.length>0&&!e.dependencies.every(e=>t.has(e))).length,a={};e.forEach(e=>{e.dependencies&&e.dependencies.length>0&&e.dependencies.forEach(e=>{let t=String(e);a[t]=(a[t]||0)+1})});let o,s=0;for(let[e,t]of Object.entries(a))t>s&&(s=t,o=parseInt(e));let c=e.reduce((e,t)=>e+(t.dependencies?t.dependencies.length:0),0),l=e.length>0?c/e.length:0;return{tasksWithNoDeps:n,tasksReadyToWork:n+r,tasksBlockedByDeps:i,mostDependedOnTaskId:o,mostDependedOnCount:s,avgDependenciesPerTask:l}}function Ft(e){let t={critical:0,high:0,medium:0,low:0};return e.forEach(e=>{let n=e.priority||`medium`;t[n]++}),t}function It(e){return e.total===0?{}:{done:e.done/e.total*100,"in-progress":e.inProgress/e.total*100,pending:e.pending/e.total*100,blocked:e.blocked/e.total*100,deferred:e.deferred/e.total*100,cancelled:e.cancelled/e.total*100,review:(e.review||0)/e.total*100}}function Lt(e,t=!1){let n=[];t?n.push(`Completed: ${B.green(`${e.completedCount}/${e.total}`)}`):n.push(`Done: ${B.green(e.done)}`),n.push(`Cancelled: ${B.gray(e.cancelled)}`),n.push(`Deferred: ${B.gray(e.deferred)}`);let r=n.join(` `);n.length=0,n.push(`In Progress: ${B.blue(e.inProgress)}`),n.push(`Review: ${B.magenta(e.review||0)}`),n.push(`Pending: ${B.yellow(e.pending)}`),n.push(`Blocked: ${B.red(e.blocked)}`);let i=n.join(` `);return r+`
@@ -244,7 +244,7 @@ Examples:
244
244
  Note: Briefs must be created through the Hamster Studio web interface.
245
245
  `).action(async e=>{await this.executeCreate(e)})}async initTmCore(){this.tmCore||=await I({projectPath:process.cwd()})}async executeList(e){try{await this.checkAuth()||process.exit(1);let t=await this.ensureOrgSelectedLocal();t||process.exit(1);let n=J(`Fetching briefs...`).start(),r=await this.authManager.getBriefs(t);n.stop();let i=this.authManager.getContext()?.briefId,a=r.map(e=>({name:e.document?.title||`Brief ${e.id.slice(-8)}`,isCurrent:e.id===i,taskCount:e.taskCount||0,completedTasks:0,statusBreakdown:{},created:e.createdAt,description:e.document?.description,status:e.status,briefId:e.id,updatedAt:e.updatedAt}));a.sort((e,t)=>e.isCurrent?-1:t.isCurrent?1:0),this.setLastResult({success:!0,action:`list`,briefs:a,currentBrief:i||null,message:`Found ${a.length} brief(s)`}),process.stdout.isTTY&&a.length>0?await this.promptBriefSelection(a):a.length===0?An(`No briefs found in this organization`):this.displayBriefsTable(a,e?.showMetadata)}catch(e){Y(`Failed to list briefs: ${e.message}`),this.setLastResult({success:!1,action:`list`,message:e.message}),process.exit(1)}}async ensureOrgSelectedLocal(){let e=await Qn(this.authManager);return e.success&&e.orgId||null}displayBriefsTable(e,t){let r=n(`cli-table3`),i=Math.max(process.stdout.columns||120,80),a=Math.floor(i*.95),o=[.35,.25,.2,.1,.1].map((e,t)=>Math.max(Math.floor(a*e),t===0?20:8)),s=new r({head:[B.cyan.bold(`Brief Name`),B.cyan.bold(`Status`),B.cyan.bold(`Updated`),B.cyan.bold(`Tasks`),B.cyan.bold(`Completed`)],colWidths:o,wordWrap:!0});e.forEach(e=>{let t=e.briefId?e.briefId.slice(-8):`unknown`,n=e.isCurrent?`${B.green(`●`)} ${B.green.bold(e.name)} ${B.gray(`(current - ${t})`)}`:` ${e.name} ${B.gray(`(${t})`)}`,r=e.updatedAt?new Date(e.updatedAt).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`}):B.gray(`N/A`);s.push([n,bn(e.status,!0),B.gray(r),B.white(String(e.taskCount||0)),B.green(String(e.completedTasks||0))])}),console.log(s.toString())}formatBriefAsTableRow(e,t){let n=e.briefId?e.briefId.slice(-8):`unknown`,r=e.isCurrent,i=r?B.green(`●`):` `,a=r?`(current)`:`(${n})`,o=t.name-4-a.length,s=e.name;s.length>o&&(s=s.substring(0,o-1)+`…`);let c=r?B.green.bold(s):s,l=r?B.gray(`(current)`):B.gray(`(${n})`),u=2+s.length+1+a.length,d=Math.max(0,t.name-u),f=`${i} ${c} ${l}${` `.repeat(d)}`,p=bn(e.status,!0),m=(e.status||`unknown`).length+2,h=Math.max(0,t.status-m),g=`${p}${` `.repeat(h)}`,_=e.updatedAt?new Date(e.updatedAt).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`}):`N/A`;return`${f} ${g} ${B.gray(_.padEnd(t.updated))} ${B.white(String(e.taskCount||0).padStart(t.tasks))} ${B.green(String(e.completedTasks||0).padStart(t.done))}`}async promptBriefSelection(e){try{if(!this.authManager.getContext()?.orgId)return;let t=Math.max(process.stdout.columns||120,80),n=Math.floor(t*.95),r={name:Math.floor(n*.42),status:Math.floor(n*.14),updated:Math.floor(n*.16),tasks:6,done:6},i=B.cyan.bold(`Brief Name`.padEnd(r.name))+B.cyan.bold(`Status`.padEnd(r.status))+B.cyan.bold(`Updated`.padEnd(r.updated))+B.cyan.bold(`Tasks`.padStart(r.tasks+2))+B.cyan.bold(`Done`.padStart(r.done+2)),a=B.gray(`─`.repeat(n)),o=[new q.Separator(i),new q.Separator(a)];e.forEach(e=>{o.push({name:this.formatBriefAsTableRow(e,r),value:e.briefId||e.name,short:e.name})}),o.push(new q.Separator(a)),o.push({name:B.dim(` (Cancel - keep current selection)`),value:null,short:`Cancelled`});let s=!1,c=(e,t)=>{t&&t.name===`escape`&&(s=!0,process.stdin.emit(`keypress`,``,{name:`c`,ctrl:!0}))};process.stdin.isTTY&&(nt.emitKeypressEvents(process.stdin),process.stdin.on(`keypress`,c));let l;try{l=await q.prompt([{type:`list`,name:`selectedBrief`,message:`Select a brief:`,choices:o,pageSize:Math.min(e.length+5,20),loop:!1}])}finally{process.stdin.isTTY&&process.stdin.removeListener(`keypress`,c)}if(s)return;if(l.selectedBrief&&l.selectedBrief!==null){let t=e.find(e=>e.briefId===l.selectedBrief||e.name===l.selectedBrief);t&&(await this.authManager.updateContext({briefId:t.briefId||void 0,briefName:t.name,briefStatus:t.status||void 0,briefUpdatedAt:t.updatedAt||void 0}),kn(`Selected brief: ${t.name}`),this.setLastResult({success:!0,action:`select`,currentBrief:t.briefId||t.name,message:`Selected brief: ${t.name}`}))}}catch(e){if(e.isTtyError)return;console.error(B.yellow(`\nNote: Could not prompt for brief selection: ${e.message}`))}}async executeSelect(e){try{if(await this.authManager.hasValidSession()||(Y(`Not authenticated. Run "tm auth login" first.`),process.exit(1)),e&&e.trim().length>0){await this.executeSelectFromUrl(e.trim());return}let t=this.authManager.getContext();t?.orgId||(On(`No organization selected. Run "tm context org" first.`),process.exit(1));let n=await Xn(this.authManager,t.orgId);this.setLastResult({success:n.success,action:`select`,currentBrief:n.briefId,message:n.message}),n.success||process.exit(1)}catch(e){On(`Failed to select brief: ${e.message}`),this.setLastResult({success:!1,action:`select`,message:e.message}),process.exit(1)}}async executeSelectFromUrl(e){try{await this.authManager.hasValidSession()||(Y(`Not authenticated. Run "tm auth login" first.`),process.exit(1)),await this.initTmCore();let t=await Zn(this.authManager,e,this.tmCore);this.setLastResult({success:t.success,action:`select`,currentBrief:t.briefId,message:t.message}),t.success||process.exit(1)}catch(e){On(`Failed to select brief: ${e.message}`),this.setLastResult({success:!1,action:`select`,message:e.message}),process.exit(1)}}async executeCreate(e){try{await this.checkAuth()||process.exit(1);let t=await Kr({tagName:e||`new-brief`,projectRoot:process.cwd(),report:(e,...t)=>{let n=t[0];e===`error`?Y(n):e===`warn`?An(n):e===`info`&&jn(n)}});if(!t)throw Error(`Failed to get brief creation URL`);this.setLastResult({success:t.success,action:`create`,message:t.message}),t.success||process.exit(1)}catch(e){On(`Failed to create brief: ${e.message}`),this.setLastResult({success:!1,action:`create`,message:e.message}),process.exit(1)}}setLastResult(e){this.lastResult=e}getLastResult(){return this.lastResult}static register(t,n){let r=new e(n);return t.addCommand(r),r}},si=class e extends G{tmCore;constructor(e){super(e||`loop`),this.description(`Run coding agent CLI in a loop, one task per iteration`).option(`-n, --iterations <number>`,`Maximum iterations`).option(`-p, --prompt <preset|path>`,`Preset name (${Pe.join(`, `)}) or path to custom prompt file`,`default`).option(`--progress-file <path>`,`Path to progress log file`,`.taskmaster/progress.txt`).option(`-t, --tag <tag>`,`Only work on tasks with this tag`).option(`--project <path>`,`Project root directory (auto-detected if not provided)`).option(`--sandbox`,`Enable sandbox mode (Docker for Claude, native sandbox for Codex)`).option(`-e, --executor <executor>`,`Execution backend (claude|codex)`).option(`--no-output`,`Exclude full executor output from iteration results`).option(`-v, --verbose`,`Show executor's work in real-time`).action(e=>this.execute(e))}async execute(e){let t=e.prompt||`default`,n=e.progressFile||`.taskmaster/progress.txt`;try{this.tmCore=await I({projectPath:We.resolve(Z(e.project))});let r=this.resolveExecutor(e.executor),i=t===`default`?await this.tmCore.tasks.getCount(`pending`,e.tag):void 0,a=this.tmCore.loop.resolveIterations({userIterations:e.iterations?parseInt(e.iterations,10):void 0,preset:t,pendingTaskCount:i});if(this.validateIterations(String(a)),Pn(this.tmCore,{tag:e.tag||`master`,storageType:this.tmCore.tasks.getStorageType()}),e.sandbox&&(r===`claude`?this.handleSandboxAuth(r):console.log(B.dim(`Using Codex native sandbox mode (workspace-write) for loop execution.`))),console.log(B.cyan(`Starting Task Master Loop...`)),console.log(B.dim(`Preset: ${t}`)),console.log(B.dim(`Max iterations: ${a}`)),console.log(B.dim(`Mode: ${e.sandbox?r===`codex`?`Codex sandbox (workspace-write)`:`Docker sandbox (Claude)`:r===`codex`?`Codex CLI`:`Claude CLI`}`)),t===`default`){let t=await this.tmCore.tasks.getNext(e.tag);t?console.log(B.white(`Next task to work on: ${B.white(t.id)} - ${t.title}`)):console.log(B.yellow(`No pending tasks found`))}console.log();let o=this.tmCore.auth.getContext()?.briefName,s={iterations:a,prompt:t,progressFile:n,tag:e.tag,executor:r,sandbox:e.sandbox,includeOutput:e.output??!0,verbose:e.verbose??!1,brief:o,callbacks:this.createOutputCallbacks()},c=await this.tmCore.loop.run(s);this.displayResult(c)}catch(e){X(e,{skipExit:!0}),process.exit(1)}}handleSandboxAuth(e){console.log(B.dim(`Checking sandbox auth...`));let t=this.tmCore.loop.checkSandboxAuth(e);if(t.error)throw Error(t.error);if(t.ready){console.log(B.green(`✓ Sandbox ready`));return}console.log(B.yellow(`Sandbox needs authentication. Starting interactive session...`)),console.log(B.dim(`Please complete auth, then Ctrl+C to continue.
246
246
  `));let n=this.tmCore.loop.runInteractiveAuth(e);if(!n.success)throw Error(n.error||`Interactive authentication failed`);console.log(B.green(`✓ Auth complete
247
- `))}resolveExecutor(e){let t=this.getConfiguredExecutor(),n=this.inferExecutorFromConfig(),r=e??process.env.TASKMASTER_EXECUTOR??t??n??`claude`,i=r.toLowerCase();if(i===`claude`||i===`codex`)return i;throw Error(`Invalid executor "${r}". Supported values: claude, codex.`)}getConfiguredExecutor(){let e=this.tmCore.config.getConfig().custom?.executor;return typeof e==`string`?e:void 0}inferExecutorFromConfig(){let e=this.tmCore.config.getConfig();if(this.isCodexProvider(e.aiProvider))return`codex`;let t=this.asObject(e.models);if(this.isCodexModelConfig(t?.main)||this.isNonEmptyObject(e.codexCli))return`codex`}isCodexModelConfig(e){if(typeof e==`string`)return this.isCodexModelId(e);let t=this.asObject(e);return t?this.isCodexProvider(t.provider)||this.isCodexModelId(t.modelId):!1}isCodexProvider(e){if(typeof e!=`string`)return!1;let t=e.trim().toLowerCase();return t===`codex`||t===`codex-cli`||t===`codex-lb`}isCodexModelId(e){return typeof e==`string`&&e.toLowerCase().includes(`codex`)}asObject(e){if(typeof e==`object`&&e)return e}isNonEmptyObject(e){let t=this.asObject(e);return!!(t&&Object.keys(t).length>0)}validateIterations(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`Invalid iterations: ${e}. Must be a positive integer.`)}createOutputCallbacks(){return{onIterationStart:(e,t)=>{console.log(),console.log(B.cyan(`━━━ Iteration ${e} of ${t} ━━━`))},onText:e=>{console.log(e)},onToolUse:e=>{console.log(B.dim(` → ${e}`))},onError:(e,t)=>{t===`warning`?console.error(B.yellow(`[Loop Warning] ${e}`)):console.error(B.red(`[Loop Error] ${e}`))},onStderr:(e,t)=>{process.stderr.write(B.dim(`[Iteration ${e}] `)+t)},onOutput:e=>{console.log(e)},onIterationEnd:e=>{let t=e.status===`success`?B.green:e.status===`error`?B.red:B.yellow;console.log(t(` Iteration ${e.iteration} completed: ${e.status}`))}}}displayResult(e){console.log(),console.log(B.bold(`Loop Complete`)),console.log(B.dim(`─`.repeat(40))),console.log(`Total iterations: ${e.totalIterations}`),console.log(`Tasks completed: ${e.tasksCompleted}`),console.log(`Final status: ${this.formatStatus(e.finalStatus)}`),e.errorMessage&&console.log(B.red(`Error: ${e.errorMessage}`))}formatStatus(e){return{all_complete:B.green(`All tasks complete`),max_iterations:B.yellow(`Max iterations reached`),blocked:B.red(`Blocked`),error:B.red(`Error`)}[e]}static register(t,n){let r=new e(n);return t.addCommand(r),r}},ci=class extends G{constructor(){super(`init`),this.description(`Initialize AGENTS.md + Skill assets for codex longrun mode`).option(`-p, --project <path>`,`Project root directory`).option(`--skill-path <path>`,`Custom SKILL.md path relative to project root`).option(`--agents-path <path>`,`Custom AGENTS.md path relative to project root`).option(`--agents-mode <mode>`,`How to handle existing AGENTS without hook: append|skip|fail`,`append`).option(`--mode <mode>`,`Execution mode: lite|full|auto`,`full`).option(`--session-dir <path>`,`Custom session directory relative to project root`).option(`--json`,`Output JSON`).action(async e=>{await this.execute(e)})}async execute(e){try{let t=Z(e.project),n=await I({projectPath:t}),r=await n.skillRun.initAssets({skillPath:e.skillPath,agentsPath:e.agentsPath,agentsMode:e.agentsMode,mode:e.mode,sessionDir:e.sessionDir});await n.close();let i=this.buildLoadHints(t,r.paths),a=i.length===2?`Load ${i[0]} -> load ${i[1]} -> continue`:void 0;if(e.json){console.log(JSON.stringify({...r,loadHints:i,immediate_action:a},null,2));return}console.log(B.green(`Codex longrun assets initialized.`)),console.log(B.gray(` AGENTS: ${r.paths.agentsPath}`)),console.log(B.gray(` SKILL : ${r.paths.skillPath}`)),console.log(B.gray(` Session: ${r.paths.sessionDir}`)),i.length===2&&(console.log(B.white(` Ask Codex to load: ${i[0]} then ${i[1]}`)),console.log(`TM_IMMEDIATE_ACTION: LOAD ${i[0]}`),console.log(`TM_IMMEDIATE_ACTION: LOAD ${i[1]}`)),r.created.length>0&&console.log(B.green(` Created: ${r.created.join(`, `)}`)),r.updated.length>0&&console.log(B.yellow(` Updated: ${r.updated.join(`, `)}`))}catch(e){X(e,{skipExit:!0}),process.exit(1)}}buildLoadHints(e,t){let n=t.skillPath;return[t.skillAgentsPath??H.join(H.dirname(t.skillPath),`AGENTS.md`),n].map(t=>`@${H.relative(e,t).split(H.sep).join(`/`)}`)}},li=class extends G{constructor(){super(`run`),this.alias(`start`),this.description(`Run long-horizon codex execution with Taskmaster task scheduling`).option(`-p, --project <path>`,`Project root directory`).option(`-t, --tag <tag>`,`Tag context for tasks`).option(`--max-retries <n>`,`Retries before marking a task blocked`,`3`).option(`--skill-path <path>`,`Custom SKILL.md path relative to project root`).option(`--agents-path <path>`,`Custom AGENTS.md path relative to project root`).option(`--agents-mode <mode>`,`How to handle existing AGENTS without hook: append|skip|fail`,`append`).option(`--mode <mode>`,`Execution mode: lite|full|auto`,`full`).option(`--session-dir <path>`,`Custom session directory relative to project root`).option(`-e, --executor <cmd>`,`Executor command`,`codex`).option(`-m, --model <model>`,`Model for codex exec`).option(`--reasoning-effort <level>`,`low|medium|high|xhigh`).option(`--exec-idle-timeout-ms <ms>`,`Per-task idle timeout in milliseconds (0 to disable)`).option(`--exec-hard-timeout-ms <ms>`,`Per-task hard timeout in milliseconds (0 to disable)`).option(`--exec-timeout-ms <ms>`,`[Deprecated] Alias of --exec-hard-timeout-ms`).option(`--no-terminate-on-result`,`Do not terminate executor after TM_RESULT is detected`).option(`--no-full-auto`,`Disable --full-auto for codex exec`).option(`--no-skip-git-repo-check`,`Disable --skip-git-repo-check for codex exec`).option(`--max-tasks <n>`,`Stop after N execution attempts`).option(`--no-continue-on-failure`,`Stop when one task fails`).option(`--json`,`Output JSON summary`).action(async e=>{await this.execute(e)})}async execute(e){try{let t=await I({projectPath:Z(e.project)});console.log(B.cyan(`Starting Codex longrun execution...`));let n=await t.skillRun.run({tag:e.tag,maxRetries:Number.parseInt(e.maxRetries||`3`,10),skillPath:e.skillPath,agentsPath:e.agentsPath,agentsMode:e.agentsMode,mode:e.mode,sessionDir:e.sessionDir,executor:e.executor,model:e.model,reasoningEffort:e.reasoningEffort,execIdleTimeoutMs:this.parseOptionalInteger(e.execIdleTimeoutMs),execHardTimeoutMs:this.parseOptionalInteger(e.execHardTimeoutMs),execTimeoutMs:this.parseOptionalInteger(e.execTimeoutMs),terminateOnResult:e.terminateOnResult,fullAuto:e.fullAuto,skipGitRepoCheck:e.skipGitRepoCheck,maxTasks:e.maxTasks?Number.parseInt(e.maxTasks,10):void 0,continueOnFailure:e.continueOnFailure,callbacks:{onTaskStart:(e,t)=>{console.log(B.white(`\n[Task ${e.id}] ${e.title} (attempt ${t})`))},onTaskEnd:e=>{console.log(B.gray(`[${e.status}] ${e.taskId} exit=${e.exitCode} duration=${e.durationMs}ms log=${e.logFile}`))}}});if(await t.close(),e.json){console.log(JSON.stringify(n,null,2));return}console.log(`
247
+ `))}resolveExecutor(e){let t=this.getConfiguredExecutor(),n=this.inferExecutorFromConfig(),r=e??process.env.TASKMASTER_EXECUTOR??t??n??`claude`,i=r.toLowerCase();if(i===`claude`||i===`codex`)return i;throw Error(`Invalid executor "${r}". Supported values: claude, codex.`)}getConfiguredExecutor(){let e=this.tmCore.config.getConfig().custom?.executor;return typeof e==`string`?e:void 0}inferExecutorFromConfig(){let e=this.tmCore.config.getConfig();if(this.isCodexProvider(e.aiProvider))return`codex`;let t=this.asObject(e.models);if(this.isCodexModelConfig(t?.main)||this.isNonEmptyObject(e.codexCli))return`codex`}isCodexModelConfig(e){if(typeof e==`string`)return this.isCodexModelId(e);let t=this.asObject(e);return t?this.isCodexProvider(t.provider)||this.isCodexModelId(t.modelId):!1}isCodexProvider(e){if(typeof e!=`string`)return!1;let t=e.trim().toLowerCase();return t===`codex`||t===`codex-cli`||t===`codex-lb`}isCodexModelId(e){return typeof e==`string`&&e.toLowerCase().includes(`codex`)}asObject(e){if(typeof e==`object`&&e)return e}isNonEmptyObject(e){let t=this.asObject(e);return!!(t&&Object.keys(t).length>0)}validateIterations(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw Error(`Invalid iterations: ${e}. Must be a positive integer.`)}createOutputCallbacks(){return{onIterationStart:(e,t)=>{console.log(),console.log(B.cyan(`━━━ Iteration ${e} of ${t} ━━━`))},onText:e=>{console.log(e)},onToolUse:e=>{console.log(B.dim(` → ${e}`))},onError:(e,t)=>{t===`warning`?console.error(B.yellow(`[Loop Warning] ${e}`)):console.error(B.red(`[Loop Error] ${e}`))},onStderr:(e,t)=>{process.stderr.write(B.dim(`[Iteration ${e}] `)+t)},onOutput:e=>{console.log(e)},onIterationEnd:e=>{let t=e.status===`success`?B.green:e.status===`error`?B.red:B.yellow;console.log(t(` Iteration ${e.iteration} completed: ${e.status}`))}}}displayResult(e){console.log(),console.log(B.bold(`Loop Complete`)),console.log(B.dim(`─`.repeat(40))),console.log(`Total iterations: ${e.totalIterations}`),console.log(`Tasks completed: ${e.tasksCompleted}`),console.log(`Final status: ${this.formatStatus(e.finalStatus)}`),e.errorMessage&&console.log(B.red(`Error: ${e.errorMessage}`))}formatStatus(e){return{all_complete:B.green(`All tasks complete`),max_iterations:B.yellow(`Max iterations reached`),blocked:B.red(`Blocked`),error:B.red(`Error`)}[e]}static register(t,n){let r=new e(n);return t.addCommand(r),r}},ci=class extends G{constructor(){super(`init`),this.description(`Initialize AGENTS.md + Skill assets for codex longrun mode`).option(`-p, --project <path>`,`Project root directory`).option(`--skill-path <path>`,`Custom SKILL.md path relative to project root`).option(`--agents-path <path>`,`Custom AGENTS.md path relative to project root`).option(`--agents-mode <mode>`,`How to handle existing AGENTS without hook: append|skip|fail`,`append`).option(`--mode <mode>`,`Execution mode: lite|full|auto`,`full`).option(`--session-dir <path>`,`Custom session directory relative to project root`).option(`--json`,`Output JSON`).action(async e=>{await this.execute(e)})}async execute(e){try{let t=Z(e.project),n=await I({projectPath:t}),r=await n.skillRun.initAssets({skillPath:e.skillPath,agentsPath:e.agentsPath,agentsMode:e.agentsMode,mode:e.mode,sessionDir:e.sessionDir});await n.close();let i=this.buildLoadHints(t,r.paths),a=i.length===2?`Load ${i[0]} -> load ${i[1]} -> continue`:void 0;if(e.json){console.log(JSON.stringify({...r,loadHints:i,immediate_action:a},null,2));return}console.log(B.green(`Codex longrun assets initialized.`)),console.log(B.gray(` AGENTS: ${r.paths.agentsPath}`)),console.log(B.gray(` SKILL : ${r.paths.skillPath}`)),console.log(B.gray(` Session: ${r.paths.sessionDir}`)),i.length===2&&(console.log(B.white(` Ask Codex to load: ${i[0]} then ${i[1]}`)),console.log(`TM_IMMEDIATE_ACTION: LOAD ${i[0]}`),console.log(`TM_IMMEDIATE_ACTION: LOAD ${i[1]}`)),r.created.length>0&&console.log(B.green(` Created: ${r.created.join(`, `)}`)),r.updated.length>0&&console.log(B.yellow(` Updated: ${r.updated.join(`, `)}`))}catch(e){X(e,{skipExit:!0}),process.exit(1)}}buildLoadHints(e,t){let n=t.skillPath;return[t.skillAgentsPath??H.join(H.dirname(t.skillPath),`AGENTS.md`),n].map(t=>`@${H.relative(e,t).split(H.sep).join(`/`)}`)}},li=class extends G{constructor(){super(`run`),this.alias(`start`),this.description(`Run long-horizon codex execution with Taskmaster task scheduling`).option(`-p, --project <path>`,`Project root directory`).option(`-t, --tag <tag>`,`Tag context for tasks`).option(`--max-retries <n>`,`Retries before marking a task blocked`,`3`).option(`--skill-path <path>`,`Custom SKILL.md path relative to project root`).option(`--agents-path <path>`,`Custom AGENTS.md path relative to project root`).option(`--agents-mode <mode>`,`How to handle existing AGENTS without hook: append|skip|fail`,`append`).option(`--mode <mode>`,`Execution mode: lite|full|auto`,`full`).option(`--session-dir <path>`,`Custom session directory relative to project root`).option(`-e, --executor <cmd>`,`Executor command`,`codex`).option(`-m, --model <model>`,`Model for codex exec`).option(`--reasoning-effort <level>`,`low|medium|high|xhigh`).option(`--no-show-executor-output`,`Disable real-time stdout/stderr output from codex exec`).option(`--exec-idle-timeout-ms <ms>`,`Per-task idle timeout in milliseconds (0 to disable)`).option(`--exec-hard-timeout-ms <ms>`,`Per-task hard timeout in milliseconds (0 to disable)`).option(`--exec-timeout-ms <ms>`,`[Deprecated] Alias of --exec-hard-timeout-ms`).option(`--no-terminate-on-result`,`Do not terminate executor after TM_RESULT is detected`).option(`--no-full-auto`,`Disable --full-auto for codex exec`).option(`--no-skip-git-repo-check`,`Disable --skip-git-repo-check for codex exec`).option(`--max-tasks <n>`,`Stop after N execution attempts`).option(`--no-continue-on-failure`,`Stop when one task fails`).option(`--json`,`Output JSON summary`).action(async e=>{await this.execute(e)})}async execute(e){try{let t=await I({projectPath:Z(e.project)});console.log(B.cyan(`Starting Codex longrun execution...`));let n=await t.skillRun.run({tag:e.tag,maxRetries:Number.parseInt(e.maxRetries||`3`,10),skillPath:e.skillPath,agentsPath:e.agentsPath,agentsMode:e.agentsMode,mode:e.mode,sessionDir:e.sessionDir,executor:e.executor,model:e.model,reasoningEffort:e.reasoningEffort,showExecutorOutput:e.showExecutorOutput,execIdleTimeoutMs:this.parseOptionalInteger(e.execIdleTimeoutMs),execHardTimeoutMs:this.parseOptionalInteger(e.execHardTimeoutMs),execTimeoutMs:this.parseOptionalInteger(e.execTimeoutMs),terminateOnResult:e.terminateOnResult,fullAuto:e.fullAuto,skipGitRepoCheck:e.skipGitRepoCheck,maxTasks:e.maxTasks?Number.parseInt(e.maxTasks,10):void 0,continueOnFailure:e.continueOnFailure,callbacks:{onTaskStart:(e,t)=>{console.log(B.white(`\n[Task ${e.id}] ${e.title} (attempt ${t})`))},onTaskEnd:e=>{console.log(B.gray(`[${e.status}] ${e.taskId} exit=${e.exitCode} duration=${e.durationMs}ms log=${e.logFile}`))},onInfo:e=>{console.log(B.gray(`[info] ${e}`))},onWarning:e=>{console.log(B.yellow(`[warn] ${e}`))}}});if(await t.close(),e.json){console.log(JSON.stringify(n,null,2));return}console.log(`
248
248
  `+B.bold(`Longrun Summary`)),console.log(B.gray(` Final status: ${n.finalStatus}`)),console.log(B.gray(` Completed: ${n.completedTaskIds.length}`)),console.log(B.gray(` Blocked: ${n.blockedTaskIds.length}`)),console.log(B.gray(` Total runs: ${n.totalRuns}`))}catch(e){X(e,{skipExit:!0}),process.exit(1)}}parseOptionalInteger(e){if(typeof e!=`string`||e.trim().length===0)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:t}},ui=class e extends G{constructor(){super(`codex`),this.description(`Codex native extension commands (skill init/run)`),this.alias(`skill-run`),this.addCommand(new ci),this.addCommand(new li)}static register(t){let n=new e;return t.addCommand(n),n}},di=class{constructor(e){this.useJson=e}output(e){this.useJson?console.log(JSON.stringify(e,null,2)):this.outputText(e)}outputText(e){for(let[t,n]of Object.entries(e))typeof n==`object`&&n?(console.log(B.cyan(`${t}:`)),this.outputObject(n,` `)):console.log(B.white(`${t}: ${n}`))}outputObject(e,t){for(let[n,r]of Object.entries(e))typeof r==`object`&&r?(console.log(B.cyan(`${t}${n}:`)),this.outputObject(r,t+` `)):console.log(B.gray(`${t}${n}: ${r}`))}error(e,t){if(this.useJson)console.error(JSON.stringify({error:e,...t},null,2));else if(console.error(B.red(`Error: ${e}`)),t)for(let[e,n]of Object.entries(t))console.error(B.gray(` ${e}: ${n}`))}success(e,t){this.useJson?console.log(JSON.stringify({success:!0,message:e,...t},null,2)):(console.log(B.green(`✓ ${e}`)),t&&this.output(t))}warning(e){this.useJson?console.warn(JSON.stringify({warning:e},null,2)):console.warn(B.yellow(`⚠️ ${e}`))}info(e){this.useJson||console.log(B.blue(`ℹ ${e}`))}},fi=class extends G{constructor(){super(`abort`),this.description(`Abort the current TDD workflow and clean up state`).option(`-f, --force`,`Force abort without confirmation`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:``},r=new di(e.json||t?.json||!1);try{let i=Z(e.projectRoot||t?.projectRoot);n={...n,projectRoot:i};let a=await I({projectPath:i});if(!await a.workflow.hasWorkflow()){r.warning(`No active workflow to abort`);return}await a.workflow.resume();let o=a.workflow.getStatus();if(!n.force&&!n.json){let{confirmed:e}=await q.prompt([{type:`confirm`,name:`confirmed`,message:`This will abort the workflow for task ${o.taskId}. Progress: ${o.progress?.completed||0}/${o.progress?.total||0} subtasks completed. Continue?`,default:!1}]);if(!e){r.info(`Abort cancelled`);return}}await a.workflow.abort(),r.success(`Workflow aborted`,{taskId:o.taskId,branchName:o.branchName,progress:o.progress,lastSubtask:o.currentSubtask?{id:o.currentSubtask.id,title:o.currentSubtask.title}:null,note:`Branch and commits remain. Clean up manually if needed.`})}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},pi=class extends G{constructor(){super(`commit`),this.description(`Create a commit for the completed GREEN phase`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:Z(e.projectRoot||t?.projectRoot)},r=new di(n.json||!1);try{let e=n.projectRoot,t=await I({projectPath:e});await t.workflow.hasWorkflow()||(r.error(`No active workflow`,{suggestion:`Start a workflow with: autopilot start <taskId>`}),process.exit(1)),await t.workflow.resume();let i=t.workflow.getStatus(),a=t.workflow.getContext();i.tddPhase!==`COMMIT`&&(r.error(`Not in COMMIT phase`,{currentPhase:i.tddPhase||i.phase,suggestion:`Complete RED and GREEN phases first`}),process.exit(1)),i.currentSubtask||(r.error(`No current subtask`),process.exit(1));let o=new Oe(e);await o.ensureGitRepository(),await o.hasStagedChanges()||(r.info(`No staged changes, staging all changes...`),await o.stageFiles([`.`]));let s=await o.getStatus(),c=[...s.staged,...s.modified],l=new oe,u=a.lastTestResults,d=l.generateMessage({type:`feat`,description:i.currentSubtask.title,changedFiles:c,taskId:i.taskId,phase:i.tddPhase,tag:a.metadata.tag||void 0,testsPassing:u?.passed,testsFailing:u?.failed,coveragePercent:void 0});await o.createCommit(d,{metadata:{taskId:i.taskId,subtaskId:i.currentSubtask.id,phase:`COMMIT`,tddCycle:`complete`}});let f=await o.getLastCommit(),p=await t.workflow.commit(),m=p.phase===`COMPLETE`;r.success(`Commit created`,{commitHash:f.hash.substring(0,7),message:d.split(`
249
249
  `)[0],subtask:{id:i.currentSubtask.id,title:i.currentSubtask.title},progress:p.progress,nextAction:m?`All subtasks complete. Run: autopilot status`:`Start next subtask with RED phase`})}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},mi=class extends G{constructor(){super(`complete`),this.description(`Complete the current TDD phase with result validation`).option(`-r, --results <json>`,`Test results JSON (with total, passed, failed, skipped)`).option(`-c, --coverage <percent>`,`Coverage percentage`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:Z(e.projectRoot||t?.projectRoot)},r=new di(n.json||!1);try{let e=n.projectRoot,t=await I({projectPath:e});await t.workflow.hasWorkflow()||(r.error(`No active workflow`,{suggestion:`Start a workflow with: autopilot start <taskId>`}),process.exit(1)),await t.workflow.resume();let i=t.workflow.getStatus(),a=i.tddPhase,o=i.currentSubtask;if(a||(r.error(`Not in a TDD phase`,{phase:i.phase}),process.exit(1)),a===`RED`||a===`GREEN`){n.results||(r.error(`Test results required for RED/GREEN phase`,{usage:`--results '{"total":10,"passed":9,"failed":1,"skipped":0}'`}),process.exit(1));let e;try{let t=JSON.parse(n.results);e={total:t.total||0,passed:t.passed||0,failed:t.failed||0,skipped:t.skipped||0,phase:a}}catch(e){r.error(`Invalid test results JSON`,{error:e.message}),process.exit(1)}a===`RED`&&e.failed===0&&(r.error(`RED phase validation failed`,{reason:`At least one test must be failing`,actual:{passed:e.passed,failed:e.failed}}),process.exit(1)),a===`GREEN`&&e.failed!==0&&(r.error(`GREEN phase validation failed`,{reason:`All tests must pass`,actual:{passed:e.passed,failed:e.failed}}),process.exit(1));let i=await t.workflow.completePhase(e);a===`RED`?r.success(`RED phase completed`,{nextPhase:i.tddPhase||`GREEN`,testResults:e,subtask:o?.title}):r.success(`GREEN phase completed`,{nextPhase:i.tddPhase||`COMMIT`,testResults:e,subtask:o?.title,suggestion:`Run: autopilot commit`})}else a===`COMMIT`&&(r.error(`Use "autopilot commit" to complete COMMIT phase`),process.exit(1))}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},hi=class extends G{constructor(){super(`finalize`),this.description(`Finalize and complete the workflow. Validates working tree is clean.`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:``},r=new di(e.json||t?.json||!1);try{let i=Z(e.projectRoot||t?.projectRoot);n={...n,projectRoot:i};let a=await I({projectPath:i});await a.workflow.hasWorkflow()||(r.error(`No active workflow`,{suggestion:`Start a workflow with: autopilot start <taskId>`}),process.exit(1)),await a.workflow.resume();let o=a.workflow.getStatus();o.phase!==`FINALIZE`&&(r.error(`Cannot finalize: workflow is in ${o.phase} phase`,{suggestion:`Complete all subtasks first`}),process.exit(1)),r.info(`Validating working tree and finalizing workflow...`);let s=await a.workflow.finalize();r.success(`Workflow completed`,{taskId:s.taskId,phase:s.phase,branchName:s.branchName,progress:s.progress})}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},gi=class extends G{constructor(){super(`next`),this.description(`Get the next action to perform in the TDD workflow`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:``},r=new di(e.json||t?.json||!1);try{let i=Z(e.projectRoot||t?.projectRoot);n={...n,projectRoot:i};let a=await I({projectPath:i});await a.workflow.hasWorkflow()||(r.error(`No active workflow`,{suggestion:`Start a workflow with: autopilot start <taskId>`}),process.exit(1)),await a.workflow.resume();let o=a.workflow.getStatus(),s=a.workflow.getNextAction(),c=a.workflow.getContext(),l=this.resolveExecutor(a,n.executor),u=o.phase,d=o.tddPhase,f=o.currentSubtask;if(u===`COMPLETE`){r.success(`Workflow complete`,{message:`All subtasks have been completed`,taskId:o.taskId});return}let p=await this.buildExecutionHint(a,o.taskId,o.phase,o.tddPhase,o.currentSubtask?.id,l),m=p?.command?`${s.nextSteps}\n\nLaunch coding agent:\n${p.command}`:s.nextSteps,h={action:s.action,description:s.description,phase:u,tddPhase:d,taskId:o.taskId,branchName:o.branchName,subtask:f?{id:f.id,title:f.title,attempts:f.attempts}:null,nextSteps:m,lastTestResults:c.lastTestResults,execution:p??{executor:l}};n.json?r.output(h):r.success(`Next action`,h)}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}async buildExecutionHint(e,t,n,r,i,a){if(n!==`SUBTASK_LOOP`||!i)return null;if(r!==`RED`&&r!==`GREEN`)return{executor:a};let o=this.composeWorkItemId(t,i),s=await e.tasks.start(o,{dryRun:!0,force:!0,updateStatus:!1,executor:a});return{executor:a,workItemId:o,command:s.command?this.buildShellCommand(s.command.executable,s.command.args):void 0}}composeWorkItemId(e,t){let n=String(t);return n.includes(`.`)?n:`${e}.${n}`}buildShellCommand(e,t){return[e,...t.map(e=>this.shellEscapeArg(e))].join(` `)}shellEscapeArg(e){return e?`'${e.replace(/'/g,`'"'"'`)}'`:`''`}resolveExecutor(e,t){let n=this.getConfiguredExecutor(e),r=this.inferExecutorFromConfig(e),i=t??process.env.TASKMASTER_EXECUTOR??n??r??`claude`,a=i.toLowerCase();if(a===`claude`||a===`codex`)return a;throw Error(`Invalid executor "${i}". Supported values: claude, codex.`)}getConfiguredExecutor(e){let t=e.config.getConfig().custom?.executor;return typeof t==`string`?t:void 0}inferExecutorFromConfig(e){let t=e.config.getConfig();if(this.isCodexProvider(t.aiProvider))return`codex`;let n=this.asObject(t.models);if(this.isCodexModelConfig(n?.main)||this.isNonEmptyObject(t.codexCli))return`codex`}isCodexModelConfig(e){if(typeof e==`string`)return this.isCodexModelId(e);let t=this.asObject(e);return t?this.isCodexProvider(t.provider)||this.isCodexModelId(t.modelId):!1}isCodexProvider(e){if(typeof e!=`string`)return!1;let t=e.trim().toLowerCase();return t===`codex`||t===`codex-cli`||t===`codex-lb`}isCodexModelId(e){return typeof e==`string`&&e.toLowerCase().includes(`codex`)}asObject(e){if(typeof e==`object`&&e)return e}isNonEmptyObject(e){let t=this.asObject(e);return!!(t&&Object.keys(t).length>0)}},_i=class extends G{constructor(){super(`resume`),this.description(`Resume a previously started TDD workflow`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:Z(e.projectRoot||t?.projectRoot)},r=new di(n.json||!1);try{let e=n.projectRoot,t=await I({projectPath:e});await t.workflow.hasWorkflow()||(r.error(`No workflow state found`,{suggestion:`Start a new workflow with: autopilot start <taskId>`}),process.exit(1)),r.info(`Loading workflow state...`);let i=await t.workflow.resume();r.success(`Workflow resumed`,{taskId:i.taskId,phase:i.phase,tddPhase:i.tddPhase,branchName:i.branchName,progress:i.progress,currentSubtask:i.currentSubtask?{id:i.currentSubtask.id,title:i.currentSubtask.title,attempts:i.currentSubtask.attempts}:null})}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},vi=class extends G{constructor(){super(`start`),this.description(`Initialize and start a new TDD workflow for a task`).argument(`<taskId>`,`Task ID to start workflow for`).option(`-f, --force`,`Force start even if workflow state exists`).option(`--max-attempts <number>`,`Maximum attempts per subtask`,`3`).action(async(e,t)=>{await this.execute(e,t)})}async execute(e,t){let n=this.parent?.opts(),r={...n,...t,projectRoot:Z(t.projectRoot||n?.projectRoot)},i=new di(r.json||!1);try{let t=ae.safeParse(e);t.success||(i.error(`Invalid task ID format`,{taskId:e,error:t.error.issues[0]?.message}),process.exit(1));let n=t.data,a=r.projectRoot,o=await I({projectPath:a});await o.workflow.hasWorkflow()&&!r.force&&(i.error(`Workflow state already exists. Use --force to overwrite or resume with "autopilot resume"`),process.exit(1));let s=o.config.getActiveTag(),c=o.auth.getContext()?.orgSlug;i.info(`Loading task ${n}...`);let{task:l}=await o.tasks.get(n);l||(i.error(`Task not found`,{taskId:n}),process.exit(1)),(!l.subtasks||l.subtasks.length===0)&&(i.error(`Task has no subtasks. Expand task first.`,{taskId:n,suggestion:`Run: task-master expand --id=${n}`}),process.exit(1));let u=parseInt(r.maxAttempts||`3`,10);i.info(`Starting TDD workflow...`);let d=await o.workflow.start({taskId:n,taskTitle:l.title,subtasks:l.subtasks.map(e=>({id:e.id,title:e.title,status:e.status,maxAttempts:u})),maxAttempts:u,force:r.force,tag:s,orgSlug:c});i.success(`TDD workflow started`,{taskId:d.taskId,title:l.title,phase:d.phase,tddPhase:d.tddPhase,branchName:d.branchName,subtasks:l.subtasks.length,currentSubtask:d.currentSubtask?.title})}catch(e){i.error(e.message),r.verbose&&console.error(e.stack),process.exit(1)}}},yi=class extends G{constructor(){super(`status`),this.description(`Show current TDD workflow status and progress`).action(async e=>{await this.execute(e)})}async execute(e){let t=this.parent?.opts(),n={...t,...e,projectRoot:Z(e.projectRoot||t?.projectRoot)},r=new di(n.json||!1);try{let e=n.projectRoot,t=await I({projectPath:e});if(!await t.workflow.hasWorkflow()){n.json?r.output({active:!1,message:`No active workflow`}):(r.info(`No active workflow`),console.log(`Start a workflow with: autopilot start <taskId>`));return}await t.workflow.resume();let i=t.workflow.getStatus(),a=t.workflow.getContext(),o={taskId:i.taskId,phase:i.phase,tddPhase:i.tddPhase,branchName:i.branchName,progress:i.progress,currentSubtask:i.currentSubtask?{id:i.currentSubtask.id,title:i.currentSubtask.title,attempts:i.currentSubtask.attempts,maxAttempts:i.currentSubtask.maxAttempts}:null,subtasks:a.subtasks.map(e=>({id:e.id,title:e.title,status:e.status,attempts:e.attempts})),errors:a.errors&&a.errors.length>0?a.errors:void 0,metadata:a.metadata};n.json?r.output(o):r.success(`Workflow status`,o)}catch(e){r.error(e.message),n.verbose&&console.error(e.stack),process.exit(1)}}},bi=class e extends G{constructor(){super(`autopilot`),this.description(`AI agent orchestration for TDD workflow execution`).alias(`ap`).option(`--json`,`Output in JSON format for machine parsing`).option(`-v, --verbose`,`Enable verbose output`).option(`-e, --executor <executor>`,`Execution backend (claude|codex)`).option(`-p, --project-root <path>`,`Project root directory (auto-detected if not specified)`),this.registerSubcommands()}registerSubcommands(){this.addCommand(new vi),this.addCommand(new _i),this.addCommand(new gi),this.addCommand(new mi),this.addCommand(new pi),this.addCommand(new yi),this.addCommand(new hi),this.addCommand(new fi)}static register(t){let n=new e;return t.addCommand(n),n}},xi=class e extends G{tmCore;lastResult;constructor(e){super(e||`generate`),this.description(`Generate individual task files from tasks.json`).option(`-t, --tag <tag>`,`Tag context for task operations`).option(`-o, --output <dir>`,`Output directory for generated files (defaults to .taskmaster/tasks)`).option(`-p, --project <path>`,`Project root directory (auto-detected if not provided)`).option(`-f, --format <format>`,`Output format (text, json)`,`text`).action(async e=>{await this.executeCommand(e)})}async executeCommand(e){let t=!1;try{this.validateOptions(e);let t=Z(e.project);await this.initializeCore(t);let n=await this.generateFiles(t,e);this.lastResult=n,this.displayResults(n,e)}catch(e){t=!0,X(e,{skipExit:!0})}finally{await this.cleanup()}t&&process.exit(1)}validateOptions(e){if(e.format&&![`text`,`json`].includes(e.format))throw Error(`Invalid format: ${e.format}. Valid formats are: text, json`)}async initializeCore(e){this.tmCore||=await I({projectPath:We.resolve(e)})}async generateFiles(e,t){if(!this.tmCore)throw Error(`TmCore not initialized`);let n=t.output?We.resolve(e,t.output):void 0;return this.tmCore.tasks.generateTaskFiles({tag:t.tag,outputDir:n})}displayResults(e,t){switch(t.format||`text`){case`json`:this.displayJson(e);break;case`text`:default:this.displayText(e,t);break}}displayJson(e){console.log(JSON.stringify(e,null,2))}displayText(e,t){if(this.tmCore){let e=this.tmCore.tasks.getStorageType(),n=t.tag||this.tmCore.config.getActiveTag();Pn(this.tmCore,{tag:n,storageType:e})}if(!e.success){console.log(W(B.red(`Error: ${e.error||`Unknown error`}`),{padding:1,borderStyle:`round`,borderColor:`red`,title:`❌ GENERATION FAILED`,titleAlignment:`center`}));return}if(e.count===0){console.log(W(B.yellow(`No tasks found to generate files for.`),{padding:1,borderStyle:`round`,borderColor:`yellow`,title:`⚠️ NO TASKS`,titleAlignment:`center`}));return}let n=`${B.green(`✓`)} Generated ${B.cyan(e.count)} task file(s)`;n+=`\n\n${B.dim(`Output directory:`)} ${e.directory}`,e.orphanedFilesRemoved>0&&(n+=`\n${B.dim(`Orphaned files removed:`)} ${e.orphanedFilesRemoved}`),console.log(W(n,{padding:1,borderStyle:`round`,borderColor:`green`,title:`📄 TASK FILES GENERATED`,titleAlignment:`center`}))}getLastResult(){return this.lastResult}async cleanup(){this.tmCore&&=void 0}static register(t,n){let r=new e(n);return t.addCommand(r),r}},Si=class e extends G{authCommand;constructor(e){super(e||`login`),this.authCommand=new er,this.description(`Login to Hamster (alias for "auth login")`),this.argument(`[token]`,`Authentication token (optional, for SSH/remote environments)`),this.option(`-y, --yes`,`Skip interactive prompts`),this.addHelpText(`after`,`
250
250
  Examples:
@@ -954,7 +954,7 @@ ${B.cyan(`1.`)} Run ${B.yellow(`task-master next`)} to see what to work on next\
954
954
  ${B.cyan(`1.`)} Run ${B.yellow(`task-master list`)} to view all tasks\n${B.cyan(`2.`)} Run ${B.yellow(`task-master expand --id=<id>`)} to break down a task into subtasks\n${B.cyan(`3.`)} Run ${B.yellow(`task-master analyze-complexity`)} to analyze task complexity`;console.log(W(e,as.nextSteps))}function vs(e){return Math.ceil(e.length/4)}function ys(e){let t=V.readFileSync(e,`utf8`);if(!t)throw Error(`Input file ${e} is empty or could not be read.`);return t}function bs(e,t){let n=[],r=1;if(!V.existsSync(e))return{existingTasks:n,nextId:r};try{let i=V.readFileSync(e,`utf8`),a=JSON.parse(i);a[t]?.tasks&&Array.isArray(a[t].tasks)&&(n=a[t].tasks,n.length>0&&(r=Math.max(...n.map(e=>e.id||0))+1))}catch{return{existingTasks:[],nextId:1}}return{existingTasks:n,nextId:r}}function xs({existingTasks:e,targetTag:t,append:n,force:r,isMCP:i,logger:a}){if(!(e.length>0)){a.report(`Tag '${t}' is empty or doesn't exist. Creating/updating tag with new tasks.`,`info`);return}if(n){a.report(`Append mode enabled. Found ${e.length} existing tasks in tag '${t}'.`,`info`);return}if(!r){let n=`Tag '${t}' already contains ${e.length} tasks. Use --force to overwrite or --append to add to existing tasks.`;if(a.report(n,`error`),i)throw Error(n);console.error(B.red(n)),process.exit(1)}a.report(`Force flag enabled. Overwriting existing tasks in tag '${t}'.`,`debug`)}function Ss(e,t,n,r){Cs(e,t);let i=t,a=new Map,o=e.map(e=>{let t=i++;return a.set(e.id,t),{...e,id:t,status:e.status||`pending`,priority:e.priority||r,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],subtasks:e.subtasks||[],title:e.title||``,description:e.description||``,details:e.details||``,testStrategy:e.testStrategy||``}});return o.forEach(e=>{e.dependencies=e.dependencies.map(e=>a.get(e)).filter(t=>t!=null&&t<e.id&&(ie(n,t)||o.some(e=>e.id===t)))}),o}function Cs(e,t=1){if(!Array.isArray(e)||e.length===0)return;let n=e.map(e=>e.id);if(n.some(e=>!Number.isInteger(e)||e<1))throw Error(`PRD tasks must use sequential positive integer IDs starting at 1.`);let r=new Set(n);if(r.size!==n.length)throw Error(`PRD task IDs must be unique and sequential starting at 1.`);let i=[...r].sort((e,t)=>e-t),a=i[0];if(a!==1&&a!==t)throw Error(`PRD task IDs must start at 1 or ${t} and be sequential.`);for(let e=0;e<i.length;e+=1)if(i[e]!==a+e)throw Error(`PRD task IDs must be a contiguous sequence starting at ${a}.`)}function ws(e,t,n,r){let i=H.dirname(e);V.existsSync(i)||V.mkdirSync(i,{recursive:!0});let a={};if(V.existsSync(e))try{let t=V.readFileSync(e,`utf8`);a=JSON.parse(t)}catch{a={}}a[n]={tasks:t,metadata:{created:a[n]?.metadata?.created||new Date().toISOString(),updated:new Date().toISOString(),description:`Tasks for ${n} context`}},ne(a[n],{description:`Tasks for ${n} context`}),V.writeFileSync(e,JSON.stringify(a,null,2)),r.report(`Successfully saved ${t.length} tasks to ${e}`,`debug`)}async function Ts(e,t,n){let r=La(),i=ce(e.projectRoot)||`medium`;return r.loadPrompt(`parse-prd`,{research:e.research,numTasks:e.numTasks,nextId:n,prdContent:t,prdPath:e.prdPath,defaultTaskPriority:i,hasCodebaseAnalysis:e.hasCodebaseAnalysis({command:`parse-prd`,prdContent:t,numTasks:e.numTasks}),projectRoot:e.projectRoot||``})}async function Es({task:e,currentCount:t,totalTasks:n,estimatedTokens:r,progressTracker:i,reportProgress:a,priorityMap:o,defaultPriority:s,estimatedInputTokens:c}){let l=e.priority||s,u=o[l]||o.medium;if(i&&(i.addTaskLine(t,e.title,l),r&&i.updateTokens(c,r)),a)try{let i=r?Math.floor(r/n):0;await a({progress:t,total:n,message:`${u} Task ${t}/${n} - ${e.title} | ~Output: ${i} tokens`})}catch{}}async function Ds({processedTasks:e,nextId:t,summary:n,prdPath:r,tasksPath:i,usedFallback:a,aiServiceResponse:o}){let s=(()=>{if(!Array.isArray(e)||e.length===0)return`task_${String(t).padStart(3,`0`)}.txt`;let n=e[0].id,r=e[e.length-1].id;return e.length===1?`task_${String(n).padStart(3,`0`)}.txt`:`task_${String(n).padStart(3,`0`)}.txt -> task_${String(r).padStart(3,`0`)}.txt`})();hs({totalTasks:e.length,taskPriorities:n.taskPriorities,prdFilePath:r,outputPath:i,elapsedTime:n.elapsedTime,usedFallback:a,taskFilesGenerated:s,actionVerb:n.actionVerb}),o?.telemetryData&&(o.mainResult?.usage&&await Xo.withSoftTimeout(o.mainResult.usage,1e3,void 0),Ml(o.telemetryData,`cli`))}function Os({processedTasks:e,research:t,finalTasks:n,tasksPath:r,aiServiceResponse:i}){console.log(W(B.green(`Successfully generated ${e.length} new tasks${t?` with research-backed analysis`:``}. Total tasks in ${r}: ${n.length}`),{padding:1,borderColor:`green`,borderStyle:`round`})),console.log(W(B.white.bold(`Next Steps:`)+`
955
955
 
956
956
  ${B.cyan(`1.`)} Run ${B.yellow(`task-master list`)} to view all tasks\n${B.cyan(`2.`)} Run ${B.yellow(`task-master expand --id=<id>`)} to break down a task into subtasks`,{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}})),i?.telemetryData&&Ml(i.telemetryData,`cli`)}async function ks(e,t){let n=new ts(e.mcpLog,e.reportProgress),{systemPrompt:r,userPrompt:a}=t,o=vs(r+a),s=null;e.outputFormat===`text`&&!e.isMCP&&(s=J(`Parsing PRD and generating tasks...
957
- `).start());try{n.report(`Calling AI service to generate tasks from PRD${e.research?` with research-backed analysis`:``}...`,`info`);let t=await i({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:$o,objectName:`tasks_data`,systemPrompt:r,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),c=null;if(t?.mainResult&&(typeof t.mainResult==`object`&&t.mainResult!==null&&`tasks`in t.mainResult?c=t.mainResult:typeof t.mainResult.object==`object`&&t.mainResult.object!==null&&`tasks`in t.mainResult.object&&(c=t.mainResult.object)),!c||!Array.isArray(c.tasks))throw Error(`AI service returned unexpected data structure after validation.`);return s&&s.succeed(`Tasks generated successfully!`),{parsedTasks:c.tasks,aiServiceResponse:t,estimatedInputTokens:o}}catch(e){throw s&&s.fail(`Error parsing PRD: ${e.message}`),e}}const[As,js,Ms]=ca,Ns=new Map;var Ps=class{constructor(e,t,n,r=null){this.name=e,this.levels=t,this.colors=n,this.thresholds=r}getColor(e){return this.colors[e]||B.gray}getLevelFromScore(e){if(!this.thresholds)throw Error(`${this.name} does not support score-based levels`);return e>=7?this.levels[0]:e<=3?this.levels[2]:this.levels[1]}};const Fs={cli:{filled:`●`,empty:`○`},statusBar:{high:`⋮`,medium:`:`,low:`.`},mcp:{high:`🔴`,medium:`🟠`,low:`🟢`}},Is=new Ps(`priority`,[As,js,Ms],{[As]:B.hex(`#CC0000`),[js]:B.hex(`#FF8800`),[Ms]:B.yellow});function Ls(e,t){let n=Fs.cli.filled,r=Fs.cli.empty,i=``;for(let a=0;a<3;a++)a<e?i+=t(n):i+=B.white(r);return i}function Rs(e,t){return 3-t.indexOf(e)}function zs(e,t){if(Ns.has(e))return Ns.get(e);let n=t();return Ns.set(e,n),n}function Bs(){return zs(`mcp-priority-all`,()=>({[As]:Fs.mcp.high,[js]:Fs.mcp.medium,[Ms]:Fs.mcp.low}))}function Vs(){return zs(`cli-priority-all`,()=>{let e={};return Is.levels.forEach(t=>{e[t]=Ls(Rs(t,Is.levels),Is.getColor(t))}),e})}function Hs(){return zs(`statusbar-priority-all`,()=>{let e={};return Is.levels.forEach((t,n)=>{let r=n===0?Fs.statusBar.high:n===1?Fs.statusBar.medium:Fs.statusBar.low;e[t]=Is.getColor(t)(r)}),e})}function Us(){return{[As]:Is.colors[As],[js]:Is.colors[js],[Ms]:Is.colors[Ms]}}function Ws(e=!1){return e?Bs():Vs()}function Gs(e,t=!1){let n=Ws(t);return n[e]||n[js]}new Ps(`complexity`,[`high`,`medium`,`low`],{high:B.hex(`#CC0000`),medium:B.hex(`#FF8800`),low:B.green},{high:e=>e>=7,medium:e=>e>=4&&e<=6,low:e=>e<=3});const Ks={clearOnComplete:!1,stopOnComplete:!0,hideCursor:!0,barsize:40},qs={shades_classic:mt.Presets.shades_classic,shades_grey:mt.Presets.shades_grey,rect:mt.Presets.rect,legacy:mt.Presets.legacy},Js=new class{constructor(e={},t=qs.shades_classic){this.defaultOptions={...Ks,...e},this.defaultPreset=t}createSingleBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new mt.SingleBar(n,r)}createMultiBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new mt.MultiBar(n,r)}_mergeConfig(e){return{...this.defaultOptions,...e}}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}setDefaultPreset(e){this.defaultPreset=e}};function Ys(e={}){return Js.createMultiBar(e)}var Xs=class{constructor(e={}){this.numUnits=e.numUnits||1,this.unitName=e.unitName||`unit`,this.startTime=null,this.completedUnits=0,this.tokensIn=0,this.tokensOut=0,this.isEstimate=!0,this.bestAvgTimePerUnit=null,this.lastEstimateTime=null,this.lastEstimateSeconds=0,this.multibar=null,this.timeTokensBar=null,this.progressBar=null,this._timerInterval=null,this.isStarted=!1,this.isFinished=!1,this._initializeCustomProperties(e)}_initializeCustomProperties(e){}get unitNamePlural(){return`${this.unitName}s`}start(){this.isStarted||this.isFinished||(this.isStarted=!0,this.startTime=Date.now(),this.multibar=Ys(),this.timeTokensBar=this.multibar.create(1,0,{},{format:this._getTimeTokensBarFormat(),barsize:1,hideCursor:!0,clearOnComplete:!1}),this.progressBar=this.multibar.create(this.numUnits,0,{},{format:this._getProgressBarFormat(),barCompleteChar:`█`,barIncompleteChar:`░`}),this._updateTimeTokensBar(),this.progressBar.update(0,{[this.unitNamePlural]:`0/${this.numUnits}`}),this._timerInterval=setInterval(()=>this._updateTimeTokensBar(),1e3),this._setupCustomUI())}_setupCustomUI(){}_getTimeTokensBarFormat(){return`{clock} {elapsed} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`${this.unitName.charAt(0).toUpperCase()+this.unitName.slice(1)}s {${this.unitNamePlural}} |{bar}| {percentage}%`}updateTokens(e,t,n=!1){this.tokensIn=e||0,this.tokensOut=t||0,this.isEstimate=n,this._updateTimeTokensBar()}_updateTimeTokensBar(){if(!this.timeTokensBar||this.isFinished)return;let e=this._formatElapsedTime(),t=this._estimateRemainingTime(),n=this.isEstimate?`~ Tokens (I/O)`:`Tokens (I/O)`;this.timeTokensBar.update(1,{clock:`⏱️`,elapsed:e,in:this.tokensIn,out:this.tokensOut,remaining:t,tokensLabel:n,...this._getCustomTimeTokensPayload()})}_getCustomTimeTokensPayload(){return{}}_formatElapsedTime(){if(!this.startTime)return`0m 00s`;let e=Math.floor((Date.now()-this.startTime)/1e3);return`${Math.floor(e/60)}m ${(e%60).toString().padStart(2,`0`)}s`}_estimateRemainingTime(){let e=this._getProgressFraction();if(e>=1)return`~0s`;let t=Date.now(),n=(t-this.startTime)/1e3;if(e===0)return`~calculating...`;let r=n/e;(this.bestAvgTimePerUnit===null||r<this.bestAvgTimePerUnit)&&(this.bestAvgTimePerUnit=r);let i=this.numUnits*(1-e),a=Math.ceil(i*this.bestAvgTimePerUnit);if(this.lastEstimateTime){let e=Math.floor((t-this.lastEstimateTime)/1e3),n=Math.max(0,this.lastEstimateSeconds-e);if(n===0)return`~0s`;a=Math.min(a,n)}return this.lastEstimateTime=t,this.lastEstimateSeconds=a,`~${this._formatDuration(a)}`}_getProgressFraction(){return this.completedUnits/this.numUnits}_formatDuration(e){if(e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;return t<60?n>0?`${t}m ${n}s`:`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}getElapsedTime(){return this.startTime?Date.now()-this.startTime:0}stop(){this.isFinished||(this.isFinished=!0,this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar&&(this._updateTimeTokensBar(),this.multibar.stop()),this.cleanup())}getSummary(){return{completedUnits:this.completedUnits,elapsedTime:this.getElapsedTime()}}cleanup(){if(this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar){try{this.multibar.stop()}catch{}this.multibar=null}this.timeTokensBar=null,this.progressBar=null,this.isStarted=!1,this.isFinished=!0,this._performCustomCleanup()}_performCustomCleanup(){}},Zs=class{constructor(e){if(!e)throw Error(`Multibar instance is required`);this.multibar=e}createBar(e,t={}){if(typeof e!=`string`)throw Error(`Format must be a string`);let n=this.multibar.create(1,1,{},{format:e,barsize:1,hideCursor:!0,clearOnComplete:!1});return n.update(1,t),n}createHeader(e,t){this.createBar(t),this.createBar(e),this.createBar(t)}createRow(e,t){if(!t||typeof t!=`object`)throw Error(`Payload must be an object`);return this.createBar(e,t)}createBorder(e){return this.createBar(e)}};function Qs(e,t,n){new Zs(e).createHeader(t,n)}function $s(e,t,n){new Zs(e).createRow(t,n)}function ec(e,t){new Zs(e).createBorder(t)}Vs();const tc=Hs();Us();const nc={DEBOUNCE_DELAY:100,MAX_TITLE_LENGTH:57,TRUNCATED_LENGTH:54,TASK_ID_PAD_START:3,TASK_ID_PAD_END:4,PRIORITY_PAD_END:3,VALID_PRIORITIES:[`high`,`medium`,`low`],DEFAULT_PRIORITY:`medium`};var rc=class{constructor(e=nc.DEBOUNCE_DELAY){this.delay=e,this.pendingTimeout=null}debounce(e){this.clear(),this.pendingTimeout=setTimeout(()=>{e(),this.pendingTimeout=null},this.delay)}clear(){this.pendingTimeout&&=(clearTimeout(this.pendingTimeout),null)}hasPending(){return this.pendingTimeout!==null}},ic=class{constructor(){this.priorities={high:0,medium:0,low:0}}increment(e){let t=this.normalize(e);return this.priorities[t]++,t}normalize(e){let t=e?e.toLowerCase():nc.DEFAULT_PRIORITY;return nc.VALID_PRIORITIES.includes(t)?t:nc.DEFAULT_PRIORITY}getCounts(){return{...this.priorities}}},ac=class{static formatTitle(e,t){return e?e.length>nc.MAX_TITLE_LENGTH?e.substring(0,nc.TRUNCATED_LENGTH)+`...`:e:`Task ${t}`}static formatPriority(e){return Gs(e,!1).padEnd(nc.PRIORITY_PAD_END,` `)}static formatTaskId(e){return e.toString().padStart(nc.TASK_ID_PAD_START,` `).padEnd(nc.TASK_ID_PAD_END,` `)}},oc=class extends Xs{_initializeCustomProperties(e){this.append=e.append,this.priorityManager=new ic,this.debouncer=new rc,this.headerShown=!1}_getTimeTokensBarFormat(){return`{clock} {elapsed} | ${tc.high} {high} ${tc.medium} {medium} ${tc.low} {low} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`Tasks {tasks} |{bar}| {percentage}%`}_getCustomTimeTokensPayload(){return this.priorityManager.getCounts()}addTaskLine(e,t,n=`medium`){if(!this.multibar||this.isFinished)return;this._ensureHeaderShown();let r=this._updateTaskCounters(e,n);this._updateTimeTokensBar(),this.debouncer.debounce(()=>{this._updateProgressDisplay(e,t,r)})}_ensureHeaderShown(){this.headerShown||(this.headerShown=!0,Qs(this.multibar,` TASK | PRI | TITLE`,`------+-----+----------------------------------------------------------------`))}_updateTaskCounters(e,t){let n=this.priorityManager.increment(t);return this.completedUnits=e,n}_updateProgressDisplay(e,t,n){this.progressBar.update(this.completedUnits,{tasks:`${this.completedUnits}/${this.numUnits}`});let r=ac.formatTitle(t,e),i=ac.formatPriority(n),a=ac.formatTaskId(e);$s(this.multibar,` ${a} | ${i} | {title}`,{title:r}),ec(this.multibar,`------+-----+----------------------------------------------------------------`),this._updateTimeTokensBar()}finish(){this.debouncer.hasPending()&&(this.debouncer.clear(),this._updateTimeTokensBar()),this.cleanup(),super.finish()}_performCustomCleanup(){this.debouncer.clear()}getSummary(){return{...super.getSummary(),taskPriorities:this.priorityManager.getCounts(),actionVerb:this.append?`appended`:`generated`}}};function sc(e={}){return new oc(e)}async function cc(e,t,n){let r=lc(e,t,n);await dc(e,n,r.estimatedInputTokens);let i=await fc(e,t,e.streamingTimeout),{progressTracker:a,priorityMap:o}=await pc(e,n),s=await mc(i.mainResult,e,t,n,a,o,r.defaultPriority,r.estimatedInputTokens,r.logger);if(uc(s),s.usage&&e.projectRoot){let{logAiUsage:t}=await import(`./ai-services-unified-BrOxyGnK.js`),{getUserId:n}=await import(`./config-manager-DyVbAaPA.js`),a=n(e.projectRoot);if(a&&i.providerName&&i.modelId)try{let n=await t({userId:a,commandName:`parse-prd`,providerName:i.providerName,modelId:i.modelId,inputTokens:s.usage.promptTokens||0,outputTokens:s.usage.completionTokens||0,outputType:e.isMCP?`mcp`:`cli`});n&&(i.telemetryData=n)}catch(e){r.logger.report(`Failed to log telemetry: ${e.message}`,`debug`)}}return wc(s,i,r.estimatedInputTokens,a)}function lc(e,t,n){let{systemPrompt:r,userPrompt:i}=t;return{logger:new ts(e.mcpLog,e.reportProgress),estimatedInputTokens:vs(r+i),defaultPriority:ce(e.projectRoot)||`medium`}}function uc(e){if(e.parsedTasks.length===0)throw Error(`No tasks were generated from the PRD`)}async function dc(e,t,n){e.reportProgress&&await e.reportProgress({progress:0,total:t,message:`Starting PRD analysis (Input: ${n} tokens)${e.research?` with research`:``}...`})}async function fc(e,n,r){let{systemPrompt:i,userPrompt:a}=n;return await Xo.withTimeout(t({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:$o,systemPrompt:i,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),r,`Streaming operation`)}async function pc(e,t){let n=Ws(e.isMCP),r=null;if(e.outputFormat===`text`&&!e.isMCP){r=sc({numUnits:t,unitName:`task`,append:e.append});let n=e.research?he():l(),i=v(e.research?`research`:`main`);us({prdFilePath:e.prdPath,outputPath:e.tasksPath,numTasks:t,append:e.append,research:e.research,force:e.force,existingTasks:[],nextId:1,model:n||`Default`,temperature:i?.temperature||.7}),r.start()}return{progressTracker:r,priorityMap:n}}async function mc(e,t,n,r,i,a,o,s,c){let{systemPrompt:l,userPrompt:u}=n,d={config:{...t,schema:$o},numTasks:r,progressTracker:i,priorityMap:a,defaultPriority:o,estimatedInputTokens:s,prompt:u,systemPrompt:l};try{let t={lastPartialObject:null,taskCount:0,estimatedOutputTokens:0,usage:null};if(await hc(e.partialObjectStream,t,d),e.usage)try{t.usage=await e.usage}catch(e){c.report(`Failed to get usage data: ${e.message}`,`debug`)}return yc(t,d)}catch(e){return c.report(`StreamObject processing failed: ${e.message}. Falling back to generateObject.`,`debug`),await Cc(d,c)}}async function hc(e,t,n){for await(let r of e)t.lastPartialObject=r,r&&(t.estimatedOutputTokens=vs(JSON.stringify(r))),await gc(r,t,n)}async function gc(e,t,n){if(!e?.tasks||!Array.isArray(e.tasks))return;let r=e.tasks.length;r>t.taskCount?(await _c(e.tasks,t.taskCount,r,t.estimatedOutputTokens,n),t.taskCount=r):n.progressTracker&&t.estimatedOutputTokens>0&&n.progressTracker.updateTokens(n.estimatedInputTokens,t.estimatedOutputTokens,!0)}async function _c(e,t,n,r,i){for(let a=t;a<n;a++){let t=e[a]||{};t.title?await Es({task:t,currentCount:a+1,totalTasks:i.numTasks,estimatedTokens:r,progressTracker:i.progressTracker,reportProgress:i.config.reportProgress,priorityMap:i.priorityMap,defaultPriority:i.defaultPriority,estimatedInputTokens:i.estimatedInputTokens}):await vc(a+1,r,i)}}async function vc(e,t,n){let{progressTracker:r,config:i,numTasks:a,defaultPriority:o,estimatedInputTokens:s}=n;r&&(r.addTaskLine(e,`Generating task ${e}...`,o),r.updateTokens(s,t,!0)),i.reportProgress&&!r&&await i.reportProgress({progress:e,total:a,message:`Generating task ${e}/${a}...`})}async function yc(e,t){let{lastPartialObject:n,estimatedOutputTokens:r,taskCount:i,usage:a}=e;if(!n?.tasks||!Array.isArray(n.tasks))throw Error(`No tasks generated from streamObject`);let o=a?.completionTokens||r,s=a?.promptTokens||t.estimatedInputTokens;return t.progressTracker&&await bc(n.tasks,i,a?o:r,t,a?s:null),{parsedTasks:n.tasks,estimatedOutputTokens:o,actualInputTokens:s,usage:a,usedFallback:!1}}async function bc(e,t,n,r,i=null){let{progressTracker:a,defaultPriority:o,estimatedInputTokens:s}=r;t>0?xc(e,a,o):await Sc(e,n,r),a.updateTokens(i||s,n,!1),a.stop()}function xc(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&t.addTaskLine(r+1,i.title,i.priority||n)}}async function Sc(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&await Es({task:i,currentCount:r+1,totalTasks:n.numTasks,estimatedTokens:t,progressTracker:n.progressTracker,reportProgress:n.config.reportProgress,priorityMap:n.priorityMap,defaultPriority:n.defaultPriority,estimatedInputTokens:n.estimatedInputTokens})}}async function Cc(e,t){if(t.report(`Using generateObject fallback for PRD parsing`,`info`),e.progressTracker)for(let t=0;t<e.numTasks;t++)e.progressTracker.addTaskLine(t+1,`Generating task ${t+1}...`,e.defaultPriority),e.progressTracker.updateTokens(e.estimatedInputTokens,0,!0);let n=await i({role:e.config.research?`research`:`main`,commandName:`parse-prd`,prompt:e.prompt,systemPrompt:e.systemPrompt,schema:e.config.schema,outputFormat:e.config.outputFormat||`text`,projectRoot:e.config.projectRoot,session:e.config.session}),r=n?.mainResult||n;if(r&&Array.isArray(r.tasks)&&(r.tasks=r.tasks.map(e=>({...e,dependencies:e.dependencies??[],priority:e.priority??null,details:e.details??null,testStrategy:e.testStrategy??null}))),r&&Array.isArray(r.tasks)){if(e.progressTracker){for(let t=0;t<r.tasks.length;t++){let n=r.tasks[t];n&&n.title&&e.progressTracker.addTaskLine(t+1,n.title,n.priority||e.defaultPriority)}let t=n.telemetryData?.outputTokens||vs(JSON.stringify(r)),i=n.telemetryData?.inputTokens||e.estimatedInputTokens;e.progressTracker.updateTokens(i,t,!1)}return{parsedTasks:r.tasks,estimatedOutputTokens:n.telemetryData?.outputTokens||vs(JSON.stringify(r)),actualInputTokens:n.telemetryData?.inputTokens,telemetryData:n.telemetryData,usedFallback:!0}}throw Error(`Failed to generate tasks using generateObject fallback`)}function wc(e,t,n,r){let i=null;if(r&&(i=r.getSummary(),r.cleanup()),e.usage&&t){let n=e.usage;t.usage||={promptTokens:n.promptTokens||0,completionTokens:n.completionTokens||0,totalTokens:n.totalTokens||0}}return{parsedTasks:e.parsedTasks,aiServiceResponse:t,estimatedInputTokens:e.actualInputTokens||n,estimatedOutputTokens:e.estimatedOutputTokens,usedFallback:e.usedFallback,progressTracker:r,summary:i}}async function Tc(e,t,n){let r=new ts(e.mcpLog,e.reportProgress);r.report(`Parsing PRD file: ${e.prdPath}, Force: ${e.force}, Append: ${e.append}, Research: ${e.research}`,`debug`);try{let{existingTasks:i,nextId:a}=bs(e.tasksPath,e.targetTag);xs({existingTasks:i,targetTag:e.targetTag,append:e.append,force:e.force,isMCP:e.isMCP,logger:r});let o=await t(e,await Ts(e,ys(e.prdPath),a),e.numTasks),s=ce(e.projectRoot)||`medium`,c=Ss(o.parsedTasks,a,i,s),l=e.append?[...i,...c]:c;return ws(e.tasksPath,l,e.targetTag,r),await Ec(e,o,c,l,a,n),{success:!0,tasksPath:e.tasksPath,telemetryData:o.aiServiceResponse?.telemetryData,tagInfo:o.aiServiceResponse?.tagInfo}}catch(t){throw r.report(`Error parsing PRD: ${t.message}`,`error`),e.isMCP||(console.error(B.red(`Error: ${t.message}`)),be(e.projectRoot)&&console.error(t)),t}}async function Ec(e,t,n,r,i,a){let{aiServiceResponse:o,estimatedInputTokens:s,estimatedOutputTokens:c}=t;if(e.reportProgress){let t=o?.telemetryData&&(o.telemetryData.inputTokens>0||o.telemetryData.outputTokens>0),n;if(t){let e=o.telemetryData.totalCost||0,t=o.telemetryData.currency||`USD`;n=`✅ Task Generation Completed | Tokens (I/O): ${o.telemetryData.inputTokens}/${o.telemetryData.outputTokens} | Cost: ${t===`USD`?`$`:t}${e.toFixed(4)}`}else n=`✅ Task Generation Completed | ~Tokens (I/O): ${s}/${a?c:`unknown`} | Cost: ~$0.00`;await e.reportProgress({progress:e.numTasks,total:e.numTasks,message:n})}e.outputFormat===`text`&&!e.isMCP&&(a&&t.summary?await Ds({processedTasks:n,nextId:i,summary:t.summary,prdPath:e.prdPath,tasksPath:e.tasksPath,usedFallback:t.usedFallback,aiServiceResponse:o}):a||Os({processedTasks:n,research:e.research,finalTasks:r,tasksPath:e.tasksPath,aiServiceResponse:o}))}async function Dc(e,t,n,r={}){return Tc(new es(e,t,n,r),cc,!0)}async function Oc(e,t,n,r={}){return Tc(new es(e,t,n,r),ks,!1)}async function kc(e,t,n,r={}){let i=new es(e,t,n,r);if(i.useStreaming)try{return await Dc(e,t,n,r)}catch(a){if(a instanceof Jo||a.code===Yo.NOT_ASYNC_ITERABLE||a.code===Yo.STREAM_PROCESSING_FAILED||a.code===Yo.STREAM_NOT_ITERABLE||Xo.isTimeoutError(a)){let o=new ts(i.mcpLog,i.reportProgress);return i.outputFormat===`text`&&!i.isMCP?console.log(B.yellow(`⚠️ Streaming operation ${a.message.includes(`timed out`)?`timed out`:`failed`}. Falling back to non-streaming mode...`)):o.report(`Streaming failed (${a.message}), falling back to non-streaming mode...`,`warn`),await Oc(e,t,n,r)}else throw a}else return await Oc(e,t,n,r)}var Ac=kc;async function jc(e,t,n=!1,r=!1,i={}){let{projectRoot:a,tag:o}=i;try{z(`info`,`Removing subtask ${t}...`);let r=w(e,a,o);if(!r||!r.tasks)throw Error(`Invalid or missing tasks file at ${e}`);if(!t.includes(`.`))throw Error(`Invalid subtask ID format: ${t}. Expected format: "parentId.subtaskId"`);let[i,s]=t.split(`.`),c=parseInt(i,10),l=parseInt(s,10),u=r.tasks.find(e=>e.id===c);if(!u)throw Error(`Parent task with ID ${c} not found`);if(!u.subtasks||u.subtasks.length===0)throw Error(`Parent task ${c} has no subtasks`);let d=u.subtasks.findIndex(e=>e.id===l);if(d===-1)throw Error(`Subtask ${t} not found`);let f={...u.subtasks[d]};u.subtasks.splice(d,1),u.subtasks.length===0&&(u.subtasks=void 0);let p=null;if(n){z(`info`,`Converting subtask ${t} to a standalone task...`);let e=Math.max(...r.tasks.map(e=>e.id))+1;p={id:e,title:f.title,description:f.description||``,details:f.details||``,status:f.status||`pending`,dependencies:f.dependencies||[],priority:u.priority||`medium`},p.dependencies.includes(c)||p.dependencies.push(c),r.tasks.push(p),z(`info`,`Created new task ${e} from subtask ${t}`)}else z(`info`,`Subtask ${t} deleted`);return _(e,r,a,o),p}catch(e){throw z(`error`,`Error removing subtask: ${e.message}`),e}}var Mc=jc;function Nc(e,t){if(typeof t==`string`&&t.includes(`.`)){let n=t.split(`.`);if(n.length!==2||!n[0]||!n[1]){let n=parseInt(t,10);return e.some(e=>e.id===n)}let[r,i]=n,a=parseInt(r,10),o=parseInt(i,10),s=e.find(e=>e.id===a);return s&&s.subtasks&&s.subtasks.some(e=>e.id===o)}let n=parseInt(t,10);return e.some(e=>e.id===n)}var Pc=Nc;async function Fc(e,t,n={}){let{projectRoot:r,tag:i}=n,a={success:!0,messages:[],errors:[],removedTasks:[]},o=t.split(`,`).map(e=>e.trim()).filter(Boolean);if(o.length===0)return a.success=!1,a.errors.push(`No valid task IDs provided.`),a;try{let t=w(e,r,i);if(!t)throw Error(`Could not read tasks file at ${e}`);let n=t._rawTaggedData||t;if(!n[i]||!n[i].tasks)throw Error(`Tag '${i}' not found or has no tasks.`);let s=n[i].tasks,c=[];for(let e of o){if(!Pc(s,e)){let t=`Task with ID ${e} in tag '${i}' not found or already removed.`;a.errors.push(t),a.success=!1;continue}try{if(typeof e==`string`&&e.includes(`.`)){let[t,n]=e.split(`.`).map(e=>parseInt(e,10)),r=s.find(e=>e.id===t);if(!r||!r.subtasks)throw Error(`Parent task ${t} or its subtasks not found for subtask ${e}`);let o=r.subtasks.findIndex(e=>e.id===n);if(o===-1)throw Error(`Subtask ${n} not found in parent task ${t}`);let c={...r.subtasks[o],parentTaskId:t};a.removedTasks.push(c),r.subtasks.splice(o,1),a.messages.push(`Successfully removed subtask ${e} from tag '${i}'`)}else{let t=parseInt(e,10),n=s.findIndex(e=>e.id===t);if(n===-1)throw Error(`Task with ID ${e} not found in tag '${i}'`);let r=s[n];a.removedTasks.push(r),c.push(t),s.splice(n,1),a.messages.push(`Successfully removed task ${e} from tag '${i}'`)}}catch(t){let n=`Error processing ID ${e}: ${t.message}`;a.errors.push(n),a.success=!1,z(`warn`,n)}}if(a.removedTasks.length>0){let t=new Set(o.map(e=>typeof e==`string`&&e.includes(`.`)?e:parseInt(e,10)));for(let e in n[i].tasks=s,n)Object.prototype.hasOwnProperty.call(n,e)&&n[e]&&n[e].tasks&&n[e].tasks.forEach(e=>{e.dependencies&&=e.dependencies.filter(e=>!t.has(e)),e.subtasks&&e.subtasks.forEach(n=>{n.dependencies&&=n.dependencies.filter(n=>!t.has(`${e.id}.${n}`)&&!t.has(n))})});_(e,n,r,i);for(let t of c){let n=H.join(H.dirname(e),`task_${t.toString().padStart(3,`0`)}.txt`);if(Ke.existsSync(n))try{Ke.unlinkSync(n),a.messages.push(`Deleted task file: ${n}`)}catch(e){let t=`Failed to delete task file ${n}: ${e.message}`;a.errors.push(t),a.success=!1,z(`warn`,t)}}}else a.errors.length===0&&a.messages.push(`No tasks found matching the provided IDs.`);let l=a.messages.join(`
957
+ `).start());try{n.report(`Calling AI service to generate tasks from PRD${e.research?` with research-backed analysis`:``}...`,`info`);let t=await i({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:$o,objectName:`tasks_data`,systemPrompt:r,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),c=null;if(t?.mainResult&&(typeof t.mainResult==`object`&&t.mainResult!==null&&`tasks`in t.mainResult?c=t.mainResult:typeof t.mainResult.object==`object`&&t.mainResult.object!==null&&`tasks`in t.mainResult.object&&(c=t.mainResult.object)),!c||!Array.isArray(c.tasks))throw Error(`AI service returned unexpected data structure after validation.`);return s&&s.succeed(`Tasks generated successfully!`),{parsedTasks:c.tasks,aiServiceResponse:t,estimatedInputTokens:o}}catch(e){throw s&&s.fail(`Error parsing PRD: ${e.message}`),e}}const[As,js,Ms]=ca,Ns=new Map;var Ps=class{constructor(e,t,n,r=null){this.name=e,this.levels=t,this.colors=n,this.thresholds=r}getColor(e){return this.colors[e]||B.gray}getLevelFromScore(e){if(!this.thresholds)throw Error(`${this.name} does not support score-based levels`);return e>=7?this.levels[0]:e<=3?this.levels[2]:this.levels[1]}};const Fs={cli:{filled:`●`,empty:`○`},statusBar:{high:`⋮`,medium:`:`,low:`.`},mcp:{high:`🔴`,medium:`🟠`,low:`🟢`}},Is=new Ps(`priority`,[As,js,Ms],{[As]:B.hex(`#CC0000`),[js]:B.hex(`#FF8800`),[Ms]:B.yellow});function Ls(e,t){let n=Fs.cli.filled,r=Fs.cli.empty,i=``;for(let a=0;a<3;a++)a<e?i+=t(n):i+=B.white(r);return i}function Rs(e,t){return 3-t.indexOf(e)}function zs(e,t){if(Ns.has(e))return Ns.get(e);let n=t();return Ns.set(e,n),n}function Bs(){return zs(`mcp-priority-all`,()=>({[As]:Fs.mcp.high,[js]:Fs.mcp.medium,[Ms]:Fs.mcp.low}))}function Vs(){return zs(`cli-priority-all`,()=>{let e={};return Is.levels.forEach(t=>{e[t]=Ls(Rs(t,Is.levels),Is.getColor(t))}),e})}function Hs(){return zs(`statusbar-priority-all`,()=>{let e={};return Is.levels.forEach((t,n)=>{let r=n===0?Fs.statusBar.high:n===1?Fs.statusBar.medium:Fs.statusBar.low;e[t]=Is.getColor(t)(r)}),e})}function Us(){return{[As]:Is.colors[As],[js]:Is.colors[js],[Ms]:Is.colors[Ms]}}function Ws(e=!1){return e?Bs():Vs()}function Gs(e,t=!1){let n=Ws(t);return n[e]||n[js]}new Ps(`complexity`,[`high`,`medium`,`low`],{high:B.hex(`#CC0000`),medium:B.hex(`#FF8800`),low:B.green},{high:e=>e>=7,medium:e=>e>=4&&e<=6,low:e=>e<=3});const Ks={clearOnComplete:!1,stopOnComplete:!0,hideCursor:!0,barsize:40},qs={shades_classic:mt.Presets.shades_classic,shades_grey:mt.Presets.shades_grey,rect:mt.Presets.rect,legacy:mt.Presets.legacy},Js=new class{constructor(e={},t=qs.shades_classic){this.defaultOptions={...Ks,...e},this.defaultPreset=t}createSingleBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new mt.SingleBar(n,r)}createMultiBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new mt.MultiBar(n,r)}_mergeConfig(e){return{...this.defaultOptions,...e}}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}setDefaultPreset(e){this.defaultPreset=e}};function Ys(e={}){return Js.createMultiBar(e)}var Xs=class{constructor(e={}){this.numUnits=e.numUnits||1,this.unitName=e.unitName||`unit`,this.startTime=null,this.completedUnits=0,this.tokensIn=0,this.tokensOut=0,this.isEstimate=!0,this.bestAvgTimePerUnit=null,this.lastEstimateTime=null,this.lastEstimateSeconds=0,this.multibar=null,this.timeTokensBar=null,this.progressBar=null,this._timerInterval=null,this.isStarted=!1,this.isFinished=!1,this._initializeCustomProperties(e)}_initializeCustomProperties(e){}get unitNamePlural(){return`${this.unitName}s`}start(){this.isStarted||this.isFinished||(this.isStarted=!0,this.startTime=Date.now(),this.multibar=Ys(),this.timeTokensBar=this.multibar.create(1,0,{},{format:this._getTimeTokensBarFormat(),barsize:1,hideCursor:!0,clearOnComplete:!1}),this.progressBar=this.multibar.create(this.numUnits,0,{},{format:this._getProgressBarFormat(),barCompleteChar:`█`,barIncompleteChar:`░`}),this._updateTimeTokensBar(),this.progressBar.update(0,{[this.unitNamePlural]:`0/${this.numUnits}`}),this._timerInterval=setInterval(()=>this._updateTimeTokensBar(),1e3),this._setupCustomUI())}_setupCustomUI(){}_getTimeTokensBarFormat(){return`{clock} {elapsed} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`${this.unitName.charAt(0).toUpperCase()+this.unitName.slice(1)}s {${this.unitNamePlural}} |{bar}| {percentage}%`}updateTokens(e,t,n=!1){this.tokensIn=e||0,this.tokensOut=t||0,this.isEstimate=n,this._updateTimeTokensBar()}_updateTimeTokensBar(){if(!this.timeTokensBar||this.isFinished)return;let e=this._formatElapsedTime(),t=this._estimateRemainingTime(),n=this.isEstimate?`~ Tokens (I/O)`:`Tokens (I/O)`;this.timeTokensBar.update(1,{clock:`⏱️`,elapsed:e,in:this.tokensIn,out:this.tokensOut,remaining:t,tokensLabel:n,...this._getCustomTimeTokensPayload()})}_getCustomTimeTokensPayload(){return{}}_formatElapsedTime(){if(!this.startTime)return`0m 00s`;let e=Math.floor((Date.now()-this.startTime)/1e3);return`${Math.floor(e/60)}m ${(e%60).toString().padStart(2,`0`)}s`}_estimateRemainingTime(){let e=this._getProgressFraction();if(e>=1)return`~0s`;let t=Date.now(),n=(t-this.startTime)/1e3;if(e===0)return`~calculating...`;let r=n/e;(this.bestAvgTimePerUnit===null||r<this.bestAvgTimePerUnit)&&(this.bestAvgTimePerUnit=r);let i=this.numUnits*(1-e),a=Math.ceil(i*this.bestAvgTimePerUnit);if(this.lastEstimateTime){let e=Math.floor((t-this.lastEstimateTime)/1e3),n=Math.max(0,this.lastEstimateSeconds-e);if(n===0)return`~0s`;a=Math.min(a,n)}return this.lastEstimateTime=t,this.lastEstimateSeconds=a,`~${this._formatDuration(a)}`}_getProgressFraction(){return this.completedUnits/this.numUnits}_formatDuration(e){if(e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;return t<60?n>0?`${t}m ${n}s`:`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}getElapsedTime(){return this.startTime?Date.now()-this.startTime:0}stop(){this.isFinished||(this.isFinished=!0,this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar&&(this._updateTimeTokensBar(),this.multibar.stop()),this.cleanup())}getSummary(){return{completedUnits:this.completedUnits,elapsedTime:this.getElapsedTime()}}cleanup(){if(this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar){try{this.multibar.stop()}catch{}this.multibar=null}this.timeTokensBar=null,this.progressBar=null,this.isStarted=!1,this.isFinished=!0,this._performCustomCleanup()}_performCustomCleanup(){}},Zs=class{constructor(e){if(!e)throw Error(`Multibar instance is required`);this.multibar=e}createBar(e,t={}){if(typeof e!=`string`)throw Error(`Format must be a string`);let n=this.multibar.create(1,1,{},{format:e,barsize:1,hideCursor:!0,clearOnComplete:!1});return n.update(1,t),n}createHeader(e,t){this.createBar(t),this.createBar(e),this.createBar(t)}createRow(e,t){if(!t||typeof t!=`object`)throw Error(`Payload must be an object`);return this.createBar(e,t)}createBorder(e){return this.createBar(e)}};function Qs(e,t,n){new Zs(e).createHeader(t,n)}function $s(e,t,n){new Zs(e).createRow(t,n)}function ec(e,t){new Zs(e).createBorder(t)}Vs();const tc=Hs();Us();const nc={DEBOUNCE_DELAY:100,MAX_TITLE_LENGTH:57,TRUNCATED_LENGTH:54,TASK_ID_PAD_START:3,TASK_ID_PAD_END:4,PRIORITY_PAD_END:3,VALID_PRIORITIES:[`high`,`medium`,`low`],DEFAULT_PRIORITY:`medium`};var rc=class{constructor(e=nc.DEBOUNCE_DELAY){this.delay=e,this.pendingTimeout=null}debounce(e){this.clear(),this.pendingTimeout=setTimeout(()=>{e(),this.pendingTimeout=null},this.delay)}clear(){this.pendingTimeout&&=(clearTimeout(this.pendingTimeout),null)}hasPending(){return this.pendingTimeout!==null}},ic=class{constructor(){this.priorities={high:0,medium:0,low:0}}increment(e){let t=this.normalize(e);return this.priorities[t]++,t}normalize(e){let t=e?e.toLowerCase():nc.DEFAULT_PRIORITY;return nc.VALID_PRIORITIES.includes(t)?t:nc.DEFAULT_PRIORITY}getCounts(){return{...this.priorities}}},ac=class{static formatTitle(e,t){return e?e.length>nc.MAX_TITLE_LENGTH?e.substring(0,nc.TRUNCATED_LENGTH)+`...`:e:`Task ${t}`}static formatPriority(e){return Gs(e,!1).padEnd(nc.PRIORITY_PAD_END,` `)}static formatTaskId(e){return e.toString().padStart(nc.TASK_ID_PAD_START,` `).padEnd(nc.TASK_ID_PAD_END,` `)}},oc=class extends Xs{_initializeCustomProperties(e){this.append=e.append,this.priorityManager=new ic,this.debouncer=new rc,this.headerShown=!1}_getTimeTokensBarFormat(){return`{clock} {elapsed} | ${tc.high} {high} ${tc.medium} {medium} ${tc.low} {low} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`Tasks {tasks} |{bar}| {percentage}%`}_getCustomTimeTokensPayload(){return this.priorityManager.getCounts()}addTaskLine(e,t,n=`medium`){if(!this.multibar||this.isFinished)return;this._ensureHeaderShown();let r=this._updateTaskCounters(e,n);this._updateTimeTokensBar(),this.debouncer.debounce(()=>{this._updateProgressDisplay(e,t,r)})}_ensureHeaderShown(){this.headerShown||(this.headerShown=!0,Qs(this.multibar,` TASK | PRI | TITLE`,`------+-----+----------------------------------------------------------------`))}_updateTaskCounters(e,t){let n=this.priorityManager.increment(t);return this.completedUnits=e,n}_updateProgressDisplay(e,t,n){this.progressBar.update(this.completedUnits,{tasks:`${this.completedUnits}/${this.numUnits}`});let r=ac.formatTitle(t,e),i=ac.formatPriority(n),a=ac.formatTaskId(e);$s(this.multibar,` ${a} | ${i} | {title}`,{title:r}),ec(this.multibar,`------+-----+----------------------------------------------------------------`),this._updateTimeTokensBar()}finish(){this.debouncer.hasPending()&&(this.debouncer.clear(),this._updateTimeTokensBar()),this.cleanup(),super.finish()}_performCustomCleanup(){this.debouncer.clear()}getSummary(){return{...super.getSummary(),taskPriorities:this.priorityManager.getCounts(),actionVerb:this.append?`appended`:`generated`}}};function sc(e={}){return new oc(e)}async function cc(e,t,n){let r=lc(e,t,n);await dc(e,n,r.estimatedInputTokens);let i=await fc(e,t,e.streamingTimeout),{progressTracker:a,priorityMap:o}=await pc(e,n),s=await mc(i.mainResult,e,t,n,a,o,r.defaultPriority,r.estimatedInputTokens,r.logger);if(uc(s),s.usage&&e.projectRoot){let{logAiUsage:t}=await import(`./ai-services-unified-DPaFvytz.js`),{getUserId:n}=await import(`./config-manager-YUjvDSOp.js`),a=n(e.projectRoot);if(a&&i.providerName&&i.modelId)try{let n=await t({userId:a,commandName:`parse-prd`,providerName:i.providerName,modelId:i.modelId,inputTokens:s.usage.promptTokens||0,outputTokens:s.usage.completionTokens||0,outputType:e.isMCP?`mcp`:`cli`});n&&(i.telemetryData=n)}catch(e){r.logger.report(`Failed to log telemetry: ${e.message}`,`debug`)}}return wc(s,i,r.estimatedInputTokens,a)}function lc(e,t,n){let{systemPrompt:r,userPrompt:i}=t;return{logger:new ts(e.mcpLog,e.reportProgress),estimatedInputTokens:vs(r+i),defaultPriority:ce(e.projectRoot)||`medium`}}function uc(e){if(e.parsedTasks.length===0)throw Error(`No tasks were generated from the PRD`)}async function dc(e,t,n){e.reportProgress&&await e.reportProgress({progress:0,total:t,message:`Starting PRD analysis (Input: ${n} tokens)${e.research?` with research`:``}...`})}async function fc(e,n,r){let{systemPrompt:i,userPrompt:a}=n;return await Xo.withTimeout(t({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:$o,systemPrompt:i,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),r,`Streaming operation`)}async function pc(e,t){let n=Ws(e.isMCP),r=null;if(e.outputFormat===`text`&&!e.isMCP){r=sc({numUnits:t,unitName:`task`,append:e.append});let n=e.research?he():l(),i=v(e.research?`research`:`main`);us({prdFilePath:e.prdPath,outputPath:e.tasksPath,numTasks:t,append:e.append,research:e.research,force:e.force,existingTasks:[],nextId:1,model:n||`Default`,temperature:i?.temperature||.7}),r.start()}return{progressTracker:r,priorityMap:n}}async function mc(e,t,n,r,i,a,o,s,c){let{systemPrompt:l,userPrompt:u}=n,d={config:{...t,schema:$o},numTasks:r,progressTracker:i,priorityMap:a,defaultPriority:o,estimatedInputTokens:s,prompt:u,systemPrompt:l};try{let t={lastPartialObject:null,taskCount:0,estimatedOutputTokens:0,usage:null};if(await hc(e.partialObjectStream,t,d),e.usage)try{t.usage=await e.usage}catch(e){c.report(`Failed to get usage data: ${e.message}`,`debug`)}return yc(t,d)}catch(e){return c.report(`StreamObject processing failed: ${e.message}. Falling back to generateObject.`,`debug`),await Cc(d,c)}}async function hc(e,t,n){for await(let r of e)t.lastPartialObject=r,r&&(t.estimatedOutputTokens=vs(JSON.stringify(r))),await gc(r,t,n)}async function gc(e,t,n){if(!e?.tasks||!Array.isArray(e.tasks))return;let r=e.tasks.length;r>t.taskCount?(await _c(e.tasks,t.taskCount,r,t.estimatedOutputTokens,n),t.taskCount=r):n.progressTracker&&t.estimatedOutputTokens>0&&n.progressTracker.updateTokens(n.estimatedInputTokens,t.estimatedOutputTokens,!0)}async function _c(e,t,n,r,i){for(let a=t;a<n;a++){let t=e[a]||{};t.title?await Es({task:t,currentCount:a+1,totalTasks:i.numTasks,estimatedTokens:r,progressTracker:i.progressTracker,reportProgress:i.config.reportProgress,priorityMap:i.priorityMap,defaultPriority:i.defaultPriority,estimatedInputTokens:i.estimatedInputTokens}):await vc(a+1,r,i)}}async function vc(e,t,n){let{progressTracker:r,config:i,numTasks:a,defaultPriority:o,estimatedInputTokens:s}=n;r&&(r.addTaskLine(e,`Generating task ${e}...`,o),r.updateTokens(s,t,!0)),i.reportProgress&&!r&&await i.reportProgress({progress:e,total:a,message:`Generating task ${e}/${a}...`})}async function yc(e,t){let{lastPartialObject:n,estimatedOutputTokens:r,taskCount:i,usage:a}=e;if(!n?.tasks||!Array.isArray(n.tasks))throw Error(`No tasks generated from streamObject`);let o=a?.completionTokens||r,s=a?.promptTokens||t.estimatedInputTokens;return t.progressTracker&&await bc(n.tasks,i,a?o:r,t,a?s:null),{parsedTasks:n.tasks,estimatedOutputTokens:o,actualInputTokens:s,usage:a,usedFallback:!1}}async function bc(e,t,n,r,i=null){let{progressTracker:a,defaultPriority:o,estimatedInputTokens:s}=r;t>0?xc(e,a,o):await Sc(e,n,r),a.updateTokens(i||s,n,!1),a.stop()}function xc(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&t.addTaskLine(r+1,i.title,i.priority||n)}}async function Sc(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&await Es({task:i,currentCount:r+1,totalTasks:n.numTasks,estimatedTokens:t,progressTracker:n.progressTracker,reportProgress:n.config.reportProgress,priorityMap:n.priorityMap,defaultPriority:n.defaultPriority,estimatedInputTokens:n.estimatedInputTokens})}}async function Cc(e,t){if(t.report(`Using generateObject fallback for PRD parsing`,`info`),e.progressTracker)for(let t=0;t<e.numTasks;t++)e.progressTracker.addTaskLine(t+1,`Generating task ${t+1}...`,e.defaultPriority),e.progressTracker.updateTokens(e.estimatedInputTokens,0,!0);let n=await i({role:e.config.research?`research`:`main`,commandName:`parse-prd`,prompt:e.prompt,systemPrompt:e.systemPrompt,schema:e.config.schema,outputFormat:e.config.outputFormat||`text`,projectRoot:e.config.projectRoot,session:e.config.session}),r=n?.mainResult||n;if(r&&Array.isArray(r.tasks)&&(r.tasks=r.tasks.map(e=>({...e,dependencies:e.dependencies??[],priority:e.priority??null,details:e.details??null,testStrategy:e.testStrategy??null}))),r&&Array.isArray(r.tasks)){if(e.progressTracker){for(let t=0;t<r.tasks.length;t++){let n=r.tasks[t];n&&n.title&&e.progressTracker.addTaskLine(t+1,n.title,n.priority||e.defaultPriority)}let t=n.telemetryData?.outputTokens||vs(JSON.stringify(r)),i=n.telemetryData?.inputTokens||e.estimatedInputTokens;e.progressTracker.updateTokens(i,t,!1)}return{parsedTasks:r.tasks,estimatedOutputTokens:n.telemetryData?.outputTokens||vs(JSON.stringify(r)),actualInputTokens:n.telemetryData?.inputTokens,telemetryData:n.telemetryData,usedFallback:!0}}throw Error(`Failed to generate tasks using generateObject fallback`)}function wc(e,t,n,r){let i=null;if(r&&(i=r.getSummary(),r.cleanup()),e.usage&&t){let n=e.usage;t.usage||={promptTokens:n.promptTokens||0,completionTokens:n.completionTokens||0,totalTokens:n.totalTokens||0}}return{parsedTasks:e.parsedTasks,aiServiceResponse:t,estimatedInputTokens:e.actualInputTokens||n,estimatedOutputTokens:e.estimatedOutputTokens,usedFallback:e.usedFallback,progressTracker:r,summary:i}}async function Tc(e,t,n){let r=new ts(e.mcpLog,e.reportProgress);r.report(`Parsing PRD file: ${e.prdPath}, Force: ${e.force}, Append: ${e.append}, Research: ${e.research}`,`debug`);try{let{existingTasks:i,nextId:a}=bs(e.tasksPath,e.targetTag);xs({existingTasks:i,targetTag:e.targetTag,append:e.append,force:e.force,isMCP:e.isMCP,logger:r});let o=await t(e,await Ts(e,ys(e.prdPath),a),e.numTasks),s=ce(e.projectRoot)||`medium`,c=Ss(o.parsedTasks,a,i,s),l=e.append?[...i,...c]:c;return ws(e.tasksPath,l,e.targetTag,r),await Ec(e,o,c,l,a,n),{success:!0,tasksPath:e.tasksPath,telemetryData:o.aiServiceResponse?.telemetryData,tagInfo:o.aiServiceResponse?.tagInfo}}catch(t){throw r.report(`Error parsing PRD: ${t.message}`,`error`),e.isMCP||(console.error(B.red(`Error: ${t.message}`)),be(e.projectRoot)&&console.error(t)),t}}async function Ec(e,t,n,r,i,a){let{aiServiceResponse:o,estimatedInputTokens:s,estimatedOutputTokens:c}=t;if(e.reportProgress){let t=o?.telemetryData&&(o.telemetryData.inputTokens>0||o.telemetryData.outputTokens>0),n;if(t){let e=o.telemetryData.totalCost||0,t=o.telemetryData.currency||`USD`;n=`✅ Task Generation Completed | Tokens (I/O): ${o.telemetryData.inputTokens}/${o.telemetryData.outputTokens} | Cost: ${t===`USD`?`$`:t}${e.toFixed(4)}`}else n=`✅ Task Generation Completed | ~Tokens (I/O): ${s}/${a?c:`unknown`} | Cost: ~$0.00`;await e.reportProgress({progress:e.numTasks,total:e.numTasks,message:n})}e.outputFormat===`text`&&!e.isMCP&&(a&&t.summary?await Ds({processedTasks:n,nextId:i,summary:t.summary,prdPath:e.prdPath,tasksPath:e.tasksPath,usedFallback:t.usedFallback,aiServiceResponse:o}):a||Os({processedTasks:n,research:e.research,finalTasks:r,tasksPath:e.tasksPath,aiServiceResponse:o}))}async function Dc(e,t,n,r={}){return Tc(new es(e,t,n,r),cc,!0)}async function Oc(e,t,n,r={}){return Tc(new es(e,t,n,r),ks,!1)}async function kc(e,t,n,r={}){let i=new es(e,t,n,r);if(i.useStreaming)try{return await Dc(e,t,n,r)}catch(a){if(a instanceof Jo||a.code===Yo.NOT_ASYNC_ITERABLE||a.code===Yo.STREAM_PROCESSING_FAILED||a.code===Yo.STREAM_NOT_ITERABLE||Xo.isTimeoutError(a)){let o=new ts(i.mcpLog,i.reportProgress);return i.outputFormat===`text`&&!i.isMCP?console.log(B.yellow(`⚠️ Streaming operation ${a.message.includes(`timed out`)?`timed out`:`failed`}. Falling back to non-streaming mode...`)):o.report(`Streaming failed (${a.message}), falling back to non-streaming mode...`,`warn`),await Oc(e,t,n,r)}else throw a}else return await Oc(e,t,n,r)}var Ac=kc;async function jc(e,t,n=!1,r=!1,i={}){let{projectRoot:a,tag:o}=i;try{z(`info`,`Removing subtask ${t}...`);let r=w(e,a,o);if(!r||!r.tasks)throw Error(`Invalid or missing tasks file at ${e}`);if(!t.includes(`.`))throw Error(`Invalid subtask ID format: ${t}. Expected format: "parentId.subtaskId"`);let[i,s]=t.split(`.`),c=parseInt(i,10),l=parseInt(s,10),u=r.tasks.find(e=>e.id===c);if(!u)throw Error(`Parent task with ID ${c} not found`);if(!u.subtasks||u.subtasks.length===0)throw Error(`Parent task ${c} has no subtasks`);let d=u.subtasks.findIndex(e=>e.id===l);if(d===-1)throw Error(`Subtask ${t} not found`);let f={...u.subtasks[d]};u.subtasks.splice(d,1),u.subtasks.length===0&&(u.subtasks=void 0);let p=null;if(n){z(`info`,`Converting subtask ${t} to a standalone task...`);let e=Math.max(...r.tasks.map(e=>e.id))+1;p={id:e,title:f.title,description:f.description||``,details:f.details||``,status:f.status||`pending`,dependencies:f.dependencies||[],priority:u.priority||`medium`},p.dependencies.includes(c)||p.dependencies.push(c),r.tasks.push(p),z(`info`,`Created new task ${e} from subtask ${t}`)}else z(`info`,`Subtask ${t} deleted`);return _(e,r,a,o),p}catch(e){throw z(`error`,`Error removing subtask: ${e.message}`),e}}var Mc=jc;function Nc(e,t){if(typeof t==`string`&&t.includes(`.`)){let n=t.split(`.`);if(n.length!==2||!n[0]||!n[1]){let n=parseInt(t,10);return e.some(e=>e.id===n)}let[r,i]=n,a=parseInt(r,10),o=parseInt(i,10),s=e.find(e=>e.id===a);return s&&s.subtasks&&s.subtasks.some(e=>e.id===o)}let n=parseInt(t,10);return e.some(e=>e.id===n)}var Pc=Nc;async function Fc(e,t,n={}){let{projectRoot:r,tag:i}=n,a={success:!0,messages:[],errors:[],removedTasks:[]},o=t.split(`,`).map(e=>e.trim()).filter(Boolean);if(o.length===0)return a.success=!1,a.errors.push(`No valid task IDs provided.`),a;try{let t=w(e,r,i);if(!t)throw Error(`Could not read tasks file at ${e}`);let n=t._rawTaggedData||t;if(!n[i]||!n[i].tasks)throw Error(`Tag '${i}' not found or has no tasks.`);let s=n[i].tasks,c=[];for(let e of o){if(!Pc(s,e)){let t=`Task with ID ${e} in tag '${i}' not found or already removed.`;a.errors.push(t),a.success=!1;continue}try{if(typeof e==`string`&&e.includes(`.`)){let[t,n]=e.split(`.`).map(e=>parseInt(e,10)),r=s.find(e=>e.id===t);if(!r||!r.subtasks)throw Error(`Parent task ${t} or its subtasks not found for subtask ${e}`);let o=r.subtasks.findIndex(e=>e.id===n);if(o===-1)throw Error(`Subtask ${n} not found in parent task ${t}`);let c={...r.subtasks[o],parentTaskId:t};a.removedTasks.push(c),r.subtasks.splice(o,1),a.messages.push(`Successfully removed subtask ${e} from tag '${i}'`)}else{let t=parseInt(e,10),n=s.findIndex(e=>e.id===t);if(n===-1)throw Error(`Task with ID ${e} not found in tag '${i}'`);let r=s[n];a.removedTasks.push(r),c.push(t),s.splice(n,1),a.messages.push(`Successfully removed task ${e} from tag '${i}'`)}}catch(t){let n=`Error processing ID ${e}: ${t.message}`;a.errors.push(n),a.success=!1,z(`warn`,n)}}if(a.removedTasks.length>0){let t=new Set(o.map(e=>typeof e==`string`&&e.includes(`.`)?e:parseInt(e,10)));for(let e in n[i].tasks=s,n)Object.prototype.hasOwnProperty.call(n,e)&&n[e]&&n[e].tasks&&n[e].tasks.forEach(e=>{e.dependencies&&=e.dependencies.filter(e=>!t.has(e)),e.subtasks&&e.subtasks.forEach(n=>{n.dependencies&&=n.dependencies.filter(n=>!t.has(`${e.id}.${n}`)&&!t.has(n))})});_(e,n,r,i);for(let t of c){let n=H.join(H.dirname(e),`task_${t.toString().padStart(3,`0`)}.txt`);if(Ke.existsSync(n))try{Ke.unlinkSync(n),a.messages.push(`Deleted task file: ${n}`)}catch(e){let t=`Failed to delete task file ${n}: ${e.message}`;a.errors.push(t),a.success=!1,z(`warn`,t)}}}else a.errors.length===0&&a.messages.push(`No tasks found matching the provided IDs.`);let l=a.messages.join(`
958
958
  `),u=a.errors.join(`
959
959
  `);return{success:a.success,message:l||`No tasks were removed.`,error:u||null,removedTasks:a.removedTasks}}catch(e){return z(`error`,`Error removing tasks: ${e.message}`),{success:!1,message:``,error:`Operation failed: ${e.message}`,removedTasks:[]}}}var Ic=Fc;ot.use(st({code:e=>e.split(`
960
960
  `).map(e=>` `+B.cyan(e)).join(`
@@ -972,9 +972,9 @@ ${B.cyan(`1.`)} Run ${B.yellow(`task-master list`)} to view all tasks\n${B.cyan(
972
972
  `);if(r.push(B.cyan(`Prompts: `)+B.yellow(i.toLocaleString())+B.gray(` (generated)`)+`
973
973
  `+a),r.length>0){let e=W(r.join(`
974
974
 
975
- `),{title:B.blue.bold(`Context Analysis`),titleAlignment:`left`,padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:1},borderStyle:`single`,borderColor:`blue`});console.log(e)}}async function zc(e,t,n,r,i,a,o){let s=!1;try{let{readJSON:c}=await import(`./utils-5vnyX__r.js`);(await import(`./update-task-by-id-DrnkDCmy.js`)).default;let{updateSubtaskById:l}=await import(`./update-subtask-by-id-bImgwSPt.js`),u=[{question:a,answer:o,type:`initial`,timestamp:new Date().toISOString()}];for(;;){let{action:a}=await q.prompt([{type:`list`,name:`action`,message:`What would you like to do next?`,choices:[{name:`Ask a follow-up question`,value:`followup`},{name:`Save to file`,value:`savefile`},{name:`Save to task/subtask`,value:`save`},{name:`Quit`,value:`quit`}],pageSize:4}]);if(a===`quit`)break;if(a===`savefile`){await Vc(u,r,t,i);continue}if(a===`save`){await Bc(u,r,t,i)&&(s=!0);continue}if(a===`followup`){let{followUpQuery:r}=await q.prompt([{type:`input`,name:`followUpQuery`,message:`Enter your follow-up question:`,validate:e=>!e||e.trim().length===0?`Please enter a valid question.`:!0}]);if(!r||r.trim().length===0)continue;console.log(`
975
+ `),{title:B.blue.bold(`Context Analysis`),titleAlignment:`left`,padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:1},borderStyle:`single`,borderColor:`blue`});console.log(e)}}async function zc(e,t,n,r,i,a,o){let s=!1;try{let{readJSON:c}=await import(`./utils-DcGaEZ8q.js`);(await import(`./update-task-by-id-D_-5VcYR.js`)).default;let{updateSubtaskById:l}=await import(`./update-subtask-by-id-CqSLuabu.js`),u=[{question:a,answer:o,type:`initial`,timestamp:new Date().toISOString()}];for(;;){let{action:a}=await q.prompt([{type:`list`,name:`action`,message:`What would you like to do next?`,choices:[{name:`Ask a follow-up question`,value:`followup`},{name:`Save to file`,value:`savefile`},{name:`Save to task/subtask`,value:`save`},{name:`Quit`,value:`quit`}],pageSize:4}]);if(a===`quit`)break;if(a===`savefile`){await Vc(u,r,t,i);continue}if(a===`save`){await Bc(u,r,t,i)&&(s=!0);continue}if(a===`followup`){let{followUpQuery:r}=await q.prompt([{type:`input`,name:`followUpQuery`,message:`Enter your follow-up question:`,validate:e=>!e||e.trim().length===0?`Please enter a valid question.`:!0}]);if(!r||r.trim().length===0)continue;console.log(`
976
976
  `+B.gray(`─`.repeat(60))+`
977
- `);let i=Wc(u),a={...e,taskIds:[],customContext:i+(e.customContext?`\n\n--- Original Context ---\n${e.customContext}`:``)},o=await Lc(r.trim(),a,t,n,!1);u.push({question:r.trim(),answer:o.result,type:`followup`,timestamp:new Date().toISOString()})}}}catch(e){i.debug(`Follow-up questions not available: ${e.message}`)}return{interactiveSaveOccurred:s}}async function Bc(e,t,n,r){try{let{readJSON:r}=await import(`./utils-5vnyX__r.js`),i=(await import(`./update-task-by-id-DrnkDCmy.js`)).default,{updateSubtaskById:a}=await import(`./update-subtask-by-id-bImgwSPt.js`),{taskId:o}=await q.prompt([{type:`input`,name:`taskId`,message:`Enter task ID (e.g., "15" for task or "15.2" for subtask):`,validate:e=>{if(!e||e.trim().length===0)return`Please enter a task ID.`;let t=e.trim();return/^\d+(\.\d+)?$/.test(t)?!0:`Invalid format. Use "15" for task or "15.2" for subtask.`}}]),s=o.trim(),c=Uc(e),l=s.includes(`.`),u=H.join(t,`.taskmaster`,`tasks`,`tasks.json`);if(!V.existsSync(u)){console.log(B.red(`❌ Tasks file not found. Please run task-master init first.`));return}let d=r(u,t,n.tag);if(!d||!d.tasks){console.log(B.red(`❌ No valid tasks found.`));return}if(l){let[e,t]=s.split(`.`).map(e=>parseInt(e,10)),r=d.tasks.find(t=>t.id===e);if(!r){console.log(B.red(`❌ Parent task ${e} not found.`));return}if(!r.subtasks||!r.subtasks.find(e=>e.id===t)){console.log(B.red(`❌ Subtask ${s} not found.`));return}console.log(B.blue(`💾 Saving research conversation to subtask...`)),await a(u,s,c,!1,n,`text`),console.log(B.green(`✅ Research conversation saved to subtask ${s}`))}else{let e=parseInt(s,10);if(!d.tasks.find(t=>t.id===e)){console.log(B.red(`❌ Task ${s} not found.`));return}console.log(B.blue(`💾 Saving research conversation to task...`)),await i(u,e,c,!1,n,`text`,!0),console.log(B.green(`✅ Research conversation saved to task ${s}`))}return!0}catch(e){return console.log(B.red(`❌ Error saving conversation: ${e.message}`)),r.error(`Error saving conversation: ${e.message}`),!1}}async function Vc(e,t,n,r){try{let n=H.join(t,`.taskmaster`,`docs`,`research`);V.existsSync(n)||V.mkdirSync(n,{recursive:!0});let i=e[0]?.question||`research-query`,a=`${new Date().toISOString().split(`T`)[0]}_${i.toLowerCase().replace(/[^a-z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).substring(0,50).replace(/^-+|-+$/g,``)}.md`,o=H.join(n,a),s=Hc(e,i);V.writeFileSync(o,s,`utf8`);let c=H.relative(t,o);return console.log(B.green(`✅ Research saved to: ${B.cyan(c)}`)),r.success(`Research conversation saved to ${c}`),o}catch(e){throw console.log(B.red(`❌ Error saving research file: ${e.message}`)),r.error(`Error saving research file: ${e.message}`),e}}function Hc(e,t){let n=new Date().toISOString(),r=`---
977
+ `);let i=Wc(u),a={...e,taskIds:[],customContext:i+(e.customContext?`\n\n--- Original Context ---\n${e.customContext}`:``)},o=await Lc(r.trim(),a,t,n,!1);u.push({question:r.trim(),answer:o.result,type:`followup`,timestamp:new Date().toISOString()})}}}catch(e){i.debug(`Follow-up questions not available: ${e.message}`)}return{interactiveSaveOccurred:s}}async function Bc(e,t,n,r){try{let{readJSON:r}=await import(`./utils-DcGaEZ8q.js`),i=(await import(`./update-task-by-id-D_-5VcYR.js`)).default,{updateSubtaskById:a}=await import(`./update-subtask-by-id-CqSLuabu.js`),{taskId:o}=await q.prompt([{type:`input`,name:`taskId`,message:`Enter task ID (e.g., "15" for task or "15.2" for subtask):`,validate:e=>{if(!e||e.trim().length===0)return`Please enter a task ID.`;let t=e.trim();return/^\d+(\.\d+)?$/.test(t)?!0:`Invalid format. Use "15" for task or "15.2" for subtask.`}}]),s=o.trim(),c=Uc(e),l=s.includes(`.`),u=H.join(t,`.taskmaster`,`tasks`,`tasks.json`);if(!V.existsSync(u)){console.log(B.red(`❌ Tasks file not found. Please run task-master init first.`));return}let d=r(u,t,n.tag);if(!d||!d.tasks){console.log(B.red(`❌ No valid tasks found.`));return}if(l){let[e,t]=s.split(`.`).map(e=>parseInt(e,10)),r=d.tasks.find(t=>t.id===e);if(!r){console.log(B.red(`❌ Parent task ${e} not found.`));return}if(!r.subtasks||!r.subtasks.find(e=>e.id===t)){console.log(B.red(`❌ Subtask ${s} not found.`));return}console.log(B.blue(`💾 Saving research conversation to subtask...`)),await a(u,s,c,!1,n,`text`),console.log(B.green(`✅ Research conversation saved to subtask ${s}`))}else{let e=parseInt(s,10);if(!d.tasks.find(t=>t.id===e)){console.log(B.red(`❌ Task ${s} not found.`));return}console.log(B.blue(`💾 Saving research conversation to task...`)),await i(u,e,c,!1,n,`text`,!0),console.log(B.green(`✅ Research conversation saved to task ${s}`))}return!0}catch(e){return console.log(B.red(`❌ Error saving conversation: ${e.message}`)),r.error(`Error saving conversation: ${e.message}`),!1}}async function Vc(e,t,n,r){try{let n=H.join(t,`.taskmaster`,`docs`,`research`);V.existsSync(n)||V.mkdirSync(n,{recursive:!0});let i=e[0]?.question||`research-query`,a=`${new Date().toISOString().split(`T`)[0]}_${i.toLowerCase().replace(/[^a-z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).substring(0,50).replace(/^-+|-+$/g,``)}.md`,o=H.join(n,a),s=Hc(e,i);V.writeFileSync(o,s,`utf8`);let c=H.relative(t,o);return console.log(B.green(`✅ Research saved to: ${B.cyan(c)}`)),r.success(`Research conversation saved to ${c}`),o}catch(e){throw console.log(B.red(`❌ Error saving research file: ${e.message}`)),r.error(`Error saving research file: ${e.message}`),e}}function Hc(e,t){let n=new Date().toISOString(),r=`---
978
978
  title: Research Session
979
979
  query: "${t}"
980
980
  date: ${new Date().toLocaleDateString()}