@hhsw2015/task-master-ai 0.43.33 → 0.43.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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-C_wzEmAq.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-DZYVJT7n.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.33`;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-D47kSPRC.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-BHkHj6Wx.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.34`;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+`
@@ -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-CAZbeUtd.js`),{getUserId:n}=await import(`./config-manager-2hd0dZGj.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-BEikuD9a.js`),{getUserId:n}=await import(`./config-manager-DeznBkH1.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-coVxmIu6.js`);(await import(`./update-task-by-id-aVi1O1ZL.js`)).default;let{updateSubtaskById:l}=await import(`./update-subtask-by-id-DKVRZTLI.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-Be5Mjf9W.js`);(await import(`./update-task-by-id-Ew-wfGRR.js`)).default;let{updateSubtaskById:l}=await import(`./update-subtask-by-id-BefMzxs3.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-coVxmIu6.js`),i=(await import(`./update-task-by-id-aVi1O1ZL.js`)).default,{updateSubtaskById:a}=await import(`./update-subtask-by-id-DKVRZTLI.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-Be5Mjf9W.js`),i=(await import(`./update-task-by-id-Ew-wfGRR.js`)).default,{updateSubtaskById:a}=await import(`./update-subtask-by-id-BefMzxs3.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()}
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{o as e,s as t}from"./ai-services-unified-C_wzEmAq.js";import{$t as n,Dt as r,Ht as i,Kt as a,Mt as o,Nt as s,On as c,Qt as l,S as u,Sn as d,Tt as f,fn as p,h as m,ht as h,in as g,ln as _,ot as v,pn as y,rn as b,st as x,tn as S,tt as C,vn as ee,vt as w,wt as te,zt as ne}from"./config-manager-DZYVJT7n.js";import"./git-utils-DllbRE35.js";import{r as re}from"./sentry-C9gSa7DA.js";import{$ as T,A as ie,B as E,C as ae,D as oe,Dt as se,Et as ce,F as le,G as ue,H as de,I as fe,J as pe,M as me,N as he,O as ge,P as _e,Q as ve,R as D,S as ye,U as be,V as xe,W as Se,X as Ce,Y as we,Z as Te,at as Ee,ct as De,dt as Oe,gt as ke,ht as Ae,i as je,it as Me,j as Ne,lt as Pe,n as Fe,pt as Ie,r as Le,rt as Re,st as ze,t as Be,ut as Ve,w as He,z as Ue}from"./dependency-manager-DvEjtS1v.js";import{t as We}from"./response-language-C-QKf5DA.js";import{a as Ge,c as Ke,f as qe,g as Je,h as Ye,l as O,m as k,p as Xe,v as A}from"./profiles-7X56Fodc.js";import j from"node:path";import M from"chalk";import N from"fs";import P from"path";import Ze from"os";import F from"node:fs";import{z as I}from"zod";import{fileURLToPath as Qe}from"url";import L from"dotenv";import*as R from"@sentry/node";import{FastMCP as $e}from"fastmcp";const z={debug:0,info:1,warn:2,error:3,success:4},et=z[u().toLowerCase()]??z.info;function B(e,...t){if(w())return;let n={debug:M.gray(`[DEBUG]`),info:M.blue(`[INFO]`),warn:M.yellow(`[WARN]`),error:M.red(`[ERROR]`),success:M.green(`[SUCCESS]`)};if(z[e]!==void 0&&z[e]>=et){let r=n[e]||``,i=t;try{switch(e){case`error`:i=t.map(e=>typeof e==`string`?M.red(e):e);break;case`warn`:i=t.map(e=>typeof e==`string`?M.yellow(e):e);break;case`success`:i=t.map(e=>typeof e==`string`?M.green(e):e);break;case`info`:i=t.map(e=>typeof e==`string`?M.blue(e):e);break;case`debug`:i=t.map(e=>typeof e==`string`?M.gray(e):e);break}}catch(e){console.error(`Internal Logger Error applying chalk color:`,e),i=t}console.error(r,...i)}}function tt(){let e=e=>(...t)=>B(e,...t);return{debug:e(`debug`),info:e(`info`),warn:e(`warn`),error:e(`error`),success:e(`success`),log:B}}var V=tt(),H=class extends Error{constructor(e,t={}){super(e),this.name=`MCPError`,this.code=t.code,this.cause=t.cause,this.mcpResponse=t.mcpResponse}},U=class extends H{constructor(e,t={}){super(e,t),this.name=`MCPSessionError`}},nt=class extends H{constructor(e,t={}){super(e,t),this.name=`MCPSamplingError`}};function W(e){if(e instanceof H)return e;let t=e.message||`Unknown MCP error`,n=e;return t.includes(`session`)||t.includes(`connection`)?new U(t,{cause:n,code:`SESSION_ERROR`}):t.includes(`sampling`)||t.includes(`timeout`)?new nt(t,{cause:n,code:`SAMPLING_ERROR`}):t.includes(`capabilities`)||t.includes(`not supported`)?new U(t,{cause:n,code:`CAPABILITY_ERROR`}):new H(t,{cause:n,code:`UNKNOWN_ERROR`})}function rt(e){let t=e.trim();t=t.replace(/^```json\s*/gm,``),t=t.replace(/^```\s*/gm,``),t=t.replace(/```\s*$/gm,``),t=t.replace(/^const\s+\w+\s*=\s*/,``),t=t.replace(/^let\s+\w+\s*=\s*/,``),t=t.replace(/^var\s+\w+\s*=\s*/,``),t=t.replace(/;?\s*$/,``),t=t.replace(/^.*?(?=\{|\[)/s,``),t.split(`
2
+ import{o as e,s as t}from"./ai-services-unified-D47kSPRC.js";import{$t as n,Dt as r,Ht as i,Kt as a,Mt as o,Nt as s,On as c,Qt as l,S as u,Sn as d,Tt as f,fn as p,h as m,ht as h,in as g,ln as _,ot as v,pn as y,rn as b,st as x,tn as S,tt as C,vn as ee,vt as w,wt as te,zt as ne}from"./config-manager-BHkHj6Wx.js";import"./git-utils-DllbRE35.js";import{r as re}from"./sentry-7KP4mTlv.js";import{$ as T,A as ie,B as E,C as ae,D as oe,Dt as se,Et as ce,F as le,G as ue,H as de,I as fe,J as pe,M as me,N as he,O as ge,P as _e,Q as ve,R as D,S as ye,U as be,V as xe,W as Se,X as Ce,Y as we,Z as Te,at as Ee,ct as De,dt as Oe,gt as ke,ht as Ae,i as je,it as Me,j as Ne,lt as Pe,n as Fe,pt as Ie,r as Le,rt as Re,st as ze,t as Be,ut as Ve,w as He,z as Ue}from"./dependency-manager-BPentJE1.js";import{t as We}from"./response-language-eRs_-hFV.js";import{a as Ge,c as Ke,f as qe,g as Je,h as Ye,l as O,m as k,p as Xe,v as A}from"./profiles-DZYu2yEn.js";import j from"node:path";import M from"chalk";import N from"fs";import P from"path";import Ze from"os";import F from"node:fs";import{z as I}from"zod";import{fileURLToPath as Qe}from"url";import L from"dotenv";import*as R from"@sentry/node";import{FastMCP as $e}from"fastmcp";const z={debug:0,info:1,warn:2,error:3,success:4},et=z[u().toLowerCase()]??z.info;function B(e,...t){if(w())return;let n={debug:M.gray(`[DEBUG]`),info:M.blue(`[INFO]`),warn:M.yellow(`[WARN]`),error:M.red(`[ERROR]`),success:M.green(`[SUCCESS]`)};if(z[e]!==void 0&&z[e]>=et){let r=n[e]||``,i=t;try{switch(e){case`error`:i=t.map(e=>typeof e==`string`?M.red(e):e);break;case`warn`:i=t.map(e=>typeof e==`string`?M.yellow(e):e);break;case`success`:i=t.map(e=>typeof e==`string`?M.green(e):e);break;case`info`:i=t.map(e=>typeof e==`string`?M.blue(e):e);break;case`debug`:i=t.map(e=>typeof e==`string`?M.gray(e):e);break}}catch(e){console.error(`Internal Logger Error applying chalk color:`,e),i=t}console.error(r,...i)}}function tt(){let e=e=>(...t)=>B(e,...t);return{debug:e(`debug`),info:e(`info`),warn:e(`warn`),error:e(`error`),success:e(`success`),log:B}}var V=tt(),H=class extends Error{constructor(e,t={}){super(e),this.name=`MCPError`,this.code=t.code,this.cause=t.cause,this.mcpResponse=t.mcpResponse}},U=class extends H{constructor(e,t={}){super(e,t),this.name=`MCPSessionError`}},nt=class extends H{constructor(e,t={}){super(e,t),this.name=`MCPSamplingError`}};function W(e){if(e instanceof H)return e;let t=e.message||`Unknown MCP error`,n=e;return t.includes(`session`)||t.includes(`connection`)?new U(t,{cause:n,code:`SESSION_ERROR`}):t.includes(`sampling`)||t.includes(`timeout`)?new nt(t,{cause:n,code:`SAMPLING_ERROR`}):t.includes(`capabilities`)||t.includes(`not supported`)?new U(t,{cause:n,code:`CAPABILITY_ERROR`}):new H(t,{cause:n,code:`UNKNOWN_ERROR`})}function rt(e){let t=e.trim();t=t.replace(/^```json\s*/gm,``),t=t.replace(/^```\s*/gm,``),t=t.replace(/```\s*$/gm,``),t=t.replace(/^const\s+\w+\s*=\s*/,``),t=t.replace(/^let\s+\w+\s*=\s*/,``),t=t.replace(/^var\s+\w+\s*=\s*/,``),t=t.replace(/;?\s*$/,``),t=t.replace(/^.*?(?=\{|\[)/s,``),t.split(`
3
3
  `);let n=-1,r=0,i=!1,a=!1;for(let e=0;e<t.length;e++){let o=t[e];if(a){a=!1;continue}if(o===`\\`){a=!0;continue}if(o===`"`&&!a){i=!i;continue}if(!i){if(o===`{`||o===`[`)r++;else if((o===`}`||o===`]`)&&(r--,r===0)){n=e;break}}}if(n>-1&&(t=t.substring(0,n+1)),n===-1){let e=t.match(/{[\s\S]*}/),n=t.match(/\[[\s\S]*\]/);e?t=e[0]:n&&(t=n[0])}try{return JSON.parse(t),t}catch{try{let e=t.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g,`$1"$2":`).replace(/'/g,`"`).replace(/,\s*([}\]])/g,`$1`);return JSON.parse(e),e}catch{return e}}}function G(e){let t=[],n=``;for(let r of e)r.role===`system`?n=K(r.content):(r.role===`user`||r.role===`assistant`)&&t.push({role:r.role,content:{type:`text`,text:K(r.content)}});return{messages:t,systemPrompt:n}}function it(e){let t=``,n=null,r=`stop`,i=[];return typeof e==`string`?t=e:e.content?(t=K(e.content),n=e.usage,r=e.finishReason||`stop`):e.text?(t=e.text,n=e.usage,r=e.finishReason||`stop`):(t=JSON.stringify(e),i.push(`Unexpected MCP response format, used JSON fallback`)),{text:t,usage:n,finishReason:r,warnings:i}}function K(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e==`string`?e:e.type===`text`&&e.text||e.text?e.text:``).filter(e=>e.length>0).join(` `):e&&typeof e==`object`&&(e.type===`text`&&e.text||e.text)?e.text:String(e||``)}function at(e,t=`result`){try{let n=q(e);return`
4
4
  CRITICAL JSON GENERATION INSTRUCTIONS:
5
5
 
@@ -41,4 +41,4 @@ Current Tag: ${n.currentTag}`),{content:[{type:`text`,text:r}],isError:!0}}funct
41
41
 
42
42
  ### Results
43
43
 
44
- ${y.result}`;if(e){let{updateSubtaskById:e}=await import(`./update-subtask-by-id-DKVRZTLI.js`);await e(P.join(d,`.taskmaster`,`tasks`,`tasks.json`),l,n,!1,{session:p,mcpLog:m,commandName:`research-save`,outputType:`mcp`,projectRoot:d,tag:f},`json`),t.info(`Research saved to subtask ${l}`)}else{let e=(await import(`./update-task-by-id-aVi1O1ZL.js`)).default,r=parseInt(l,10);await e(P.join(d,`.taskmaster`,`tasks`,`tasks.json`),r,n,!1,{session:p,mcpLog:m,commandName:`research-save`,outputType:`mcp`,projectRoot:d,tag:f},`json`,!0),t.info(`Research saved to task ${l}`)}}catch(e){t.warn(`Error saving research to task/subtask: ${e.message}`)}return v(),{success:!0,data:{query:y.query,result:y.result,contextSize:y.contextSize,contextTokens:y.contextTokens,tokenBreakdown:y.tokenBreakdown,systemPromptTokens:y.systemPromptTokens,userPromptTokens:y.userPromptTokens,totalInputTokens:y.totalInputTokens,detailLevel:y.detailLevel,telemetryData:y.telemetryData,tagInfo:y.tagInfo,savedFilePath:y.savedFilePath}}}catch(e){return v(),t.error(`Error in researchDirect: ${e.message}`),{success:!1,error:{code:e.code||`RESEARCH_ERROR`,message:e.message}}}}async function mn(e,t,n={}){let{tasksJsonPath:r,id:i,strength:a=`regular`,prompt:o,research:s=!1,projectRoot:c,tag:l}=e,{session:u}=n;x();let d=D(t);try{if(!r)return t.error(`scopeDownDirect called without tasksJsonPath`),v(),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`tasksJsonPath is required`}};if(!i)return t.error(`Missing required parameter: id`),v(),{success:!1,error:{code:`MISSING_PARAMETER`,message:`The id parameter is required for scoping down tasks`}};let e=i.split(`,`).map(e=>parseInt(e.trim(),10));t.info(`Scoping down tasks: ${e.join(`, `)}, strength: ${a}, research: ${s}`);let n=await oe(r,e,a,o,{session:u,mcpLog:d,projectRoot:c,commandName:`scope-down`,outputType:`mcp`,tag:l,research:s},`json`);return v(),{success:!0,data:{updatedTasks:n.updatedTasks,tasksUpdated:n.updatedTasks.length,message:`Successfully scoped down ${n.updatedTasks.length} task(s)`,telemetryData:n.telemetryData}}}catch(e){return v(),t.error(`Error in scopeDownDirect: ${e.message}`),{success:!1,error:{code:e.code||`SCOPE_DOWN_ERROR`,message:e.message}}}}async function hn(e,t,n={}){let{tasksJsonPath:r,id:i,strength:a=`regular`,prompt:o,research:s=!1,projectRoot:c,tag:l}=e,{session:u}=n;x();let d=D(t);try{if(!r)return t.error(`scopeUpDirect called without tasksJsonPath`),v(),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`tasksJsonPath is required`}};if(!i)return t.error(`Missing required parameter: id`),v(),{success:!1,error:{code:`MISSING_PARAMETER`,message:`The id parameter is required for scoping up tasks`}};let e=i.split(`,`).map(e=>parseInt(e.trim(),10));t.info(`Scoping up tasks: ${e.join(`, `)}, strength: ${a}, research: ${s}`);let n=await ge(r,e,a,o,{session:u,mcpLog:d,projectRoot:c,commandName:`scope-up`,outputType:`mcp`,tag:l,research:s},`json`);return v(),{success:!0,data:{updatedTasks:n.updatedTasks,tasksUpdated:n.updatedTasks.length,message:`Successfully scoped up ${n.updatedTasks.length} task(s)`,telemetryData:n.telemetryData}}}catch(e){return v(),t.error(`Error in scopeUpDirect: ${e.message}`),{success:!1,error:{code:e.code||`SCOPE_UP_ERROR`,message:e.message}}}}async function gn(e,t,n={}){let{session:r}=n,{tasksJsonPath:i,id:a,prompt:o,research:s,metadata:c,projectRoot:l,tag:u}=e,d=D(t);try{if(d.info(`Updating subtask by ID via direct function. ID: ${a}, ProjectRoot: ${l}`),!i){let e=`tasksJsonPath is required but was not provided.`;return d.error(e),{success:!1,error:{code:`MISSING_ARGUMENT`,message:e}}}if(!a||typeof a!=`string`||!a.trim()){let e=`Subtask ID cannot be empty.`;return d.error(e),{success:!1,error:{code:`INVALID_SUBTASK_ID`,message:e}}}if(!o&&!c){let e=`No prompt or metadata specified. Please provide information to append or metadata to update.`;return d.error(e),{success:!1,error:{code:`MISSING_PROMPT`,message:e}}}let e=String(a).trim(),n=i,f=s===!0;t.info(`Updating subtask with ID ${e} with prompt "${o||`(metadata-only)`}" and research: ${f}`);let p=w();p||x();try{let t=await He(n,e,o,f,{mcpLog:d,session:r,projectRoot:l,tag:u,commandName:`update-subtask`,outputType:`mcp`,metadata:c},`json`);if(!t||t.updatedSubtask===null){let e=`Subtask ${a} or its parent task not found.`;return d.error(e),{success:!1,error:{code:`SUBTASK_NOT_FOUND`,message:e}}}let i=e.split(`.`)[0],s=`Successfully updated subtask with ID ${e}`;return d.success(s),{success:!0,data:{message:`Successfully updated subtask with ID ${e}`,subtaskId:e,parentId:i,subtask:t.updatedSubtask,tasksPath:n,useResearch:f,telemetryData:t.telemetryData,tagInfo:t.tagInfo}}}catch(e){return d.error(`Error updating subtask by ID: ${e.message}`),{success:!1,error:{code:`UPDATE_SUBTASK_CORE_ERROR`,message:e.message||`Unknown error updating subtask`}}}finally{!p&&w()&&v()}}catch(e){return d.error(`Setup error in updateSubtaskByIdDirect: ${e.message}`),w()&&v(),{success:!1,error:{code:`DIRECT_FUNCTION_SETUP_ERROR`,message:e.message||`Unknown setup error`}}}}async function _n(e,t,n={}){let{session:r}=n,{tasksJsonPath:i,id:a,prompt:o,research:s,append:c,metadata:l,projectRoot:u,tag:d}=e,f=D(t);try{if(f.info(`Updating task by ID via direct function. ID: ${a}, ProjectRoot: ${u}`),!a){let e=`No task ID specified. Please provide a task ID to update.`;return f.error(e),{success:!1,error:{code:`INPUT_VALIDATION_ERROR`,message:e}}}if(!o&&!l){let e=`No prompt or metadata specified. Please provide a prompt with new information or metadata for the task update.`;return f.error(e),{success:!1,error:{code:`INPUT_VALIDATION_ERROR`,message:e}}}let t;if(typeof a==`string`)t=a;else if(typeof a==`number`)t=String(a);else{let e=`Invalid task ID type: ${typeof a}. Task ID must be a string or number.`;return f.error(e),{success:!1,error:{code:`INPUT_VALIDATION_ERROR`,message:e}}}let n=i||E({projectRoot:u,file:e.file},f);if(!n){let e=`tasks.json path could not be resolved.`;return f.error(e),{success:!1,error:{code:`INPUT_VALIDATION_ERROR`,message:e}}}let p=s===!0;f.info(`Updating task with ID ${t} with prompt "${o||`(metadata-only)`}" and research: ${p}`);let m=w();m||x();try{let e=await ae(n,t,o,p,{mcpLog:f,session:r,projectRoot:u,tag:d,commandName:`update-task`,outputType:`mcp`,metadata:l},`json`,c||!1);if(!e||e.updatedTask===null){let n=`Task ${t} was not updated (likely already completed).`;return f.info(n),{success:!0,data:{message:n,taskId:t,updated:!1,telemetryData:e?.telemetryData,tagInfo:e?.tagInfo}}}let i=`Successfully updated task with ID ${t} based on the prompt`;return f.info(i),{success:!0,data:{message:i,taskId:t,tasksPath:n,useResearch:p,updated:!0,updatedTask:e.updatedTask,telemetryData:e.telemetryData,tagInfo:e.tagInfo}}}catch(e){return f.error(`Error updating task by ID: ${e.message}`),{success:!1,error:{code:`UPDATE_TASK_CORE_ERROR`,message:e.message||`Unknown error updating task`}}}finally{!m&&w()&&v()}}catch(e){return f.error(`Setup error in updateTaskByIdDirect: ${e.message}`),w()&&v(),{success:!1,error:{code:`DIRECT_FUNCTION_SETUP_ERROR`,message:e.message||`Unknown setup error`}}}}async function vn(e,t,n={}){let{session:r}=n,{from:i,prompt:a,research:o,tasksJsonPath:s,projectRoot:c,tag:l}=e,u=D(t);if(!c)return u.error(`updateTasksDirect requires a projectRoot argument.`),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`projectRoot is required.`}};if(!i)return u.error(`updateTasksDirect called without from ID`),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`Starting task ID (from) is required`}};if(!a)return u.error(`updateTasksDirect called without prompt`),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`Update prompt is required`}};u.info(`Updating tasks via direct function. From: ${i}, Research: ${o}, File: ${s}, ProjectRoot: ${c}`),x();try{let e=await ye(s,i,a,o,{session:r,mcpLog:u,projectRoot:c,tag:l},`json`);return e&&e.success&&Array.isArray(e.updatedTasks)?(u.success(`Successfully updated ${e.updatedTasks.length} tasks.`),{success:!0,data:{message:`Successfully updated ${e.updatedTasks.length} tasks.`,tasksPath:s,updatedCount:e.updatedTasks.length,telemetryData:e.telemetryData,tagInfo:e.tagInfo}}):(u.error(`Core updateTasks function did not return a successful structure.`),{success:!1,error:{code:`CORE_FUNCTION_ERROR`,message:e?.message||`Core function failed to update tasks or returned unexpected result.`}})}catch(e){return u.error(`Error executing core updateTasks: ${e.message}`),{success:!1,error:{code:`UPDATE_TASKS_CORE_ERROR`,message:e.message||`Unknown error updating tasks`}}}finally{v()}}async function yn(e,t,n={}){let{tasksJsonPath:r,name:i,projectRoot:a}=e,{session:o}=n;x();let s=D(t);try{if(!r)return t.error(`useTagDirect called without tasksJsonPath`),v(),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`tasksJsonPath is required`}};if(!i||typeof i!=`string`)return t.error(`Missing required parameter: name`),v(),{success:!1,error:{code:`MISSING_PARAMETER`,message:`Tag name is required and must be a string`}};t.info(`Switching to tag: ${i}`);let e=await Ae(r,i,{},{session:o,mcpLog:s,projectRoot:a},`json`);return v(),{success:!0,data:{tagName:e.currentTag,switched:e.switched,previousTag:e.previousTag,taskCount:e.taskCount,message:`Successfully switched to tag "${e.currentTag}"`}}}catch(e){return v(),t.error(`Error in useTagDirect: ${e.message}`),{success:!1,error:{code:e.code||`USE_TAG_ERROR`,message:e.message}}}}async function bn(e,t){let{tasksJsonPath:n,projectRoot:r,tag:i}=e;if(!n)return t.error(`validateDependenciesDirect called without tasksJsonPath`),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`tasksJsonPath is required`}};try{t.info(`Validating dependencies in tasks: ${n}`);let e=n;return N.existsSync(e)?(x(),await je(e,{projectRoot:r,tag:i}),v(),{success:!0,data:{message:`Dependencies validated successfully`,tasksPath:e}}):{success:!1,error:{code:`FILE_NOT_FOUND`,message:`Tasks file not found at ${e}`}}}catch(e){return v(),t.error(`Error validating dependencies: ${e.message}`),{success:!1,error:{code:`VALIDATION_ERROR`,message:e.message}}}}function xn(e){e.addTool({name:`add_dependency`,description:`Add a dependency relationship between two tasks`,parameters:I.object({id:I.string().describe(`ID of task that will depend on another task`),dependsOn:I.string().describe(`ID of task that will become a dependency`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Add Dependency`,destructiveHint:!0},execute:Q(`add-dependency`,async(e,{log:t,session:n})=>{try{t.info(`Adding dependency for task ${e.id} to depend on ${e.dependsOn}`);let n=r({projectRoot:e.projectRoot,tag:e.tag}),i;try{i=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await zt({tasksJsonPath:i,id:e.id,dependsOn:e.dependsOn,projectRoot:e.projectRoot,tag:n},t);return a.success?t.info(`Successfully added dependency: ${a.data.message}`):t.error(`Failed to add dependency: ${a.error.message}`),Y({result:a,log:t,errorPrefix:`Error adding dependency`,projectRoot:e.projectRoot,tag:n})}catch(e){return t.error(`Error in addDependency tool: ${e.message}`),J(e.message)}})})}function Sn(e){e.addTool({name:`add_subtask`,description:`Add a subtask to an existing task`,parameters:I.object({id:I.string().describe(`Parent task ID (required)`),taskId:I.string().optional().describe(`Existing task ID to convert to subtask`),title:I.string().optional().describe(`Title for the new subtask (when creating a new subtask)`),description:I.string().optional().describe(`Description for the new subtask`),details:I.string().optional().describe(`Implementation details for the new subtask`),status:I.string().optional().describe(`Status for the new subtask (default: 'pending')`),dependencies:I.string().optional().describe(`Comma-separated list of dependency IDs for the new subtask`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),skipGenerate:I.boolean().optional().describe(`Skip regenerating task files`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Add Subtask`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{let i=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Adding subtask with args: ${JSON.stringify(e)}`);let a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o=await Bt({tasksJsonPath:a,id:e.id,taskId:e.taskId,title:e.title,description:e.description,details:e.details,status:e.status,dependencies:e.dependencies,skipGenerate:e.skipGenerate,projectRoot:e.projectRoot,tag:i},t,{session:n});return o.success?t.info(`Subtask added successfully: ${o.data.message}`):t.error(`Failed to add subtask: ${o.error.message}`),Y({result:o,log:t,errorPrefix:`Error adding subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in addSubtask tool: ${e.message}`),J(e.message)}})})}function Cn(e){e.addTool({name:`add_tag`,description:`Create a new tag for organizing tasks in different contexts`,parameters:I.object({name:I.string().describe(`Name of the new tag to create`),copyFromCurrent:I.boolean().optional().describe(`Whether to copy tasks from the current tag (default: false)`),copyFromTag:I.string().optional().describe(`Specific tag to copy tasks from`),fromBranch:I.boolean().optional().describe(`Create tag name from current git branch (ignores name parameter)`),description:I.string().optional().describe(`Optional description for the tag`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Add Tag`,destructiveHint:!1},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting add-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await Vt({tasksJsonPath:r,name:e.name,copyFromCurrent:e.copyFromCurrent,copyFromTag:e.copyFromTag,fromBranch:e.fromBranch,description:e.description,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error creating tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in add-tag tool: ${e.message}`),J(e.message)}})})}function wn(e){e.addTool({name:`add_task`,description:`Add a new task using AI`,parameters:I.object({prompt:I.string().optional().describe(`Description of the task to add (required if not using manual fields)`),title:I.string().optional().describe(`Task title (for manual task creation)`),description:I.string().optional().describe(`Task description (for manual task creation)`),details:I.string().optional().describe(`Implementation details (for manual task creation)`),testStrategy:I.string().optional().describe(`Test strategy (for manual task creation)`),dependencies:I.string().optional().describe(`Comma-separated list of task IDs this task depends on`),priority:I.string().optional().describe(`Task priority (high, medium, low)`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`),research:I.boolean().optional().describe(`Whether to use research capabilities for task creation`)}),annotations:{title:`Add Task`,destructiveHint:!1},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting add-task with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await Ht({tasksJsonPath:a,prompt:e.prompt,title:e.title,description:e.description,details:e.details,testStrategy:e.testStrategy,dependencies:e.dependencies,priority:e.priority,research:e.research,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error adding task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in add-task tool: ${e.message}`),J(e.message)}})})}function Tn(e){e.addTool({name:`analyze_project_complexity`,description:`Analyze task complexity and generate expansion recommendations.`,parameters:I.object({threshold:I.coerce.number().int().min(1).max(10).optional().default(5).describe(`Complexity score threshold (1-10) to recommend expansion.`),research:I.boolean().optional().default(!1).describe(`Use Perplexity AI for research-backed analysis.`),output:I.string().optional().describe(`Output file path relative to project root (default: ${s}).`),file:I.string().optional().describe(`Path to the tasks file relative to project root (default: tasks/tasks.json).`),ids:I.string().optional().describe(`Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").`),from:I.coerce.number().int().positive().optional().describe(`Starting task ID in a range to analyze.`),to:I.coerce.number().int().positive().optional().describe(`Ending task ID in a range to analyze.`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Analyze Project Complexity`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{let i=`analyze_project_complexity`;try{t.info(`Executing ${i} tool with args: ${JSON.stringify(e)}`);let a=r({projectRoot:e.projectRoot,tag:e.tag}),o;try{o=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`${i}: Resolved tasks path: ${o}`)}catch(n){return t.error(`${i}: Error finding tasks.json: ${n.message}`),J(`Failed to find tasks.json within project root '${e.projectRoot}': ${n.message}`)}let s=C(e.output,{projectRoot:e.projectRoot,tag:a},t);t.info(`${i}: Report output path: ${s}`);let c=P.dirname(s);try{N.existsSync(c)||(N.mkdirSync(c,{recursive:!0}),t.info(`${i}: Created output directory: ${c}`))}catch(e){return t.error(`${i}: Failed to create output directory ${c}: ${e.message}`),J(`Failed to create output directory: ${e.message}`)}let l=await Ut({tasksJsonPath:o,outputPath:s,threshold:e.threshold,research:e.research,projectRoot:e.projectRoot,tag:a,ids:e.ids,from:e.from,to:e.to},t,{session:n});return t.info(`${i}: Direct function result: success=${l.success}`),Y({result:l,log:t,errorPrefix:`Error analyzing task complexity`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${i} tool execute: ${e.message}`),J(`Internal tool error (${i}): ${e.message}`)}})})}function En(e){e.addTool({name:`clear_subtasks`,description:`Clear subtasks from specified tasks`,parameters:I.object({id:I.string().optional().describe(`Task IDs (comma-separated) to clear subtasks from`),all:I.boolean().optional().describe(`Clear subtasks from all tasks`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}).refine(e=>e.id||e.all,{message:`Either 'id' or 'all' parameter must be provided`,path:[`id`,`all`]}),annotations:{title:`Clear Subtasks`,destructiveHint:!0},execute:Q(`clear-subtasks`,async(e,t)=>{try{t.log.info(`Clearing subtasks with args: ${JSON.stringify(e)}`);let n=r({projectRoot:e.projectRoot,tag:e.tag}),i;try{i=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await Wt({tasksJsonPath:i,id:e.id,all:e.all,projectRoot:e.projectRoot,tag:n},t.log,{session:t.session});return a.success?t.log.info(`Subtasks cleared successfully: ${a.data.message}`):t.log.error(`Failed to clear subtasks: ${a.error.message}`),Y({result:a,log:t.log,errorPrefix:`Error clearing subtasks`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in clearSubtasks tool: ${e.message}`),J(e.message)}})})}function Dn(e){e.addTool({name:`complexity_report`,description:`Display the complexity analysis report in a readable format`,parameters:I.object({file:I.string().optional().describe(`Path to the report file (default: ${s})`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Complexity Report`,readOnlyHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Getting complexity report with args: ${JSON.stringify(e)}`);let n=h(e.projectRoot),r=Ue({projectRoot:e.projectRoot,complexityReport:e.file,tag:n},t);if(t.info(`Reading complexity report from path: `,r),!r)return J(`No complexity report found. Run task-master analyze-complexity first.`);let i=await Gt({reportPath:r},t);return i.success?t.info(`Successfully retrieved complexity report`):t.error(`Failed to retrieve complexity report: ${i.error.message}`),Y({result:i,log:t,errorPrefix:`Error retrieving complexity report`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in complexity-report tool: ${e.message}`),J(`Failed to retrieve complexity report: ${e.message}`)}})})}function On(e){e.addTool({name:`copy_tag`,description:`Copy an existing tag to create a new tag with all tasks and metadata`,parameters:I.object({sourceName:I.string().describe(`Name of the source tag to copy from`),targetName:I.string().describe(`Name of the new tag to create`),description:I.string().optional().describe(`Optional description for the new tag`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Copy Tag`,destructiveHint:!1},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting copy-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await Kt({tasksJsonPath:r,sourceName:e.sourceName,targetName:e.targetName,description:e.description,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error copying tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in copy-tag tool: ${e.message}`),J(e.message)}})})}function kn(e){e.addTool({name:`delete_tag`,description:`Delete an existing tag and all its tasks`,parameters:I.object({name:I.string().describe(`Name of the tag to delete`),yes:I.boolean().optional().describe(`Skip confirmation prompts (default: true for MCP)`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Delete Tag`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting delete-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await qt({tasksJsonPath:r,name:e.name,yes:e.yes===void 0?!0:e.yes,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error deleting tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in delete-tag tool: ${e.message}`),J(e.message)}})})}function An(e){e.addTool({name:`expand_all`,description:`Expand all pending tasks into subtasks based on complexity or defaults`,parameters:I.object({num:I.string().optional().describe(`Target number of subtasks per task (uses complexity/defaults otherwise)`),research:I.boolean().optional().describe(`Enable research-backed subtask generation (e.g., using Perplexity)`),prompt:I.string().optional().describe(`Additional context to guide subtask generation for all tasks`),force:I.boolean().optional().describe(`Force regeneration of subtasks for tasks that already have them`),file:I.string().optional().describe(`Absolute path to the tasks file in the /tasks folder inside the project root (default: tasks/tasks.json)`),projectRoot:I.string().optional().describe(`Absolute path to the project root directory (derived from session if possible)`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Expand All Tasks`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Tool expand_all execution started with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`Resolved tasks.json path: ${a}`)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o=xe(null,{projectRoot:e.projectRoot,tag:i},t);return t.info(`Using complexity report path: ${o}`),Y({result:await Jt({tasksJsonPath:a,num:e.num,research:e.research,prompt:e.prompt,force:e.force,projectRoot:e.projectRoot,tag:i,complexityReportPath:o},t,{session:n}),log:t,errorPrefix:`Error expanding all tasks`,projectRoot:e.projectRoot})}catch(e){return t.error(`Unexpected error in expand_all tool execute: ${e.message}`),e.stack&&t.error(e.stack),J(`An unexpected error occurred: ${e.message}`)}})})}function jn(e){e.addTool({name:`expand_task`,description:`Expand a task into subtasks for detailed implementation`,parameters:I.object({id:I.string().describe(`ID of task to expand`),num:I.string().optional().describe(`Number of subtasks to generate`),research:I.boolean().optional().default(!1).describe(`Use research role for generation`),prompt:I.string().optional().describe(`Additional context for subtask generation`),file:I.string().optional().describe(`Path to the tasks file relative to project root (e.g., tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),force:I.boolean().optional().default(!1).describe(`Force expansion even if subtasks exist`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Expand Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting expand-task with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o=Ue({...e,tag:i},t);return Y({result:await Yt({tasksJsonPath:a,id:e.id,num:e.num,research:e.research,prompt:e.prompt,force:e.force,complexityReportPath:o,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error expanding task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in expand-task tool: ${e.message}`),J(e.message)}})})}function Mn(e){e.addTool({name:`fix_dependencies`,description:`Fix invalid dependencies in tasks automatically`,parameters:I.object({file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Fix Dependencies`,destructiveHint:!0},execute:Q(`fix-dependencies`,async(e,t)=>{try{t.log.info(`Fixing dependencies with args: ${JSON.stringify(e)}`);let n=r({projectRoot:e.projectRoot,tag:e.tag}),i;try{i=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await Xt({tasksJsonPath:i,projectRoot:e.projectRoot,tag:n},t.log);return a.success?t.log.info(`Successfully fixed dependencies: ${a.data.message}`):t.log.error(`Failed to fix dependencies: ${a.error.message}`),Y({result:a,log:t.log,errorPrefix:`Error fixing dependencies`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in fixDependencies tool: ${e.message}`),J(e.message)}})})}function Nn(e){e.addTool({name:`initialize_project`,description:`Initializes a new Task Master project structure by calling the core initialization logic. Creates necessary folders and configuration files for Task Master in the current directory. If you are using Codex CLI, set withCodex=true (and keep yes=true) so Codex longrun assets are created in the same step.`,parameters:I.object({skipInstall:I.boolean().optional().default(!1).describe(`Skip installing dependencies automatically. Never do this unless you are sure the project is already installed.`),addAliases:I.boolean().optional().default(!0).describe(`Add shell aliases (tm, taskmaster, hamster, ham) to shell config file.`),initGit:I.boolean().optional().default(!0).describe(`Initialize Git repository in project root.`),storeTasksInGit:I.boolean().optional().default(!0).describe(`Store tasks in Git (tasks.json and tasks/ directory).`),yes:I.boolean().optional().default(!0).describe(`Skip prompts and use default values. Always set to true for MCP tools.`),withCodex:I.boolean().optional().default(!1).describe(`Initialize Codex longrun assets together with project init. For Codex CLI workflows, set this to true.`),projectRoot:I.string().describe(`The root directory for the project. ALWAYS SET THIS TO THE PROJECT ROOT DIRECTORY. IF NOT SET, THE TOOL WILL NOT WORK.`),rules:I.array(I.enum(A)).optional().describe(`List of rule profiles to include at initialization. If omitted, defaults to Cursor profile only. Available options: ${A.join(`, `)}`)}),annotations:{title:`Initialize Project`,destructiveHint:!0},execute:Z(async(e,t)=>{let{log:n}=t,r=t.session;try{return n.info(`Executing initialize_project tool with args: ${JSON.stringify(e)}`),Y({result:await Zt(e,n,{session:r}),log:n,errorPrefix:`Initialization failed`,projectRoot:e.projectRoot})}catch(e){let t=`Project initialization tool failed: ${e.message||`Unknown error`}`;return n.error(t,e),J(t,{details:e.stack})}})})}function Pn(e){e.addTool({name:`list_tags`,description:`List all available tags with task counts and metadata`,parameters:I.object({showMetadata:I.boolean().optional().describe(`Whether to include metadata in the output (default: false)`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`List Tags`,readOnlyHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting list-tags with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await Qt({tasksJsonPath:r,showMetadata:e.showMetadata,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error listing tags`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in list-tags tool: ${e.message}`),J(e.message)}})})}function Fn(e){e.addTool({name:`models`,description:`Get information about available AI models or set model configurations. Run without arguments to get the current model configuration and API key status for the selected model providers.`,parameters:I.object({setMain:I.string().optional().describe(`Set the primary model for task generation/updates. Model provider API key is required in the MCP config ENV.`),setResearch:I.string().optional().describe(`Set the model for research-backed operations. Model provider API key is required in the MCP config ENV.`),setFallback:I.string().optional().describe(`Set the model to use if the primary fails. Model provider API key is required in the MCP config ENV.`),listAvailableModels:I.boolean().optional().describe(`List all available models not currently in use. Input/output costs values are in dollars (3 is $3.00).`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),openrouter:I.boolean().optional().describe(`Indicates the set model ID is a custom OpenRouter model.`),ollama:I.boolean().optional().describe(`Indicates the set model ID is a custom Ollama model.`),bedrock:I.boolean().optional().describe(`Indicates the set model ID is a custom AWS Bedrock model.`),azure:I.boolean().optional().describe(`Indicates the set model ID is a custom Azure OpenAI model.`),vertex:I.boolean().optional().describe(`Indicates the set model ID is a custom Google Vertex AI model.`),"openai-compatible":I.boolean().optional().describe(`Indicates the set model ID is a custom OpenAI-compatible model. Requires baseURL parameter.`),baseURL:I.string().optional().describe(`Custom base URL for providers that support it (e.g., https://api.example.com/v1).`)}),annotations:{title:`Models`,destructiveHint:!0},execute:Q(`models`,async(e,t)=>{try{return t.log.info(`Starting models tool with args: ${JSON.stringify(e)}`),Y({result:await nn({...e,projectRoot:e.projectRoot},t.log,{session:t.session}),log:t.log,errorPrefix:`Error managing models`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in models tool: ${e.message}`),J(e.message)}})})}function In(e){e.addTool({name:`move_task`,description:`Move a task or subtask to a new position`,parameters:I.object({from:I.string().describe(`ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")`),to:I.string().optional().describe(`ID of the destination (e.g., "7" or "7.3"). Required for within-tag moves. For cross-tag moves, if omitted, task will be moved to the target tag maintaining its ID`),file:I.string().optional().describe(`Custom path to tasks.json file`),projectRoot:I.string().describe(`Root directory of the project (typically derived from session)`),tag:I.string().optional().describe(`Tag context to operate on`),fromTag:I.string().optional().describe(`Source tag for cross-tag moves`),toTag:I.string().optional().describe(`Target tag for cross-tag moves`),withDependencies:I.boolean().optional().describe(`Move dependent tasks along with main task`),ignoreDependencies:I.boolean().optional().describe(`Break cross-tag dependencies during move`)}),annotations:{title:`Move Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{if(e.fromTag&&e.toTag&&e.fromTag!==e.toTag){if(!e.from)return J(`Source IDs are required for cross-tag moves`,`MISSING_SOURCE_IDS`);e.to&&t.warn(`The "to" parameter is not used for cross-tag moves and will be ignored. Tasks retain their original IDs in the target tag.`);let r=e.file;return r||=E(e,t),Y({result:await rn({sourceIds:e.from,sourceTag:e.fromTag,targetTag:e.toTag,withDependencies:e.withDependencies||!1,ignoreDependencies:e.ignoreDependencies||!1,tasksJsonPath:r,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error moving tasks between tags`,projectRoot:e.projectRoot})}else{if(!e.to)return J(`Destination ID is required for within-tag moves`,`MISSING_DESTINATION_ID`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a=e.file;a||=E(e,t);let o=e.from.split(`,`).map(e=>e.trim()),s=e.to.split(`,`).map(e=>e.trim());if(o.length!==s.length){if(o.length>1){let r=[],c=[];for(let l=0;l<o.length;l++){let u=o[l],d=s[l];if(u===d){t.info(`Skipping ${u} -> ${d} (same ID)`),c.push({fromId:u,toId:d,reason:`same ID`});continue}let f=l===o.length-1,p=await an({sourceId:u,destinationId:d,tasksJsonPath:a,projectRoot:e.projectRoot,tag:i,generateFiles:f},t,{session:n});p.success?r.push(p.data):t.error(`Failed to move ${u} to ${d}: ${p.error.message}`)}return Y({result:{success:!0,data:{moves:r,skipped:c.length>0?c:void 0,message:`Successfully moved ${r.length} tasks${c.length>0?`, skipped ${c.length}`:``}`}},log:t,errorPrefix:`Error moving multiple tasks`,projectRoot:e.projectRoot})}return Y({result:{success:!0,data:{moves:results,skippedMoves,message:`Successfully moved ${results.length} tasks${skippedMoves.length>0?`, skipped ${skippedMoves.length} moves`:``}`}},log:t,errorPrefix:`Error moving multiple tasks`,projectRoot:e.projectRoot})}else return Y({result:await an({sourceId:e.from,destinationId:e.to,tasksJsonPath:a,projectRoot:e.projectRoot,tag:i,generateFiles:!0},t,{session:n}),log:t,errorPrefix:`Error moving task`,projectRoot:e.projectRoot})}}catch(e){return J(`Failed to move task: ${e.message}`,`MOVE_TASK_ERROR`)}})})}function Ln(e){e.addTool({name:`next_task`,description:`Find the next task to work on based on dependencies and status`,parameters:I.object({file:I.string().optional().describe(`Absolute path to the tasks file`),complexityReport:I.string().optional().describe(`Path to the complexity report file (relative to project root or absolute)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Next Task`,readOnlyHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Finding next task with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=ue(e,n)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o;try{o=de({...e,tag:i},n)}catch(e){t.error(`Error finding complexity report: ${e.message}`),o=null}let s=await on({tasksJsonPath:a,reportPath:o,projectRoot:e.projectRoot,tag:i},t,{session:n});return t.info(`Next task result: ${s.success?`found`:`none`}`),Y({result:s,log:t,errorPrefix:`Error finding next task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error finding next task: ${e.message}`),J(e.message)}})})}function Rn(e){e.addTool({name:`parse_prd`,description:`Parse a Product Requirements Document (PRD) text file to automatically generate initial tasks. Reinitializing the project is not necessary to run this tool. It is recommended to run parse-prd after initializing the project and creating/importing a prd.txt file in the project root's ${i} directory.`,parameters:I.object({input:I.string().optional().default(ne).describe(`Absolute path to the PRD document file (.txt, .md, etc.)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`),destination:I.enum([`local`,`hamster`]).optional().default(`local`).describe(`Where to parse the PRD: "local" writes tasks.json, "hamster" creates a cloud brief and tasks`),output:I.string().optional().describe(`Output path for tasks.json file (default: ${a})`),numTasks:I.string().optional().describe(`Approximate number of top-level tasks to generate (default: 10). As the agent, if you have enough information, ensure to enter a number of tasks that would logically scale with project complexity. Setting to 0 will allow Taskmaster to determine the appropriate number of tasks based on the complexity of the PRD. Avoid entering numbers above 50 due to context window limitations.`),force:I.boolean().optional().default(!1).describe(`Overwrite existing output file without prompting.`),research:I.boolean().optional().describe(`Enable Taskmaster to use the research role for potentially more informed task generation. Requires appropriate API key.`),append:I.boolean().optional().describe(`Append generated tasks to existing file.`)}),annotations:{title:`Parse PRD`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n,reportProgress:i})=>{try{let a=r({projectRoot:e.projectRoot,tag:e.tag}),o=dt(i,t);return Y({result:await sn({...e,tag:a},t,{session:n,reportProgress:o}),log:t,errorPrefix:`Error parsing PRD`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in parse_prd: ${e.message}`),J(`Failed to parse PRD: ${e.message}`)}})})}function zn(e){e.addTool({name:`remove_dependency`,description:`Remove a dependency from a task`,parameters:I.object({id:I.string().describe(`Task ID to remove dependency from`),dependsOn:I.string().describe(`Task ID to remove as a dependency`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Remove Dependency`,destructiveHint:!0},execute:Q(`remove-dependency`,async(e,t)=>{try{let n=r({projectRoot:e.projectRoot,tag:e.tag});t.log.info(`Removing dependency for task ${e.id} from ${e.dependsOn} with args: ${JSON.stringify(e)}`);let i;try{i=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await ln({tasksJsonPath:i,id:e.id,dependsOn:e.dependsOn,projectRoot:e.projectRoot,tag:n},t.log);return a.success?t.log.info(`Successfully removed dependency: ${a.data.message}`):t.log.error(`Failed to remove dependency: ${a.error.message}`),Y({result:a,log:t.log,errorPrefix:`Error removing dependency`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in removeDependency tool: ${e.message}`),J(e.message)}})})}function Bn(e){e.addTool({name:`remove_subtask`,description:`Remove a subtask from its parent task`,parameters:I.object({id:I.string().describe(`Subtask ID to remove in format 'parentId.subtaskId' (required)`),convert:I.boolean().optional().describe(`Convert the subtask to a standalone task instead of deleting it`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),skipGenerate:I.boolean().optional().describe(`Skip regenerating task files`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Remove Subtask`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{let i=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Removing subtask with args: ${JSON.stringify(e)}`);let a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o=await un({tasksJsonPath:a,id:e.id,convert:e.convert,skipGenerate:e.skipGenerate,projectRoot:e.projectRoot,tag:i},t,{session:n});return o.success?t.info(`Subtask removed successfully: ${o.data.message}`):t.error(`Failed to remove subtask: ${o.error.message}`),Y({result:o,log:t,errorPrefix:`Error removing subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in removeSubtask tool: ${e.message}`),J(e.message)}})})}function Vn(e){e.addTool({name:`remove_task`,description:`Remove a task or subtask permanently from the tasks list`,parameters:I.object({id:I.string().describe(`ID of the task or subtask to remove (e.g., '5' or '5.2'). Can be comma-separated to update multiple tasks/subtasks at once.`),file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),confirm:I.boolean().optional().describe(`Whether to skip confirmation prompt (default: false)`),tag:I.string().optional().describe(`Specify which tag context to operate on. Defaults to the current active tag.`)}),annotations:{title:`Remove Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Removing task(s) with ID(s): ${e.id}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}t.info(`Using tasks file path: ${a}`);let o=await dn({tasksJsonPath:a,id:e.id,projectRoot:e.projectRoot,tag:i},t,{session:n});return o.success?t.info(`Successfully removed task: ${e.id}`):t.error(`Failed to remove task: ${o.error.message}`),Y({result:o,log:t,errorPrefix:`Error removing task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in remove-task tool: ${e.message}`),J(`Failed to remove task: ${e.message}`)}})})}function Hn(e){e.addTool({name:`rename_tag`,description:`Rename an existing tag`,parameters:I.object({oldName:I.string().describe(`Current name of the tag to rename`),newName:I.string().describe(`New name for the tag`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Rename Tag`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting rename-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await fn({tasksJsonPath:r,oldName:e.oldName,newName:e.newName,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error renaming tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in rename-tag tool: ${e.message}`),J(e.message)}})})}function Un(e){e.addTool({name:`research`,description:`Perform AI-powered research queries with project context`,parameters:I.object({query:I.string().describe(`Research query/prompt (required)`),taskIds:I.string().optional().describe(`Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17")`),filePaths:I.string().optional().describe(`Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md")`),customContext:I.string().optional().describe(`Additional custom context text to include in the research`),includeProjectTree:I.boolean().optional().describe(`Include project file tree structure in context (default: false)`),detailLevel:I.enum([`low`,`medium`,`high`]).optional().describe(`Detail level for the research response (default: medium)`),saveTo:I.string().optional().describe(`Automatically save research results to specified task/subtask ID (e.g., "15" or "15.2")`),saveToFile:I.boolean().optional().describe(`Save research results to .taskmaster/docs/research/ directory (default: false)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Research`,destructiveHint:!0,openWorldHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{let i=r({projectRoot:e.projectRoot,tag:e.tag});return t.info(`Starting research with query: "${e.query.substring(0,100)}${e.query.length>100?`...`:``}"`),Y({result:await pn({query:e.query,taskIds:e.taskIds,filePaths:e.filePaths,customContext:e.customContext,includeProjectTree:e.includeProjectTree||!1,detailLevel:e.detailLevel||`medium`,saveTo:e.saveTo,saveToFile:e.saveToFile||!1,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error performing research`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in research tool: ${e.message}`),J(e.message)}})})}async function Wn(e,t,n={}){let{projectRoot:r,language:i}=e,a=D(t);t.info(`Executing response-language_direct with args: ${JSON.stringify(e)}`),t.info(`Using project root: ${r}`);try{return x(),We(i,{mcpLog:a,projectRoot:r})}catch(e){return{success:!1,error:{code:`DIRECT_FUNCTION_ERROR`,message:e.message,details:e.stack}}}finally{v()}}function Gn(e){e.addTool({name:`response-language`,description:`Get or set the response language for the project`,parameters:I.object({projectRoot:I.string().describe(`The root directory for the project. ALWAYS SET THIS TO THE PROJECT ROOT DIRECTORY. IF NOT SET, THE TOOL WILL NOT WORK.`),language:I.string().describe(`The new response language to set. like "中文" "English" or "español".`)}),annotations:{title:`Response Language`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{return t.info(`Executing response-language tool with args: ${JSON.stringify(e)}`),Y({result:await Wn({...e,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error setting response language`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in response-language tool: ${e.message}`),J(e.message)}})})}async function Kn(e,t,n={}){x();try{let{action:t,profiles:n,projectRoot:r,yes:i,force:a}=e;if(!t||!Array.isArray(n)||n.length===0||!r)return{success:!1,error:{code:`MISSING_ARGUMENT`,message:`action, profiles, and projectRoot are required.`}};let o=[],s=[];if(t===O.REMOVE){if(!a&&Ke(r,n)){let e=Ge(r);return e.filter(e=>!n.includes(e)),{success:!1,error:{code:`CRITICAL_REMOVAL_BLOCKED`,message:`CRITICAL: This operation would remove ALL remaining rule profiles (${n.join(`, `)}), leaving your project with no rules configurations. This could significantly impact functionality. Currently installed profiles: ${e.join(`, `)}. If you're certain you want to proceed, set force: true or use the CLI with --force flag.`}}}for(let e of n){if(!Ye(e)){o.push({profileName:e,success:!1,error:`The requested rule profile for '${e}' is unavailable. Supported profiles are: ${A.join(`, `)}.`});continue}let t=Je(r,k(e));o.push(t)}let e=o.filter(e=>e.success).map(e=>e.profileName),t=o.filter(e=>e.skipped).map(e=>e.profileName),i=o.filter(e=>e.error&&!e.success&&!e.skipped),s=o.filter(e=>e.notice),c=``;return e.length>0&&(c+=`Successfully removed Task Master rules: ${e.join(`, `)}.`),t.length>0&&(c+=`Skipped (default or protected): ${t.join(`, `)}.`),i.length>0&&(c+=i.map(e=>`Error removing ${e.profileName}: ${e.error}`).join(` `)),s.length>0&&(c+=` Notices: ${s.map(e=>`${e.profileName} - ${e.notice}`).join(`; `)}.`),v(),{success:i.length===0,data:{summary:c,results:o}}}else if(t===O.ADD){for(let e of n){if(!Ye(e)){s.push({profileName:e,success:!1,error:`Profile not found: static import missing for '${e}'. Valid profiles: ${A.join(`, `)}`});continue}let t=k(e),{success:n,failed:i}=Xe(r,t),a=t.rulesDir,o=P.join(r,a),c=t.profileDir,l=t.mcpConfig!==!1,u=l&&t.mcpConfigPath?P.join(r,t.mcpConfigPath):null,d=l&&u?N.existsSync(u):void 0,f=N.existsSync(o),p=N.existsSync(P.join(r,c)),m=i>0?`${i} rule files failed to convert.`:null,h={profileName:e,mcpConfigCreated:d,rulesDirCreated:f,profileFolderCreated:p,skipped:!1,error:m,success:(l?d:!0)&&f&&n>0&&!m};s.push(h)}let e=s.filter(e=>e.success).map(e=>e.profileName),t=s.filter(e=>e.error&&!e.success),i=``;return e.length>0&&(i+=`Successfully added rules: ${e.join(`, `)}.`),t.length>0&&(i+=t.map(e=>` Error adding ${e.profileName}: ${e.error}`).join(` `)),v(),{success:t.length===0,data:{summary:i,results:s}}}else return v(),{success:!1,error:{code:`INVALID_ACTION`,message:`Unknown action. Use "${O.ADD}" or "${O.REMOVE}".`}}}catch(e){return v(),t.error(`[rulesDirect] Error: ${e.message}`),{success:!1,error:{code:e.code||`RULES_ERROR`,message:e.message}}}}function qn(e){e.addTool({name:`rules`,description:`Add or remove rule profiles from the project.`,parameters:I.object({action:I.enum([`add`,`remove`]).describe(`Whether to add or remove rule profiles.`),profiles:I.array(I.enum(A)).min(1).describe(`List of rule profiles to add or remove (e.g., [\"cursor\", \"roo\"]). Available options: ${A.join(`, `)}`),projectRoot:I.string().describe(`The root directory of the project. Must be an absolute path.`),force:I.boolean().optional().default(!1).describe(`DANGEROUS: Force removal even if it would leave no rule profiles. Only use if you are absolutely certain.`)}),annotations:{title:`Rules`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{return t.info(`[rules tool] Executing action: ${e.action} for profiles: ${e.profiles.join(`, `)} in ${e.projectRoot}`),Y({result:await Kn(e,t,{session:n}),log:t,projectRoot:e.projectRoot})}catch(e){return t.error(`[rules tool] Error: ${e.message}`),J(e.message,{details:e.stack})}})})}function Jn(e){e.addTool({name:`scope_down_task`,description:`Decrease the complexity of one or more tasks using AI`,parameters:I.object({id:I.string().describe(`Comma-separated list of task IDs to scope down (e.g., "1,3,5")`),strength:I.string().optional().describe(`Strength level: light, regular, or heavy (default: regular)`),prompt:I.string().optional().describe(`Custom prompt for specific scoping adjustments`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`),research:I.boolean().optional().describe(`Whether to use research capabilities for scoping`)}),annotations:{title:`Scope Down Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting scope-down with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await mn({tasksJsonPath:a,id:e.id,strength:e.strength,prompt:e.prompt,research:e.research,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error scoping down task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in scope-down tool: ${e.message}`),J(e.message)}})})}function Yn(e){e.addTool({name:`scope_up_task`,description:`Increase the complexity of one or more tasks using AI`,parameters:I.object({id:I.string().describe(`Comma-separated list of task IDs to scope up (e.g., "1,3,5")`),strength:I.string().optional().describe(`Strength level: light, regular, or heavy (default: regular)`),prompt:I.string().optional().describe(`Custom prompt for specific scoping adjustments`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`),research:I.boolean().optional().describe(`Whether to use research capabilities for scoping`)}),annotations:{title:`Scope Up Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting scope-up with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await hn({tasksJsonPath:a,id:e.id,strength:e.strength,prompt:e.prompt,research:e.research,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error scoping up task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in scope-up tool: ${e.message}`),J(e.message)}})})}function Xn(e){e.addTool({name:`update_subtask`,description:`Appends timestamped information to a specific subtask without replacing existing content. If you just want to update the subtask status, use set_task_status instead.`,parameters:I.object({id:b.describe(`ID of the subtask to update in format "parentId.subtaskId" (e.g., "5.2"). Parent ID is the ID of the task that contains the subtask.`),prompt:I.string().optional().describe(`Information to add to the subtask. Required unless only updating metadata.`),research:I.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),metadata:I.string().optional().describe(`JSON string of metadata to merge into subtask metadata. Example: '{"ticketId": "JIRA-456", "reviewed": true}'. Requires TASK_MASTER_ALLOW_METADATA_UPDATES=true in MCP environment.`),file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Subtask`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{let i=`update_subtask`;try{let a=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Updating subtask with args: ${JSON.stringify(e)}`);let o;try{o=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`${i}: Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let s=mt(e.metadata,J);if(s.error)return s.error;let c=s.parsedMetadata;if(!e.prompt&&!c)return J(`Either prompt or metadata must be provided for update-subtask`);let l=await gn({tasksJsonPath:o,id:e.id,prompt:e.prompt,research:e.research,metadata:c,projectRoot:e.projectRoot,tag:a},t,{session:n});return l.success?t.info(`Successfully updated subtask with ID ${e.id}`):t.error(`Failed to update subtask: ${l.error?.message||`Unknown error`}`),Y({result:l,log:t,errorPrefix:`Error updating subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${i} tool execute: ${e.message}`),J(`Internal tool error (${i}): ${e.message}`)}})})}function Zn(e){e.addTool({name:`update_task`,description:`Updates a single task by ID with new information or context provided in the prompt.`,parameters:I.object({id:I.string().describe(`ID of the task (e.g., '15') to update. Subtasks are supported using the update-subtask tool.`),prompt:I.string().optional().describe(`New information or context to incorporate into the task. Required unless only updating metadata.`),research:I.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),append:I.boolean().optional().describe(`Append timestamped information to task details instead of full update`),metadata:I.string().optional().describe(`JSON string of metadata to merge into task metadata. Example: '{"githubIssue": 42, "sprint": "Q1-S3"}'. Requires TASK_MASTER_ALLOW_METADATA_UPDATES=true in MCP environment.`),file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{let i=`update_task`;try{let a=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Executing ${i} tool with args: ${JSON.stringify(e)}`);let o;try{o=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`${i}: Resolved tasks path: ${o}`)}catch(e){return t.error(`${i}: Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let s=mt(e.metadata,J);if(s.error)return s.error;let c=s.parsedMetadata;if(!e.prompt&&!c)return J(`Either prompt or metadata must be provided for update-task`);let l=await _n({tasksJsonPath:o,id:e.id,prompt:e.prompt,research:e.research,append:e.append,metadata:c,projectRoot:e.projectRoot,tag:a},t,{session:n});return t.info(`${i}: Direct function result: success=${l.success}`),Y({result:l,log:t,errorPrefix:`Error updating task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${i} tool execute: ${e.message}`),J(`Internal tool error (${i}): ${e.message}`)}})})}function Qn(e){e.addTool({name:`update`,description:`Update multiple upcoming tasks (with ID >= 'from' ID) based on new context or changes provided in the prompt. Use 'update_task' instead for a single specific task or 'update_subtask' for subtasks.`,parameters:I.object({from:I.string().describe(`Task ID from which to start updating (inclusive). IMPORTANT: This tool uses 'from', not 'id'`),prompt:I.string().describe(`Explanation of changes or new context to apply`),research:I.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),file:I.string().optional().describe(`Path to the tasks file relative to project root`),projectRoot:I.string().optional().describe(`The directory of the project. (Optional, usually from session)`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Tasks`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{let i=`update`,{from:a,prompt:o,research:s,file:c,projectRoot:l,tag:u}=e,d=r({projectRoot:e.projectRoot,tag:e.tag});try{t.info(`Executing ${i} tool with normalized root: ${l}`);let r;try{r=E({projectRoot:l,file:c},t),t.info(`${i}: Resolved tasks path: ${r}`)}catch(e){return t.error(`${i}: Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json within project root '${l}': ${e.message}`)}let u=await vn({tasksJsonPath:r,from:a,prompt:o,research:s,projectRoot:l,tag:d},t,{session:n});return t.info(`${i}: Direct function result: success=${u.success}`),Y({result:u,log:t,errorPrefix:`Error updating tasks`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${i} tool execute: ${e.message}`),J(`Internal tool error (${i}): ${e.message}`)}})})}function $n(e){e.addTool({name:`use_tag`,description:`Switch to a different tag context for task operations`,parameters:I.object({name:I.string().describe(`Name of the tag to switch to`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Use Tag`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting use-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await yn({tasksJsonPath:r,name:e.name,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error switching tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in use-tag tool: ${e.message}`),J(e.message)}})})}function er(e){e.addTool({name:`validate_dependencies`,description:`Check tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.`,parameters:I.object({file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Validate Dependencies`,readOnlyHint:!0},execute:Q(`validate-dependencies`,async(e,{log:t,session:n})=>{try{let n=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Validating dependencies with args: ${JSON.stringify(e)}`);let i;try{i=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await bn({tasksJsonPath:i,projectRoot:e.projectRoot,tag:n},t);return a.success?t.info(`Successfully validated dependencies: ${a.data.message}`):t.error(`Failed to validate dependencies: ${a.error.message}`),Y({result:a,log:t,errorPrefix:`Error validating dependencies`,projectRoot:e.projectRoot,tag:n})}catch(e){return t.error(`Error in validateDependencies tool: ${e.message}`),J(e.message)}})})}const $={initialize_project:Nn,models:Fn,rules:qn,parse_prd:Rn,"response-language":Gn,analyze_project_complexity:Tn,expand_task:jn,expand_all:An,scope_up_task:Yn,scope_down_task:Jn,get_tasks:Mt,get_task:Pt,next_task:Ln,complexity_report:Dn,set_task_status:Rt,add_task:wn,add_subtask:Sn,update:Qn,update_task:Zn,update_subtask:Xn,remove_task:Vn,remove_subtask:Bn,clear_subtasks:En,move_task:In,add_dependency:xn,remove_dependency:zn,validate_dependencies:er,fix_dependencies:Mn,list_tags:Pn,add_tag:Cn,delete_tag:kn,use_tag:$n,rename_tag:Hn,copy_tag:On,research:Un,autopilot_start:gt,autopilot_resume:vt,autopilot_next:bt,autopilot_status:St,autopilot_complete:wt,autopilot_commit:Et,autopilot_finalize:Ot,autopilot_abort:At,generate:It},tr=[`get_tasks`,`next_task`,`get_task`,`set_task_status`,`update_subtask`,`parse_prd`,`expand_task`],nr=[...tr,`initialize_project`,`analyze_project_complexity`,`expand_all`,`add_subtask`,`remove_task`,`add_task`,`complexity_report`];function rr(e){return $[e]||null}function ir(){let e=process.env.TASK_MASTER_TOOLS;if(!e||e.trim()===``)return V.debug(`No TASK_MASTER_TOOLS env var found, defaulting to "core"`),`core`;let t=e.trim();return V.debug(`TASK_MASTER_TOOLS env var: "${t}"`),t}function ar(e,t=`core`){let n=[],r=[];try{let i=t.trim(),a=[],o=i.toLowerCase();switch(o){case`all`:a=Object.keys($),V.info(`Loading all available tools`);break;case`core`:case`lean`:a=tr,V.info(`Loading core tools only`);break;case`standard`:a=nr,V.info(`Loading standard tools`);break;default:let e=i.split(`,`).map(e=>e.trim()).filter(e=>e.length>0),t=new Set,n=[],r={response_language:`response-language`};for(let i of e){let e=null,a=i.toLowerCase();if(r[a]){let t=r[a];for(let n of Object.keys($))if(n.toLowerCase()===t.toLowerCase()){e=n;break}}if(!e){for(let t of Object.keys($))if(t.toLowerCase()===a){e=t;break}}if(!e){let t=a.replace(/_/g,`-`);for(let n of Object.keys($))if(n.toLowerCase()===t){e=n;break}}if(!e){let t=a.replace(/-/g,`_`);for(let n of Object.keys($))if(n.toLowerCase()===t){e=n;break}}e?(t.add(e),V.debug(`Resolved tool "${i}" to "${e}"`)):(n.push(i),V.warn(`Unknown tool specified: "${i}"`))}a=Array.from(t),n.length>0&&V.warn(`Unknown tools: ${n.join(`, `)}`),a.length===0?(V.warn(`No valid tools found in custom list. Loading all tools as fallback.`),a=Object.keys($)):V.info(`Loading ${a.length} custom tools from list (${t.size} unique after normalization)`);break}return V.info(`Registering ${a.length} MCP tools (mode: ${i})`),a.forEach(t=>{try{let i=rr(t);i?(i(e),V.debug(`Registered tool: ${t}`),n.push(t)):(V.warn(`Tool ${t} not found in registry`),r.push(t))}catch(e){e.message&&e.message.includes(`already registered`)?(V.debug(`Tool ${t} already registered, skipping`),n.push(t)):(V.error(`Failed to register tool ${t}: ${e.message}`),r.push(t))}}),V.info(`Successfully registered ${n.length}/${a.length} tools`),r.length>0&&V.warn(`Failed tools: ${r.join(`, `)}`),{registeredTools:n,failedTools:r,normalizedMode:o}}catch(t){V.error(`Error parsing TASK_MASTER_TOOLS environment variable: ${t.message}`),V.info(`Falling back to loading all tools`);let i=Object.keys($);for(let t of i){let i=rr(t);if(i)try{i(e),n.push(t)}catch(e){e.message&&e.message.includes(`already registered`)?(V.debug(`Fallback tool ${t} already registered, skipping`),n.push(t)):(V.warn(`Failed to register fallback tool '${t}': ${e.message}`),r.push(t))}else V.warn(`Tool '${t}' not found in registry`),r.push(t)}return V.info(`Successfully registered ${n.length} fallback tools`),{registeredTools:n,failedTools:r,normalizedMode:`all`}}}L.config(),re();const or=Qe(import.meta.url);P.dirname(or);var sr=class{constructor(){this.options={name:`Task Master MCP Server`,version:se};let e=new $e(this.options);if(e._mcpServer&&R.wrapMcpServerWithSentry)try{e._mcpServer=R.wrapMcpServerWithSentry(e._mcpServer)}catch(e){V.warn(`Failed to wrap MCP server with Sentry: ${e.message}`)}this.server=e,this.initialized=!1,this.init=this.init.bind(this),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this.logger=V}async init(){if(this.initialized)return;let e=ir();this.logger.info(`Task Master MCP Server starting...`),this.logger.info(`Tool mode configuration: ${e}`);let t=ar(this.server,e);return this.logger.info(`Normalized tool mode: ${t.normalizedMode}`),this.logger.info(`Registered ${t.registeredTools.length} tools successfully`),t.registeredTools.length>0&&this.logger.debug(`Registered tools: ${t.registeredTools.join(`, `)}`),t.failedTools.length>0&&this.logger.warn(`Failed to register ${t.failedTools.length} tools: ${t.failedTools.join(`, `)}`),this.initialized=!0,this}async start(){return this.initialized||await this.init(),this.server.on(`connect`,e=>{e.session.server.sendLoggingMessage({data:{context:e.session.context,message:`MCP Server connected: ${e.session.name}`},level:`info`}),this.registerRemoteProvider(e.session)}),await this.server.start({transportType:`stdio`,timeout:12e4}),this}registerRemoteProvider(e){if(e){if(!e.clientCapabilities||!e.clientCapabilities.sampling){e.server.sendLoggingMessage({data:{context:e.context,message:`MCP session missing required sampling capabilities, providers not registered`},level:`info`});return}let n=new lt;n.setSession(e),t.getInstance().registerProvider(`mcp`,n),e.server.sendLoggingMessage({data:{context:e.context,message:`MCP Server connected`},level:`info`})}else e.server.sendLoggingMessage({data:{context:e.context,message:`No MCP sessions available, providers not registered`},level:`warn`})}async stop(){this.server&&await this.server.stop()}};L.config(),process.env.TASK_MASTER_MCP=`true`;async function cr(){let e=new sr;process.on(`SIGINT`,async()=>{await e.stop(),process.exit(0)}),process.on(`SIGTERM`,async()=>{await e.stop(),process.exit(0)});try{await e.start()}catch(e){V.error(`Failed to start MCP server: ${e.message}`),process.exit(1)}}cr();export{};
44
+ ${y.result}`;if(e){let{updateSubtaskById:e}=await import(`./update-subtask-by-id-BefMzxs3.js`);await e(P.join(d,`.taskmaster`,`tasks`,`tasks.json`),l,n,!1,{session:p,mcpLog:m,commandName:`research-save`,outputType:`mcp`,projectRoot:d,tag:f},`json`),t.info(`Research saved to subtask ${l}`)}else{let e=(await import(`./update-task-by-id-Ew-wfGRR.js`)).default,r=parseInt(l,10);await e(P.join(d,`.taskmaster`,`tasks`,`tasks.json`),r,n,!1,{session:p,mcpLog:m,commandName:`research-save`,outputType:`mcp`,projectRoot:d,tag:f},`json`,!0),t.info(`Research saved to task ${l}`)}}catch(e){t.warn(`Error saving research to task/subtask: ${e.message}`)}return v(),{success:!0,data:{query:y.query,result:y.result,contextSize:y.contextSize,contextTokens:y.contextTokens,tokenBreakdown:y.tokenBreakdown,systemPromptTokens:y.systemPromptTokens,userPromptTokens:y.userPromptTokens,totalInputTokens:y.totalInputTokens,detailLevel:y.detailLevel,telemetryData:y.telemetryData,tagInfo:y.tagInfo,savedFilePath:y.savedFilePath}}}catch(e){return v(),t.error(`Error in researchDirect: ${e.message}`),{success:!1,error:{code:e.code||`RESEARCH_ERROR`,message:e.message}}}}async function mn(e,t,n={}){let{tasksJsonPath:r,id:i,strength:a=`regular`,prompt:o,research:s=!1,projectRoot:c,tag:l}=e,{session:u}=n;x();let d=D(t);try{if(!r)return t.error(`scopeDownDirect called without tasksJsonPath`),v(),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`tasksJsonPath is required`}};if(!i)return t.error(`Missing required parameter: id`),v(),{success:!1,error:{code:`MISSING_PARAMETER`,message:`The id parameter is required for scoping down tasks`}};let e=i.split(`,`).map(e=>parseInt(e.trim(),10));t.info(`Scoping down tasks: ${e.join(`, `)}, strength: ${a}, research: ${s}`);let n=await oe(r,e,a,o,{session:u,mcpLog:d,projectRoot:c,commandName:`scope-down`,outputType:`mcp`,tag:l,research:s},`json`);return v(),{success:!0,data:{updatedTasks:n.updatedTasks,tasksUpdated:n.updatedTasks.length,message:`Successfully scoped down ${n.updatedTasks.length} task(s)`,telemetryData:n.telemetryData}}}catch(e){return v(),t.error(`Error in scopeDownDirect: ${e.message}`),{success:!1,error:{code:e.code||`SCOPE_DOWN_ERROR`,message:e.message}}}}async function hn(e,t,n={}){let{tasksJsonPath:r,id:i,strength:a=`regular`,prompt:o,research:s=!1,projectRoot:c,tag:l}=e,{session:u}=n;x();let d=D(t);try{if(!r)return t.error(`scopeUpDirect called without tasksJsonPath`),v(),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`tasksJsonPath is required`}};if(!i)return t.error(`Missing required parameter: id`),v(),{success:!1,error:{code:`MISSING_PARAMETER`,message:`The id parameter is required for scoping up tasks`}};let e=i.split(`,`).map(e=>parseInt(e.trim(),10));t.info(`Scoping up tasks: ${e.join(`, `)}, strength: ${a}, research: ${s}`);let n=await ge(r,e,a,o,{session:u,mcpLog:d,projectRoot:c,commandName:`scope-up`,outputType:`mcp`,tag:l,research:s},`json`);return v(),{success:!0,data:{updatedTasks:n.updatedTasks,tasksUpdated:n.updatedTasks.length,message:`Successfully scoped up ${n.updatedTasks.length} task(s)`,telemetryData:n.telemetryData}}}catch(e){return v(),t.error(`Error in scopeUpDirect: ${e.message}`),{success:!1,error:{code:e.code||`SCOPE_UP_ERROR`,message:e.message}}}}async function gn(e,t,n={}){let{session:r}=n,{tasksJsonPath:i,id:a,prompt:o,research:s,metadata:c,projectRoot:l,tag:u}=e,d=D(t);try{if(d.info(`Updating subtask by ID via direct function. ID: ${a}, ProjectRoot: ${l}`),!i){let e=`tasksJsonPath is required but was not provided.`;return d.error(e),{success:!1,error:{code:`MISSING_ARGUMENT`,message:e}}}if(!a||typeof a!=`string`||!a.trim()){let e=`Subtask ID cannot be empty.`;return d.error(e),{success:!1,error:{code:`INVALID_SUBTASK_ID`,message:e}}}if(!o&&!c){let e=`No prompt or metadata specified. Please provide information to append or metadata to update.`;return d.error(e),{success:!1,error:{code:`MISSING_PROMPT`,message:e}}}let e=String(a).trim(),n=i,f=s===!0;t.info(`Updating subtask with ID ${e} with prompt "${o||`(metadata-only)`}" and research: ${f}`);let p=w();p||x();try{let t=await He(n,e,o,f,{mcpLog:d,session:r,projectRoot:l,tag:u,commandName:`update-subtask`,outputType:`mcp`,metadata:c},`json`);if(!t||t.updatedSubtask===null){let e=`Subtask ${a} or its parent task not found.`;return d.error(e),{success:!1,error:{code:`SUBTASK_NOT_FOUND`,message:e}}}let i=e.split(`.`)[0],s=`Successfully updated subtask with ID ${e}`;return d.success(s),{success:!0,data:{message:`Successfully updated subtask with ID ${e}`,subtaskId:e,parentId:i,subtask:t.updatedSubtask,tasksPath:n,useResearch:f,telemetryData:t.telemetryData,tagInfo:t.tagInfo}}}catch(e){return d.error(`Error updating subtask by ID: ${e.message}`),{success:!1,error:{code:`UPDATE_SUBTASK_CORE_ERROR`,message:e.message||`Unknown error updating subtask`}}}finally{!p&&w()&&v()}}catch(e){return d.error(`Setup error in updateSubtaskByIdDirect: ${e.message}`),w()&&v(),{success:!1,error:{code:`DIRECT_FUNCTION_SETUP_ERROR`,message:e.message||`Unknown setup error`}}}}async function _n(e,t,n={}){let{session:r}=n,{tasksJsonPath:i,id:a,prompt:o,research:s,append:c,metadata:l,projectRoot:u,tag:d}=e,f=D(t);try{if(f.info(`Updating task by ID via direct function. ID: ${a}, ProjectRoot: ${u}`),!a){let e=`No task ID specified. Please provide a task ID to update.`;return f.error(e),{success:!1,error:{code:`INPUT_VALIDATION_ERROR`,message:e}}}if(!o&&!l){let e=`No prompt or metadata specified. Please provide a prompt with new information or metadata for the task update.`;return f.error(e),{success:!1,error:{code:`INPUT_VALIDATION_ERROR`,message:e}}}let t;if(typeof a==`string`)t=a;else if(typeof a==`number`)t=String(a);else{let e=`Invalid task ID type: ${typeof a}. Task ID must be a string or number.`;return f.error(e),{success:!1,error:{code:`INPUT_VALIDATION_ERROR`,message:e}}}let n=i||E({projectRoot:u,file:e.file},f);if(!n){let e=`tasks.json path could not be resolved.`;return f.error(e),{success:!1,error:{code:`INPUT_VALIDATION_ERROR`,message:e}}}let p=s===!0;f.info(`Updating task with ID ${t} with prompt "${o||`(metadata-only)`}" and research: ${p}`);let m=w();m||x();try{let e=await ae(n,t,o,p,{mcpLog:f,session:r,projectRoot:u,tag:d,commandName:`update-task`,outputType:`mcp`,metadata:l},`json`,c||!1);if(!e||e.updatedTask===null){let n=`Task ${t} was not updated (likely already completed).`;return f.info(n),{success:!0,data:{message:n,taskId:t,updated:!1,telemetryData:e?.telemetryData,tagInfo:e?.tagInfo}}}let i=`Successfully updated task with ID ${t} based on the prompt`;return f.info(i),{success:!0,data:{message:i,taskId:t,tasksPath:n,useResearch:p,updated:!0,updatedTask:e.updatedTask,telemetryData:e.telemetryData,tagInfo:e.tagInfo}}}catch(e){return f.error(`Error updating task by ID: ${e.message}`),{success:!1,error:{code:`UPDATE_TASK_CORE_ERROR`,message:e.message||`Unknown error updating task`}}}finally{!m&&w()&&v()}}catch(e){return f.error(`Setup error in updateTaskByIdDirect: ${e.message}`),w()&&v(),{success:!1,error:{code:`DIRECT_FUNCTION_SETUP_ERROR`,message:e.message||`Unknown setup error`}}}}async function vn(e,t,n={}){let{session:r}=n,{from:i,prompt:a,research:o,tasksJsonPath:s,projectRoot:c,tag:l}=e,u=D(t);if(!c)return u.error(`updateTasksDirect requires a projectRoot argument.`),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`projectRoot is required.`}};if(!i)return u.error(`updateTasksDirect called without from ID`),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`Starting task ID (from) is required`}};if(!a)return u.error(`updateTasksDirect called without prompt`),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`Update prompt is required`}};u.info(`Updating tasks via direct function. From: ${i}, Research: ${o}, File: ${s}, ProjectRoot: ${c}`),x();try{let e=await ye(s,i,a,o,{session:r,mcpLog:u,projectRoot:c,tag:l},`json`);return e&&e.success&&Array.isArray(e.updatedTasks)?(u.success(`Successfully updated ${e.updatedTasks.length} tasks.`),{success:!0,data:{message:`Successfully updated ${e.updatedTasks.length} tasks.`,tasksPath:s,updatedCount:e.updatedTasks.length,telemetryData:e.telemetryData,tagInfo:e.tagInfo}}):(u.error(`Core updateTasks function did not return a successful structure.`),{success:!1,error:{code:`CORE_FUNCTION_ERROR`,message:e?.message||`Core function failed to update tasks or returned unexpected result.`}})}catch(e){return u.error(`Error executing core updateTasks: ${e.message}`),{success:!1,error:{code:`UPDATE_TASKS_CORE_ERROR`,message:e.message||`Unknown error updating tasks`}}}finally{v()}}async function yn(e,t,n={}){let{tasksJsonPath:r,name:i,projectRoot:a}=e,{session:o}=n;x();let s=D(t);try{if(!r)return t.error(`useTagDirect called without tasksJsonPath`),v(),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`tasksJsonPath is required`}};if(!i||typeof i!=`string`)return t.error(`Missing required parameter: name`),v(),{success:!1,error:{code:`MISSING_PARAMETER`,message:`Tag name is required and must be a string`}};t.info(`Switching to tag: ${i}`);let e=await Ae(r,i,{},{session:o,mcpLog:s,projectRoot:a},`json`);return v(),{success:!0,data:{tagName:e.currentTag,switched:e.switched,previousTag:e.previousTag,taskCount:e.taskCount,message:`Successfully switched to tag "${e.currentTag}"`}}}catch(e){return v(),t.error(`Error in useTagDirect: ${e.message}`),{success:!1,error:{code:e.code||`USE_TAG_ERROR`,message:e.message}}}}async function bn(e,t){let{tasksJsonPath:n,projectRoot:r,tag:i}=e;if(!n)return t.error(`validateDependenciesDirect called without tasksJsonPath`),{success:!1,error:{code:`MISSING_ARGUMENT`,message:`tasksJsonPath is required`}};try{t.info(`Validating dependencies in tasks: ${n}`);let e=n;return N.existsSync(e)?(x(),await je(e,{projectRoot:r,tag:i}),v(),{success:!0,data:{message:`Dependencies validated successfully`,tasksPath:e}}):{success:!1,error:{code:`FILE_NOT_FOUND`,message:`Tasks file not found at ${e}`}}}catch(e){return v(),t.error(`Error validating dependencies: ${e.message}`),{success:!1,error:{code:`VALIDATION_ERROR`,message:e.message}}}}function xn(e){e.addTool({name:`add_dependency`,description:`Add a dependency relationship between two tasks`,parameters:I.object({id:I.string().describe(`ID of task that will depend on another task`),dependsOn:I.string().describe(`ID of task that will become a dependency`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Add Dependency`,destructiveHint:!0},execute:Q(`add-dependency`,async(e,{log:t,session:n})=>{try{t.info(`Adding dependency for task ${e.id} to depend on ${e.dependsOn}`);let n=r({projectRoot:e.projectRoot,tag:e.tag}),i;try{i=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await zt({tasksJsonPath:i,id:e.id,dependsOn:e.dependsOn,projectRoot:e.projectRoot,tag:n},t);return a.success?t.info(`Successfully added dependency: ${a.data.message}`):t.error(`Failed to add dependency: ${a.error.message}`),Y({result:a,log:t,errorPrefix:`Error adding dependency`,projectRoot:e.projectRoot,tag:n})}catch(e){return t.error(`Error in addDependency tool: ${e.message}`),J(e.message)}})})}function Sn(e){e.addTool({name:`add_subtask`,description:`Add a subtask to an existing task`,parameters:I.object({id:I.string().describe(`Parent task ID (required)`),taskId:I.string().optional().describe(`Existing task ID to convert to subtask`),title:I.string().optional().describe(`Title for the new subtask (when creating a new subtask)`),description:I.string().optional().describe(`Description for the new subtask`),details:I.string().optional().describe(`Implementation details for the new subtask`),status:I.string().optional().describe(`Status for the new subtask (default: 'pending')`),dependencies:I.string().optional().describe(`Comma-separated list of dependency IDs for the new subtask`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),skipGenerate:I.boolean().optional().describe(`Skip regenerating task files`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Add Subtask`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{let i=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Adding subtask with args: ${JSON.stringify(e)}`);let a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o=await Bt({tasksJsonPath:a,id:e.id,taskId:e.taskId,title:e.title,description:e.description,details:e.details,status:e.status,dependencies:e.dependencies,skipGenerate:e.skipGenerate,projectRoot:e.projectRoot,tag:i},t,{session:n});return o.success?t.info(`Subtask added successfully: ${o.data.message}`):t.error(`Failed to add subtask: ${o.error.message}`),Y({result:o,log:t,errorPrefix:`Error adding subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in addSubtask tool: ${e.message}`),J(e.message)}})})}function Cn(e){e.addTool({name:`add_tag`,description:`Create a new tag for organizing tasks in different contexts`,parameters:I.object({name:I.string().describe(`Name of the new tag to create`),copyFromCurrent:I.boolean().optional().describe(`Whether to copy tasks from the current tag (default: false)`),copyFromTag:I.string().optional().describe(`Specific tag to copy tasks from`),fromBranch:I.boolean().optional().describe(`Create tag name from current git branch (ignores name parameter)`),description:I.string().optional().describe(`Optional description for the tag`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Add Tag`,destructiveHint:!1},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting add-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await Vt({tasksJsonPath:r,name:e.name,copyFromCurrent:e.copyFromCurrent,copyFromTag:e.copyFromTag,fromBranch:e.fromBranch,description:e.description,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error creating tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in add-tag tool: ${e.message}`),J(e.message)}})})}function wn(e){e.addTool({name:`add_task`,description:`Add a new task using AI`,parameters:I.object({prompt:I.string().optional().describe(`Description of the task to add (required if not using manual fields)`),title:I.string().optional().describe(`Task title (for manual task creation)`),description:I.string().optional().describe(`Task description (for manual task creation)`),details:I.string().optional().describe(`Implementation details (for manual task creation)`),testStrategy:I.string().optional().describe(`Test strategy (for manual task creation)`),dependencies:I.string().optional().describe(`Comma-separated list of task IDs this task depends on`),priority:I.string().optional().describe(`Task priority (high, medium, low)`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`),research:I.boolean().optional().describe(`Whether to use research capabilities for task creation`)}),annotations:{title:`Add Task`,destructiveHint:!1},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting add-task with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await Ht({tasksJsonPath:a,prompt:e.prompt,title:e.title,description:e.description,details:e.details,testStrategy:e.testStrategy,dependencies:e.dependencies,priority:e.priority,research:e.research,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error adding task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in add-task tool: ${e.message}`),J(e.message)}})})}function Tn(e){e.addTool({name:`analyze_project_complexity`,description:`Analyze task complexity and generate expansion recommendations.`,parameters:I.object({threshold:I.coerce.number().int().min(1).max(10).optional().default(5).describe(`Complexity score threshold (1-10) to recommend expansion.`),research:I.boolean().optional().default(!1).describe(`Use Perplexity AI for research-backed analysis.`),output:I.string().optional().describe(`Output file path relative to project root (default: ${s}).`),file:I.string().optional().describe(`Path to the tasks file relative to project root (default: tasks/tasks.json).`),ids:I.string().optional().describe(`Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").`),from:I.coerce.number().int().positive().optional().describe(`Starting task ID in a range to analyze.`),to:I.coerce.number().int().positive().optional().describe(`Ending task ID in a range to analyze.`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Analyze Project Complexity`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{let i=`analyze_project_complexity`;try{t.info(`Executing ${i} tool with args: ${JSON.stringify(e)}`);let a=r({projectRoot:e.projectRoot,tag:e.tag}),o;try{o=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`${i}: Resolved tasks path: ${o}`)}catch(n){return t.error(`${i}: Error finding tasks.json: ${n.message}`),J(`Failed to find tasks.json within project root '${e.projectRoot}': ${n.message}`)}let s=C(e.output,{projectRoot:e.projectRoot,tag:a},t);t.info(`${i}: Report output path: ${s}`);let c=P.dirname(s);try{N.existsSync(c)||(N.mkdirSync(c,{recursive:!0}),t.info(`${i}: Created output directory: ${c}`))}catch(e){return t.error(`${i}: Failed to create output directory ${c}: ${e.message}`),J(`Failed to create output directory: ${e.message}`)}let l=await Ut({tasksJsonPath:o,outputPath:s,threshold:e.threshold,research:e.research,projectRoot:e.projectRoot,tag:a,ids:e.ids,from:e.from,to:e.to},t,{session:n});return t.info(`${i}: Direct function result: success=${l.success}`),Y({result:l,log:t,errorPrefix:`Error analyzing task complexity`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${i} tool execute: ${e.message}`),J(`Internal tool error (${i}): ${e.message}`)}})})}function En(e){e.addTool({name:`clear_subtasks`,description:`Clear subtasks from specified tasks`,parameters:I.object({id:I.string().optional().describe(`Task IDs (comma-separated) to clear subtasks from`),all:I.boolean().optional().describe(`Clear subtasks from all tasks`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}).refine(e=>e.id||e.all,{message:`Either 'id' or 'all' parameter must be provided`,path:[`id`,`all`]}),annotations:{title:`Clear Subtasks`,destructiveHint:!0},execute:Q(`clear-subtasks`,async(e,t)=>{try{t.log.info(`Clearing subtasks with args: ${JSON.stringify(e)}`);let n=r({projectRoot:e.projectRoot,tag:e.tag}),i;try{i=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await Wt({tasksJsonPath:i,id:e.id,all:e.all,projectRoot:e.projectRoot,tag:n},t.log,{session:t.session});return a.success?t.log.info(`Subtasks cleared successfully: ${a.data.message}`):t.log.error(`Failed to clear subtasks: ${a.error.message}`),Y({result:a,log:t.log,errorPrefix:`Error clearing subtasks`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in clearSubtasks tool: ${e.message}`),J(e.message)}})})}function Dn(e){e.addTool({name:`complexity_report`,description:`Display the complexity analysis report in a readable format`,parameters:I.object({file:I.string().optional().describe(`Path to the report file (default: ${s})`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Complexity Report`,readOnlyHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Getting complexity report with args: ${JSON.stringify(e)}`);let n=h(e.projectRoot),r=Ue({projectRoot:e.projectRoot,complexityReport:e.file,tag:n},t);if(t.info(`Reading complexity report from path: `,r),!r)return J(`No complexity report found. Run task-master analyze-complexity first.`);let i=await Gt({reportPath:r},t);return i.success?t.info(`Successfully retrieved complexity report`):t.error(`Failed to retrieve complexity report: ${i.error.message}`),Y({result:i,log:t,errorPrefix:`Error retrieving complexity report`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in complexity-report tool: ${e.message}`),J(`Failed to retrieve complexity report: ${e.message}`)}})})}function On(e){e.addTool({name:`copy_tag`,description:`Copy an existing tag to create a new tag with all tasks and metadata`,parameters:I.object({sourceName:I.string().describe(`Name of the source tag to copy from`),targetName:I.string().describe(`Name of the new tag to create`),description:I.string().optional().describe(`Optional description for the new tag`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Copy Tag`,destructiveHint:!1},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting copy-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await Kt({tasksJsonPath:r,sourceName:e.sourceName,targetName:e.targetName,description:e.description,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error copying tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in copy-tag tool: ${e.message}`),J(e.message)}})})}function kn(e){e.addTool({name:`delete_tag`,description:`Delete an existing tag and all its tasks`,parameters:I.object({name:I.string().describe(`Name of the tag to delete`),yes:I.boolean().optional().describe(`Skip confirmation prompts (default: true for MCP)`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Delete Tag`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting delete-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await qt({tasksJsonPath:r,name:e.name,yes:e.yes===void 0?!0:e.yes,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error deleting tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in delete-tag tool: ${e.message}`),J(e.message)}})})}function An(e){e.addTool({name:`expand_all`,description:`Expand all pending tasks into subtasks based on complexity or defaults`,parameters:I.object({num:I.string().optional().describe(`Target number of subtasks per task (uses complexity/defaults otherwise)`),research:I.boolean().optional().describe(`Enable research-backed subtask generation (e.g., using Perplexity)`),prompt:I.string().optional().describe(`Additional context to guide subtask generation for all tasks`),force:I.boolean().optional().describe(`Force regeneration of subtasks for tasks that already have them`),file:I.string().optional().describe(`Absolute path to the tasks file in the /tasks folder inside the project root (default: tasks/tasks.json)`),projectRoot:I.string().optional().describe(`Absolute path to the project root directory (derived from session if possible)`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Expand All Tasks`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Tool expand_all execution started with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`Resolved tasks.json path: ${a}`)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o=xe(null,{projectRoot:e.projectRoot,tag:i},t);return t.info(`Using complexity report path: ${o}`),Y({result:await Jt({tasksJsonPath:a,num:e.num,research:e.research,prompt:e.prompt,force:e.force,projectRoot:e.projectRoot,tag:i,complexityReportPath:o},t,{session:n}),log:t,errorPrefix:`Error expanding all tasks`,projectRoot:e.projectRoot})}catch(e){return t.error(`Unexpected error in expand_all tool execute: ${e.message}`),e.stack&&t.error(e.stack),J(`An unexpected error occurred: ${e.message}`)}})})}function jn(e){e.addTool({name:`expand_task`,description:`Expand a task into subtasks for detailed implementation`,parameters:I.object({id:I.string().describe(`ID of task to expand`),num:I.string().optional().describe(`Number of subtasks to generate`),research:I.boolean().optional().default(!1).describe(`Use research role for generation`),prompt:I.string().optional().describe(`Additional context for subtask generation`),file:I.string().optional().describe(`Path to the tasks file relative to project root (e.g., tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),force:I.boolean().optional().default(!1).describe(`Force expansion even if subtasks exist`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Expand Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting expand-task with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o=Ue({...e,tag:i},t);return Y({result:await Yt({tasksJsonPath:a,id:e.id,num:e.num,research:e.research,prompt:e.prompt,force:e.force,complexityReportPath:o,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error expanding task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in expand-task tool: ${e.message}`),J(e.message)}})})}function Mn(e){e.addTool({name:`fix_dependencies`,description:`Fix invalid dependencies in tasks automatically`,parameters:I.object({file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Fix Dependencies`,destructiveHint:!0},execute:Q(`fix-dependencies`,async(e,t)=>{try{t.log.info(`Fixing dependencies with args: ${JSON.stringify(e)}`);let n=r({projectRoot:e.projectRoot,tag:e.tag}),i;try{i=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await Xt({tasksJsonPath:i,projectRoot:e.projectRoot,tag:n},t.log);return a.success?t.log.info(`Successfully fixed dependencies: ${a.data.message}`):t.log.error(`Failed to fix dependencies: ${a.error.message}`),Y({result:a,log:t.log,errorPrefix:`Error fixing dependencies`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in fixDependencies tool: ${e.message}`),J(e.message)}})})}function Nn(e){e.addTool({name:`initialize_project`,description:`Initializes a new Task Master project structure by calling the core initialization logic. Creates necessary folders and configuration files for Task Master in the current directory. If you are using Codex CLI, set withCodex=true (and keep yes=true) so Codex longrun assets are created in the same step.`,parameters:I.object({skipInstall:I.boolean().optional().default(!1).describe(`Skip installing dependencies automatically. Never do this unless you are sure the project is already installed.`),addAliases:I.boolean().optional().default(!0).describe(`Add shell aliases (tm, taskmaster, hamster, ham) to shell config file.`),initGit:I.boolean().optional().default(!0).describe(`Initialize Git repository in project root.`),storeTasksInGit:I.boolean().optional().default(!0).describe(`Store tasks in Git (tasks.json and tasks/ directory).`),yes:I.boolean().optional().default(!0).describe(`Skip prompts and use default values. Always set to true for MCP tools.`),withCodex:I.boolean().optional().default(!1).describe(`Initialize Codex longrun assets together with project init. For Codex CLI workflows, set this to true.`),projectRoot:I.string().describe(`The root directory for the project. ALWAYS SET THIS TO THE PROJECT ROOT DIRECTORY. IF NOT SET, THE TOOL WILL NOT WORK.`),rules:I.array(I.enum(A)).optional().describe(`List of rule profiles to include at initialization. If omitted, defaults to Cursor profile only. Available options: ${A.join(`, `)}`)}),annotations:{title:`Initialize Project`,destructiveHint:!0},execute:Z(async(e,t)=>{let{log:n}=t,r=t.session;try{return n.info(`Executing initialize_project tool with args: ${JSON.stringify(e)}`),Y({result:await Zt(e,n,{session:r}),log:n,errorPrefix:`Initialization failed`,projectRoot:e.projectRoot})}catch(e){let t=`Project initialization tool failed: ${e.message||`Unknown error`}`;return n.error(t,e),J(t,{details:e.stack})}})})}function Pn(e){e.addTool({name:`list_tags`,description:`List all available tags with task counts and metadata`,parameters:I.object({showMetadata:I.boolean().optional().describe(`Whether to include metadata in the output (default: false)`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`List Tags`,readOnlyHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting list-tags with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await Qt({tasksJsonPath:r,showMetadata:e.showMetadata,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error listing tags`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in list-tags tool: ${e.message}`),J(e.message)}})})}function Fn(e){e.addTool({name:`models`,description:`Get information about available AI models or set model configurations. Run without arguments to get the current model configuration and API key status for the selected model providers.`,parameters:I.object({setMain:I.string().optional().describe(`Set the primary model for task generation/updates. Model provider API key is required in the MCP config ENV.`),setResearch:I.string().optional().describe(`Set the model for research-backed operations. Model provider API key is required in the MCP config ENV.`),setFallback:I.string().optional().describe(`Set the model to use if the primary fails. Model provider API key is required in the MCP config ENV.`),listAvailableModels:I.boolean().optional().describe(`List all available models not currently in use. Input/output costs values are in dollars (3 is $3.00).`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),openrouter:I.boolean().optional().describe(`Indicates the set model ID is a custom OpenRouter model.`),ollama:I.boolean().optional().describe(`Indicates the set model ID is a custom Ollama model.`),bedrock:I.boolean().optional().describe(`Indicates the set model ID is a custom AWS Bedrock model.`),azure:I.boolean().optional().describe(`Indicates the set model ID is a custom Azure OpenAI model.`),vertex:I.boolean().optional().describe(`Indicates the set model ID is a custom Google Vertex AI model.`),"openai-compatible":I.boolean().optional().describe(`Indicates the set model ID is a custom OpenAI-compatible model. Requires baseURL parameter.`),baseURL:I.string().optional().describe(`Custom base URL for providers that support it (e.g., https://api.example.com/v1).`)}),annotations:{title:`Models`,destructiveHint:!0},execute:Q(`models`,async(e,t)=>{try{return t.log.info(`Starting models tool with args: ${JSON.stringify(e)}`),Y({result:await nn({...e,projectRoot:e.projectRoot},t.log,{session:t.session}),log:t.log,errorPrefix:`Error managing models`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in models tool: ${e.message}`),J(e.message)}})})}function In(e){e.addTool({name:`move_task`,description:`Move a task or subtask to a new position`,parameters:I.object({from:I.string().describe(`ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")`),to:I.string().optional().describe(`ID of the destination (e.g., "7" or "7.3"). Required for within-tag moves. For cross-tag moves, if omitted, task will be moved to the target tag maintaining its ID`),file:I.string().optional().describe(`Custom path to tasks.json file`),projectRoot:I.string().describe(`Root directory of the project (typically derived from session)`),tag:I.string().optional().describe(`Tag context to operate on`),fromTag:I.string().optional().describe(`Source tag for cross-tag moves`),toTag:I.string().optional().describe(`Target tag for cross-tag moves`),withDependencies:I.boolean().optional().describe(`Move dependent tasks along with main task`),ignoreDependencies:I.boolean().optional().describe(`Break cross-tag dependencies during move`)}),annotations:{title:`Move Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{if(e.fromTag&&e.toTag&&e.fromTag!==e.toTag){if(!e.from)return J(`Source IDs are required for cross-tag moves`,`MISSING_SOURCE_IDS`);e.to&&t.warn(`The "to" parameter is not used for cross-tag moves and will be ignored. Tasks retain their original IDs in the target tag.`);let r=e.file;return r||=E(e,t),Y({result:await rn({sourceIds:e.from,sourceTag:e.fromTag,targetTag:e.toTag,withDependencies:e.withDependencies||!1,ignoreDependencies:e.ignoreDependencies||!1,tasksJsonPath:r,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error moving tasks between tags`,projectRoot:e.projectRoot})}else{if(!e.to)return J(`Destination ID is required for within-tag moves`,`MISSING_DESTINATION_ID`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a=e.file;a||=E(e,t);let o=e.from.split(`,`).map(e=>e.trim()),s=e.to.split(`,`).map(e=>e.trim());if(o.length!==s.length){if(o.length>1){let r=[],c=[];for(let l=0;l<o.length;l++){let u=o[l],d=s[l];if(u===d){t.info(`Skipping ${u} -> ${d} (same ID)`),c.push({fromId:u,toId:d,reason:`same ID`});continue}let f=l===o.length-1,p=await an({sourceId:u,destinationId:d,tasksJsonPath:a,projectRoot:e.projectRoot,tag:i,generateFiles:f},t,{session:n});p.success?r.push(p.data):t.error(`Failed to move ${u} to ${d}: ${p.error.message}`)}return Y({result:{success:!0,data:{moves:r,skipped:c.length>0?c:void 0,message:`Successfully moved ${r.length} tasks${c.length>0?`, skipped ${c.length}`:``}`}},log:t,errorPrefix:`Error moving multiple tasks`,projectRoot:e.projectRoot})}return Y({result:{success:!0,data:{moves:results,skippedMoves,message:`Successfully moved ${results.length} tasks${skippedMoves.length>0?`, skipped ${skippedMoves.length} moves`:``}`}},log:t,errorPrefix:`Error moving multiple tasks`,projectRoot:e.projectRoot})}else return Y({result:await an({sourceId:e.from,destinationId:e.to,tasksJsonPath:a,projectRoot:e.projectRoot,tag:i,generateFiles:!0},t,{session:n}),log:t,errorPrefix:`Error moving task`,projectRoot:e.projectRoot})}}catch(e){return J(`Failed to move task: ${e.message}`,`MOVE_TASK_ERROR`)}})})}function Ln(e){e.addTool({name:`next_task`,description:`Find the next task to work on based on dependencies and status`,parameters:I.object({file:I.string().optional().describe(`Absolute path to the tasks file`),complexityReport:I.string().optional().describe(`Path to the complexity report file (relative to project root or absolute)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Next Task`,readOnlyHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Finding next task with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=ue(e,n)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o;try{o=de({...e,tag:i},n)}catch(e){t.error(`Error finding complexity report: ${e.message}`),o=null}let s=await on({tasksJsonPath:a,reportPath:o,projectRoot:e.projectRoot,tag:i},t,{session:n});return t.info(`Next task result: ${s.success?`found`:`none`}`),Y({result:s,log:t,errorPrefix:`Error finding next task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error finding next task: ${e.message}`),J(e.message)}})})}function Rn(e){e.addTool({name:`parse_prd`,description:`Parse a Product Requirements Document (PRD) text file to automatically generate initial tasks. Reinitializing the project is not necessary to run this tool. It is recommended to run parse-prd after initializing the project and creating/importing a prd.txt file in the project root's ${i} directory.`,parameters:I.object({input:I.string().optional().default(ne).describe(`Absolute path to the PRD document file (.txt, .md, etc.)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`),destination:I.enum([`local`,`hamster`]).optional().default(`local`).describe(`Where to parse the PRD: "local" writes tasks.json, "hamster" creates a cloud brief and tasks`),output:I.string().optional().describe(`Output path for tasks.json file (default: ${a})`),numTasks:I.string().optional().describe(`Approximate number of top-level tasks to generate (default: 10). As the agent, if you have enough information, ensure to enter a number of tasks that would logically scale with project complexity. Setting to 0 will allow Taskmaster to determine the appropriate number of tasks based on the complexity of the PRD. Avoid entering numbers above 50 due to context window limitations.`),force:I.boolean().optional().default(!1).describe(`Overwrite existing output file without prompting.`),research:I.boolean().optional().describe(`Enable Taskmaster to use the research role for potentially more informed task generation. Requires appropriate API key.`),append:I.boolean().optional().describe(`Append generated tasks to existing file.`)}),annotations:{title:`Parse PRD`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n,reportProgress:i})=>{try{let a=r({projectRoot:e.projectRoot,tag:e.tag}),o=dt(i,t);return Y({result:await sn({...e,tag:a},t,{session:n,reportProgress:o}),log:t,errorPrefix:`Error parsing PRD`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in parse_prd: ${e.message}`),J(`Failed to parse PRD: ${e.message}`)}})})}function zn(e){e.addTool({name:`remove_dependency`,description:`Remove a dependency from a task`,parameters:I.object({id:I.string().describe(`Task ID to remove dependency from`),dependsOn:I.string().describe(`Task ID to remove as a dependency`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Remove Dependency`,destructiveHint:!0},execute:Q(`remove-dependency`,async(e,t)=>{try{let n=r({projectRoot:e.projectRoot,tag:e.tag});t.log.info(`Removing dependency for task ${e.id} from ${e.dependsOn} with args: ${JSON.stringify(e)}`);let i;try{i=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await ln({tasksJsonPath:i,id:e.id,dependsOn:e.dependsOn,projectRoot:e.projectRoot,tag:n},t.log);return a.success?t.log.info(`Successfully removed dependency: ${a.data.message}`):t.log.error(`Failed to remove dependency: ${a.error.message}`),Y({result:a,log:t.log,errorPrefix:`Error removing dependency`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in removeDependency tool: ${e.message}`),J(e.message)}})})}function Bn(e){e.addTool({name:`remove_subtask`,description:`Remove a subtask from its parent task`,parameters:I.object({id:I.string().describe(`Subtask ID to remove in format 'parentId.subtaskId' (required)`),convert:I.boolean().optional().describe(`Convert the subtask to a standalone task instead of deleting it`),file:I.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),skipGenerate:I.boolean().optional().describe(`Skip regenerating task files`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Remove Subtask`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{let i=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Removing subtask with args: ${JSON.stringify(e)}`);let a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let o=await un({tasksJsonPath:a,id:e.id,convert:e.convert,skipGenerate:e.skipGenerate,projectRoot:e.projectRoot,tag:i},t,{session:n});return o.success?t.info(`Subtask removed successfully: ${o.data.message}`):t.error(`Failed to remove subtask: ${o.error.message}`),Y({result:o,log:t,errorPrefix:`Error removing subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in removeSubtask tool: ${e.message}`),J(e.message)}})})}function Vn(e){e.addTool({name:`remove_task`,description:`Remove a task or subtask permanently from the tasks list`,parameters:I.object({id:I.string().describe(`ID of the task or subtask to remove (e.g., '5' or '5.2'). Can be comma-separated to update multiple tasks/subtasks at once.`),file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),confirm:I.boolean().optional().describe(`Whether to skip confirmation prompt (default: false)`),tag:I.string().optional().describe(`Specify which tag context to operate on. Defaults to the current active tag.`)}),annotations:{title:`Remove Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Removing task(s) with ID(s): ${e.id}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}t.info(`Using tasks file path: ${a}`);let o=await dn({tasksJsonPath:a,id:e.id,projectRoot:e.projectRoot,tag:i},t,{session:n});return o.success?t.info(`Successfully removed task: ${e.id}`):t.error(`Failed to remove task: ${o.error.message}`),Y({result:o,log:t,errorPrefix:`Error removing task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in remove-task tool: ${e.message}`),J(`Failed to remove task: ${e.message}`)}})})}function Hn(e){e.addTool({name:`rename_tag`,description:`Rename an existing tag`,parameters:I.object({oldName:I.string().describe(`Current name of the tag to rename`),newName:I.string().describe(`New name for the tag`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Rename Tag`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting rename-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await fn({tasksJsonPath:r,oldName:e.oldName,newName:e.newName,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error renaming tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in rename-tag tool: ${e.message}`),J(e.message)}})})}function Un(e){e.addTool({name:`research`,description:`Perform AI-powered research queries with project context`,parameters:I.object({query:I.string().describe(`Research query/prompt (required)`),taskIds:I.string().optional().describe(`Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17")`),filePaths:I.string().optional().describe(`Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md")`),customContext:I.string().optional().describe(`Additional custom context text to include in the research`),includeProjectTree:I.boolean().optional().describe(`Include project file tree structure in context (default: false)`),detailLevel:I.enum([`low`,`medium`,`high`]).optional().describe(`Detail level for the research response (default: medium)`),saveTo:I.string().optional().describe(`Automatically save research results to specified task/subtask ID (e.g., "15" or "15.2")`),saveToFile:I.boolean().optional().describe(`Save research results to .taskmaster/docs/research/ directory (default: false)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Research`,destructiveHint:!0,openWorldHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{let i=r({projectRoot:e.projectRoot,tag:e.tag});return t.info(`Starting research with query: "${e.query.substring(0,100)}${e.query.length>100?`...`:``}"`),Y({result:await pn({query:e.query,taskIds:e.taskIds,filePaths:e.filePaths,customContext:e.customContext,includeProjectTree:e.includeProjectTree||!1,detailLevel:e.detailLevel||`medium`,saveTo:e.saveTo,saveToFile:e.saveToFile||!1,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error performing research`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in research tool: ${e.message}`),J(e.message)}})})}async function Wn(e,t,n={}){let{projectRoot:r,language:i}=e,a=D(t);t.info(`Executing response-language_direct with args: ${JSON.stringify(e)}`),t.info(`Using project root: ${r}`);try{return x(),We(i,{mcpLog:a,projectRoot:r})}catch(e){return{success:!1,error:{code:`DIRECT_FUNCTION_ERROR`,message:e.message,details:e.stack}}}finally{v()}}function Gn(e){e.addTool({name:`response-language`,description:`Get or set the response language for the project`,parameters:I.object({projectRoot:I.string().describe(`The root directory for the project. ALWAYS SET THIS TO THE PROJECT ROOT DIRECTORY. IF NOT SET, THE TOOL WILL NOT WORK.`),language:I.string().describe(`The new response language to set. like "中文" "English" or "español".`)}),annotations:{title:`Response Language`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{return t.info(`Executing response-language tool with args: ${JSON.stringify(e)}`),Y({result:await Wn({...e,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error setting response language`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in response-language tool: ${e.message}`),J(e.message)}})})}async function Kn(e,t,n={}){x();try{let{action:t,profiles:n,projectRoot:r,yes:i,force:a}=e;if(!t||!Array.isArray(n)||n.length===0||!r)return{success:!1,error:{code:`MISSING_ARGUMENT`,message:`action, profiles, and projectRoot are required.`}};let o=[],s=[];if(t===O.REMOVE){if(!a&&Ke(r,n)){let e=Ge(r);return e.filter(e=>!n.includes(e)),{success:!1,error:{code:`CRITICAL_REMOVAL_BLOCKED`,message:`CRITICAL: This operation would remove ALL remaining rule profiles (${n.join(`, `)}), leaving your project with no rules configurations. This could significantly impact functionality. Currently installed profiles: ${e.join(`, `)}. If you're certain you want to proceed, set force: true or use the CLI with --force flag.`}}}for(let e of n){if(!Ye(e)){o.push({profileName:e,success:!1,error:`The requested rule profile for '${e}' is unavailable. Supported profiles are: ${A.join(`, `)}.`});continue}let t=Je(r,k(e));o.push(t)}let e=o.filter(e=>e.success).map(e=>e.profileName),t=o.filter(e=>e.skipped).map(e=>e.profileName),i=o.filter(e=>e.error&&!e.success&&!e.skipped),s=o.filter(e=>e.notice),c=``;return e.length>0&&(c+=`Successfully removed Task Master rules: ${e.join(`, `)}.`),t.length>0&&(c+=`Skipped (default or protected): ${t.join(`, `)}.`),i.length>0&&(c+=i.map(e=>`Error removing ${e.profileName}: ${e.error}`).join(` `)),s.length>0&&(c+=` Notices: ${s.map(e=>`${e.profileName} - ${e.notice}`).join(`; `)}.`),v(),{success:i.length===0,data:{summary:c,results:o}}}else if(t===O.ADD){for(let e of n){if(!Ye(e)){s.push({profileName:e,success:!1,error:`Profile not found: static import missing for '${e}'. Valid profiles: ${A.join(`, `)}`});continue}let t=k(e),{success:n,failed:i}=Xe(r,t),a=t.rulesDir,o=P.join(r,a),c=t.profileDir,l=t.mcpConfig!==!1,u=l&&t.mcpConfigPath?P.join(r,t.mcpConfigPath):null,d=l&&u?N.existsSync(u):void 0,f=N.existsSync(o),p=N.existsSync(P.join(r,c)),m=i>0?`${i} rule files failed to convert.`:null,h={profileName:e,mcpConfigCreated:d,rulesDirCreated:f,profileFolderCreated:p,skipped:!1,error:m,success:(l?d:!0)&&f&&n>0&&!m};s.push(h)}let e=s.filter(e=>e.success).map(e=>e.profileName),t=s.filter(e=>e.error&&!e.success),i=``;return e.length>0&&(i+=`Successfully added rules: ${e.join(`, `)}.`),t.length>0&&(i+=t.map(e=>` Error adding ${e.profileName}: ${e.error}`).join(` `)),v(),{success:t.length===0,data:{summary:i,results:s}}}else return v(),{success:!1,error:{code:`INVALID_ACTION`,message:`Unknown action. Use "${O.ADD}" or "${O.REMOVE}".`}}}catch(e){return v(),t.error(`[rulesDirect] Error: ${e.message}`),{success:!1,error:{code:e.code||`RULES_ERROR`,message:e.message}}}}function qn(e){e.addTool({name:`rules`,description:`Add or remove rule profiles from the project.`,parameters:I.object({action:I.enum([`add`,`remove`]).describe(`Whether to add or remove rule profiles.`),profiles:I.array(I.enum(A)).min(1).describe(`List of rule profiles to add or remove (e.g., [\"cursor\", \"roo\"]). Available options: ${A.join(`, `)}`),projectRoot:I.string().describe(`The root directory of the project. Must be an absolute path.`),force:I.boolean().optional().default(!1).describe(`DANGEROUS: Force removal even if it would leave no rule profiles. Only use if you are absolutely certain.`)}),annotations:{title:`Rules`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{return t.info(`[rules tool] Executing action: ${e.action} for profiles: ${e.profiles.join(`, `)} in ${e.projectRoot}`),Y({result:await Kn(e,t,{session:n}),log:t,projectRoot:e.projectRoot})}catch(e){return t.error(`[rules tool] Error: ${e.message}`),J(e.message,{details:e.stack})}})})}function Jn(e){e.addTool({name:`scope_down_task`,description:`Decrease the complexity of one or more tasks using AI`,parameters:I.object({id:I.string().describe(`Comma-separated list of task IDs to scope down (e.g., "1,3,5")`),strength:I.string().optional().describe(`Strength level: light, regular, or heavy (default: regular)`),prompt:I.string().optional().describe(`Custom prompt for specific scoping adjustments`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`),research:I.boolean().optional().describe(`Whether to use research capabilities for scoping`)}),annotations:{title:`Scope Down Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting scope-down with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await mn({tasksJsonPath:a,id:e.id,strength:e.strength,prompt:e.prompt,research:e.research,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error scoping down task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in scope-down tool: ${e.message}`),J(e.message)}})})}function Yn(e){e.addTool({name:`scope_up_task`,description:`Increase the complexity of one or more tasks using AI`,parameters:I.object({id:I.string().describe(`Comma-separated list of task IDs to scope up (e.g., "1,3,5")`),strength:I.string().optional().describe(`Strength level: light, regular, or heavy (default: regular)`),prompt:I.string().optional().describe(`Custom prompt for specific scoping adjustments`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`),research:I.boolean().optional().describe(`Whether to use research capabilities for scoping`)}),annotations:{title:`Scope Up Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting scope-up with args: ${JSON.stringify(e)}`);let i=r({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await hn({tasksJsonPath:a,id:e.id,strength:e.strength,prompt:e.prompt,research:e.research,projectRoot:e.projectRoot,tag:i},t,{session:n}),log:t,errorPrefix:`Error scoping up task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in scope-up tool: ${e.message}`),J(e.message)}})})}function Xn(e){e.addTool({name:`update_subtask`,description:`Appends timestamped information to a specific subtask without replacing existing content. If you just want to update the subtask status, use set_task_status instead.`,parameters:I.object({id:b.describe(`ID of the subtask to update in format "parentId.subtaskId" (e.g., "5.2"). Parent ID is the ID of the task that contains the subtask.`),prompt:I.string().optional().describe(`Information to add to the subtask. Required unless only updating metadata.`),research:I.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),metadata:I.string().optional().describe(`JSON string of metadata to merge into subtask metadata. Example: '{"ticketId": "JIRA-456", "reviewed": true}'. Requires TASK_MASTER_ALLOW_METADATA_UPDATES=true in MCP environment.`),file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Subtask`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{let i=`update_subtask`;try{let a=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Updating subtask with args: ${JSON.stringify(e)}`);let o;try{o=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`${i}: Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let s=mt(e.metadata,J);if(s.error)return s.error;let c=s.parsedMetadata;if(!e.prompt&&!c)return J(`Either prompt or metadata must be provided for update-subtask`);let l=await gn({tasksJsonPath:o,id:e.id,prompt:e.prompt,research:e.research,metadata:c,projectRoot:e.projectRoot,tag:a},t,{session:n});return l.success?t.info(`Successfully updated subtask with ID ${e.id}`):t.error(`Failed to update subtask: ${l.error?.message||`Unknown error`}`),Y({result:l,log:t,errorPrefix:`Error updating subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${i} tool execute: ${e.message}`),J(`Internal tool error (${i}): ${e.message}`)}})})}function Zn(e){e.addTool({name:`update_task`,description:`Updates a single task by ID with new information or context provided in the prompt.`,parameters:I.object({id:I.string().describe(`ID of the task (e.g., '15') to update. Subtasks are supported using the update-subtask tool.`),prompt:I.string().optional().describe(`New information or context to incorporate into the task. Required unless only updating metadata.`),research:I.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),append:I.boolean().optional().describe(`Append timestamped information to task details instead of full update`),metadata:I.string().optional().describe(`JSON string of metadata to merge into task metadata. Example: '{"githubIssue": 42, "sprint": "Q1-S3"}'. Requires TASK_MASTER_ALLOW_METADATA_UPDATES=true in MCP environment.`),file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Task`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{let i=`update_task`;try{let a=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Executing ${i} tool with args: ${JSON.stringify(e)}`);let o;try{o=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`${i}: Resolved tasks path: ${o}`)}catch(e){return t.error(`${i}: Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let s=mt(e.metadata,J);if(s.error)return s.error;let c=s.parsedMetadata;if(!e.prompt&&!c)return J(`Either prompt or metadata must be provided for update-task`);let l=await _n({tasksJsonPath:o,id:e.id,prompt:e.prompt,research:e.research,append:e.append,metadata:c,projectRoot:e.projectRoot,tag:a},t,{session:n});return t.info(`${i}: Direct function result: success=${l.success}`),Y({result:l,log:t,errorPrefix:`Error updating task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${i} tool execute: ${e.message}`),J(`Internal tool error (${i}): ${e.message}`)}})})}function Qn(e){e.addTool({name:`update`,description:`Update multiple upcoming tasks (with ID >= 'from' ID) based on new context or changes provided in the prompt. Use 'update_task' instead for a single specific task or 'update_subtask' for subtasks.`,parameters:I.object({from:I.string().describe(`Task ID from which to start updating (inclusive). IMPORTANT: This tool uses 'from', not 'id'`),prompt:I.string().describe(`Explanation of changes or new context to apply`),research:I.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),file:I.string().optional().describe(`Path to the tasks file relative to project root`),projectRoot:I.string().optional().describe(`The directory of the project. (Optional, usually from session)`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Tasks`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{let i=`update`,{from:a,prompt:o,research:s,file:c,projectRoot:l,tag:u}=e,d=r({projectRoot:e.projectRoot,tag:e.tag});try{t.info(`Executing ${i} tool with normalized root: ${l}`);let r;try{r=E({projectRoot:l,file:c},t),t.info(`${i}: Resolved tasks path: ${r}`)}catch(e){return t.error(`${i}: Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json within project root '${l}': ${e.message}`)}let u=await vn({tasksJsonPath:r,from:a,prompt:o,research:s,projectRoot:l,tag:d},t,{session:n});return t.info(`${i}: Direct function result: success=${u.success}`),Y({result:u,log:t,errorPrefix:`Error updating tasks`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${i} tool execute: ${e.message}`),J(`Internal tool error (${i}): ${e.message}`)}})})}function $n(e){e.addTool({name:`use_tag`,description:`Switch to a different tag context for task operations`,parameters:I.object({name:I.string().describe(`Name of the tag to switch to`),file:I.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Use Tag`,destructiveHint:!0},execute:Z(async(e,{log:t,session:n})=>{try{t.info(`Starting use-tag with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}return Y({result:await yn({tasksJsonPath:r,name:e.name,projectRoot:e.projectRoot},t,{session:n}),log:t,errorPrefix:`Error switching tag`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in use-tag tool: ${e.message}`),J(e.message)}})})}function er(e){e.addTool({name:`validate_dependencies`,description:`Check tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.`,parameters:I.object({file:I.string().optional().describe(`Absolute path to the tasks file`),projectRoot:I.string().describe(`The directory of the project. Must be an absolute path.`),tag:I.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Validate Dependencies`,readOnlyHint:!0},execute:Q(`validate-dependencies`,async(e,{log:t,session:n})=>{try{let n=r({projectRoot:e.projectRoot,tag:e.tag});t.info(`Validating dependencies with args: ${JSON.stringify(e)}`);let i;try{i=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),J(`Failed to find tasks.json: ${e.message}`)}let a=await bn({tasksJsonPath:i,projectRoot:e.projectRoot,tag:n},t);return a.success?t.info(`Successfully validated dependencies: ${a.data.message}`):t.error(`Failed to validate dependencies: ${a.error.message}`),Y({result:a,log:t,errorPrefix:`Error validating dependencies`,projectRoot:e.projectRoot,tag:n})}catch(e){return t.error(`Error in validateDependencies tool: ${e.message}`),J(e.message)}})})}const $={initialize_project:Nn,models:Fn,rules:qn,parse_prd:Rn,"response-language":Gn,analyze_project_complexity:Tn,expand_task:jn,expand_all:An,scope_up_task:Yn,scope_down_task:Jn,get_tasks:Mt,get_task:Pt,next_task:Ln,complexity_report:Dn,set_task_status:Rt,add_task:wn,add_subtask:Sn,update:Qn,update_task:Zn,update_subtask:Xn,remove_task:Vn,remove_subtask:Bn,clear_subtasks:En,move_task:In,add_dependency:xn,remove_dependency:zn,validate_dependencies:er,fix_dependencies:Mn,list_tags:Pn,add_tag:Cn,delete_tag:kn,use_tag:$n,rename_tag:Hn,copy_tag:On,research:Un,autopilot_start:gt,autopilot_resume:vt,autopilot_next:bt,autopilot_status:St,autopilot_complete:wt,autopilot_commit:Et,autopilot_finalize:Ot,autopilot_abort:At,generate:It},tr=[`get_tasks`,`next_task`,`get_task`,`set_task_status`,`update_subtask`,`parse_prd`,`expand_task`],nr=[...tr,`initialize_project`,`analyze_project_complexity`,`expand_all`,`add_subtask`,`remove_task`,`add_task`,`complexity_report`];function rr(e){return $[e]||null}function ir(){let e=process.env.TASK_MASTER_TOOLS;if(!e||e.trim()===``)return V.debug(`No TASK_MASTER_TOOLS env var found, defaulting to "core"`),`core`;let t=e.trim();return V.debug(`TASK_MASTER_TOOLS env var: "${t}"`),t}function ar(e,t=`core`){let n=[],r=[];try{let i=t.trim(),a=[],o=i.toLowerCase();switch(o){case`all`:a=Object.keys($),V.info(`Loading all available tools`);break;case`core`:case`lean`:a=tr,V.info(`Loading core tools only`);break;case`standard`:a=nr,V.info(`Loading standard tools`);break;default:let e=i.split(`,`).map(e=>e.trim()).filter(e=>e.length>0),t=new Set,n=[],r={response_language:`response-language`};for(let i of e){let e=null,a=i.toLowerCase();if(r[a]){let t=r[a];for(let n of Object.keys($))if(n.toLowerCase()===t.toLowerCase()){e=n;break}}if(!e){for(let t of Object.keys($))if(t.toLowerCase()===a){e=t;break}}if(!e){let t=a.replace(/_/g,`-`);for(let n of Object.keys($))if(n.toLowerCase()===t){e=n;break}}if(!e){let t=a.replace(/-/g,`_`);for(let n of Object.keys($))if(n.toLowerCase()===t){e=n;break}}e?(t.add(e),V.debug(`Resolved tool "${i}" to "${e}"`)):(n.push(i),V.warn(`Unknown tool specified: "${i}"`))}a=Array.from(t),n.length>0&&V.warn(`Unknown tools: ${n.join(`, `)}`),a.length===0?(V.warn(`No valid tools found in custom list. Loading all tools as fallback.`),a=Object.keys($)):V.info(`Loading ${a.length} custom tools from list (${t.size} unique after normalization)`);break}return V.info(`Registering ${a.length} MCP tools (mode: ${i})`),a.forEach(t=>{try{let i=rr(t);i?(i(e),V.debug(`Registered tool: ${t}`),n.push(t)):(V.warn(`Tool ${t} not found in registry`),r.push(t))}catch(e){e.message&&e.message.includes(`already registered`)?(V.debug(`Tool ${t} already registered, skipping`),n.push(t)):(V.error(`Failed to register tool ${t}: ${e.message}`),r.push(t))}}),V.info(`Successfully registered ${n.length}/${a.length} tools`),r.length>0&&V.warn(`Failed tools: ${r.join(`, `)}`),{registeredTools:n,failedTools:r,normalizedMode:o}}catch(t){V.error(`Error parsing TASK_MASTER_TOOLS environment variable: ${t.message}`),V.info(`Falling back to loading all tools`);let i=Object.keys($);for(let t of i){let i=rr(t);if(i)try{i(e),n.push(t)}catch(e){e.message&&e.message.includes(`already registered`)?(V.debug(`Fallback tool ${t} already registered, skipping`),n.push(t)):(V.warn(`Failed to register fallback tool '${t}': ${e.message}`),r.push(t))}else V.warn(`Tool '${t}' not found in registry`),r.push(t)}return V.info(`Successfully registered ${n.length} fallback tools`),{registeredTools:n,failedTools:r,normalizedMode:`all`}}}L.config(),re();const or=Qe(import.meta.url);P.dirname(or);var sr=class{constructor(){this.options={name:`Task Master MCP Server`,version:se};let e=new $e(this.options);if(e._mcpServer&&R.wrapMcpServerWithSentry)try{e._mcpServer=R.wrapMcpServerWithSentry(e._mcpServer)}catch(e){V.warn(`Failed to wrap MCP server with Sentry: ${e.message}`)}this.server=e,this.initialized=!1,this.init=this.init.bind(this),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this.logger=V}async init(){if(this.initialized)return;let e=ir();this.logger.info(`Task Master MCP Server starting...`),this.logger.info(`Tool mode configuration: ${e}`);let t=ar(this.server,e);return this.logger.info(`Normalized tool mode: ${t.normalizedMode}`),this.logger.info(`Registered ${t.registeredTools.length} tools successfully`),t.registeredTools.length>0&&this.logger.debug(`Registered tools: ${t.registeredTools.join(`, `)}`),t.failedTools.length>0&&this.logger.warn(`Failed to register ${t.failedTools.length} tools: ${t.failedTools.join(`, `)}`),this.initialized=!0,this}async start(){return this.initialized||await this.init(),this.server.on(`connect`,e=>{e.session.server.sendLoggingMessage({data:{context:e.session.context,message:`MCP Server connected: ${e.session.name}`},level:`info`}),this.registerRemoteProvider(e.session)}),await this.server.start({transportType:`stdio`,timeout:12e4}),this}registerRemoteProvider(e){if(e){if(!e.clientCapabilities||!e.clientCapabilities.sampling){e.server.sendLoggingMessage({data:{context:e.context,message:`MCP session missing required sampling capabilities, providers not registered`},level:`info`});return}let n=new lt;n.setSession(e),t.getInstance().registerProvider(`mcp`,n),e.server.sendLoggingMessage({data:{context:e.context,message:`MCP Server connected`},level:`info`})}else e.server.sendLoggingMessage({data:{context:e.context,message:`No MCP sessions available, providers not registered`},level:`warn`})}async stop(){this.server&&await this.server.stop()}};L.config(),process.env.TASK_MASTER_MCP=`true`;async function cr(){let e=new sr;process.on(`SIGINT`,async()=>{await e.stop(),process.exit(0)}),process.on(`SIGTERM`,async()=>{await e.stop(),process.exit(0)});try{await e.start()}catch(e){V.error(`Failed to start MCP server: ${e.message}`),process.exit(1)}}cr();export{};
@@ -1,4 +1,4 @@
1
- import{c as e}from"./ai-services-unified-C_wzEmAq.js";import{Bt as t,D as n,Ft as r,Gt as i,Ht as a,It as o,J as s,Pt as c,Ut as l,Vt as u,Wt as d,hn as f,ln as p,qt as m,vt as h,yt as g}from"./config-manager-DZYVJT7n.js";import{r as _}from"./git-utils-DllbRE35.js";import{Ct as v,St as y,Tt as b,x}from"./dependency-manager-DvEjtS1v.js";import*as S from"node:path";import C from"chalk";import w from"fs";import T from"path";import{randomUUID as E}from"crypto";import D from"os";import*as O from"node:fs";import*as k from"node:os";import{execSync as A}from"child_process";import{fileURLToPath as ee}from"url";import j from"boxen";import M from"readline";import te from"figlet";import ne from"gradient-string";import re from"inquirer";import ie from"ora";import ae from"open";const N=[`amp`,`claude`,`cline`,`codex`,`cursor`,`gemini`,`kiro`,`opencode`,`kilo`,`roo`,`trae`,`vscode`,`windsurf`,`zed`],oe=[`architect`,`ask`,`orchestrator`,`code`,`debug`,`test`],se=`# Task files`,ce=`tasks.json`,le=`tasks/`;function ue(e){return e.trim().replace(/^#/,``).trim()}function P(e){let t=ue(e);return t===ce||t===le}function de(e,t){return e.map(e=>{if(P(e)){let n=ue(e),r=e.match(/\s*$/)[0];return t?`# ${n}${r}`:`${n}${r}`}return e})}function fe(e){let t=[],n=!1;for(let r of e){if(r.trim()===se){n=!0;continue}P(r)||n&&!r.trim()||(n&&r.trim()&&!P(r)&&(n=!1),n||t.push(r))}return t}function pe(e,t){return e.filter(e=>{let n=e.trim();return!n||P(e)||n===se?!1:!t.has(n)})}function me(e){let t=[se];return e?t.push(`# ${ce}`,`# ${le} `):t.push(ce,`${le} `),t}function he(e){if(e.some(e=>e.trim())){let t=e[e.length-1];t&&t.trim()&&e.push(``)}}function ge(e,t,n){if(!e||typeof e!=`string`)throw Error(`targetPath must be a non-empty string`);if(!e.endsWith(`.gitignore`))throw Error(`targetPath must end with .gitignore`);if(!t||typeof t!=`string`)throw Error(`content must be a non-empty string`);if(typeof n!=`boolean`)throw Error(`storeTasksInGit must be a boolean`)}function _e(e,t,n){try{w.writeFileSync(e,t.join(`
1
+ import{c as e}from"./ai-services-unified-D47kSPRC.js";import{Bt as t,D as n,Ft as r,Gt as i,Ht as a,It as o,J as s,Pt as c,Ut as l,Vt as u,Wt as d,hn as f,ln as p,qt as m,vt as h,yt as g}from"./config-manager-BHkHj6Wx.js";import{r as _}from"./git-utils-DllbRE35.js";import{Ct as v,St as y,Tt as b,x}from"./dependency-manager-BPentJE1.js";import*as S from"node:path";import C from"chalk";import w from"fs";import T from"path";import{randomUUID as E}from"crypto";import D from"os";import*as O from"node:fs";import*as k from"node:os";import{execSync as A}from"child_process";import{fileURLToPath as ee}from"url";import j from"boxen";import M from"readline";import te from"figlet";import ne from"gradient-string";import re from"inquirer";import ie from"ora";import ae from"open";const N=[`amp`,`claude`,`cline`,`codex`,`cursor`,`gemini`,`kiro`,`opencode`,`kilo`,`roo`,`trae`,`vscode`,`windsurf`,`zed`],oe=[`architect`,`ask`,`orchestrator`,`code`,`debug`,`test`],se=`# Task files`,ce=`tasks.json`,le=`tasks/`;function ue(e){return e.trim().replace(/^#/,``).trim()}function P(e){let t=ue(e);return t===ce||t===le}function de(e,t){return e.map(e=>{if(P(e)){let n=ue(e),r=e.match(/\s*$/)[0];return t?`# ${n}${r}`:`${n}${r}`}return e})}function fe(e){let t=[],n=!1;for(let r of e){if(r.trim()===se){n=!0;continue}P(r)||n&&!r.trim()||(n&&r.trim()&&!P(r)&&(n=!1),n||t.push(r))}return t}function pe(e,t){return e.filter(e=>{let n=e.trim();return!n||P(e)||n===se?!1:!t.has(n)})}function me(e){let t=[se];return e?t.push(`# ${ce}`,`# ${le} `):t.push(ce,`${le} `),t}function he(e){if(e.some(e=>e.trim())){let t=e[e.length-1];t&&t.trim()&&e.push(``)}}function ge(e,t,n){if(!e||typeof e!=`string`)throw Error(`targetPath must be a non-empty string`);if(!e.endsWith(`.gitignore`))throw Error(`targetPath must end with .gitignore`);if(!t||typeof t!=`string`)throw Error(`content must be a non-empty string`);if(typeof n!=`boolean`)throw Error(`storeTasksInGit must be a boolean`)}function _e(e,t,n){try{w.writeFileSync(e,t.join(`
2
2
  `)+`
3
3
  `),typeof n==`function`&&n(`success`,`Created ${e} with full template`)}catch(t){throw typeof n==`function`&&n(`error`,`Failed to create ${e}: ${t.message}`),t}}function ve(e,t,n,r){try{let i=fe(w.readFileSync(e,`utf8`).split(`
4
4
  `)),a=pe(t,new Set(i.map(e=>e.trim()).filter(e=>e))),o=[...i];a.length>0&&(he(o),o.push(...a)),he(o),o.push(...me(n)),w.writeFileSync(e,o.join(`
@@ -3510,7 +3510,7 @@ Do you want to continue with these settings? (Y/n): `))).trim().toLowerCase()===
3510
3510
  `));let{storageType:e}=await re.prompt([{type:`list`,name:`storageType`,message:C.white(`How do you want to build it?
3511
3511
  `),choices:[{name:[C.bold(`Solo (Taskmaster)`),``,C.white(` • Parse your own PRDs into structured task lists and build with any IDE or background agents`),C.white(` • Agents execute tasks with precision, no scope creep, no going off-track`),C.white(` • Tasks live in a local JSON file, everything stays in your repo`),C.white(` • Upgrade to Hamster to bring the Taskmaster experience to your team`),``].join(`
3512
3512
  `),value:`local`,short:`Solo (Taskmaster)`},{name:[C.bold(`Together (Hamster)`),``,C.white(` • Write a brief with your team. Hamster refines it into a plan.`),C.white(` • Your team drafts, refines, and aligns on the same page before executing`),C.white(` • One brief, one plan, one source of truth for execution`),C.white(` • Access tasks on Taskmaster and execute with any AI agent`),``].join(`
3513
- `),value:`cloud`,short:`Together (Hamster)`}],default:`local`,pageSize:20}]);return e}catch(e){if(e.isTtyError||e.name===`ExitPromptError`)return X(`warn`,`Storage selection cancelled, defaulting to local storage`),`local`;throw e}}async function Tn(e,n,s,d,f,p=N,g=`local`,v=null){let y=process.cwd();X(`debug`,`Initializing project in ${y}`),Z(T.join(y,u)),Z(T.join(y,i)),Z(T.join(y,a)),Z(T.join(y,l)),Z(T.join(y,m)),bn(y);let b={year:new Date().getFullYear()},S=g===`cloud`?`team`:`solo`;function w(e){let t=q(e);t?J(y,t,{mode:S}):X(`warn`,`Unknown rule profile: ${e}`)}Q(`env.example`,T.join(y,c),b),Q(`config.json`,T.join(y,t),{...b});let E=T.join(y,t);fn(E)?X(`debug`,`Updated config with correct maxTokens values`):X(`debug`,`Could not update maxTokens in config`),Cn(E,g,v);try{let e=L(`gitignore`,`utf8`);ye(T.join(y,o),e,s,X)}catch(e){X(`error`,`Failed to create .gitignore: ${e.message}`)}Q(`example_prd.txt`,T.join(y,r)),Q(`example_prd_rpg.txt`,T.join(y,m,`example_prd_rpg.txt`));try{n===!1?X(`info`,`Git initialization skipped due to --no-git flag.`):n===!0?_()?X(`debug`,`Existing Git repository detected – skipping git init despite --git flag.`):(X(`info`,`Initializing Git repository due to --git flag...`),A(`git init`,{cwd:y,stdio:`ignore`}),X(`success`,`Git repository initialized`)):_()?X(`debug`,`Existing Git repository detected – skipping git init.`):(X(`info`,`No Git repository detected. Initializing one in project root...`),A(`git init`,{cwd:y,stdio:`ignore`}),X(`success`,`Git repository initialized`))}catch{X(`warn`,`Git not available, skipping repository initialization`)}if(f.rulesExplicitlyProvided||f.yes){X(`info`,`Generating profile rules from command-line flags...`);for(let e of p)w(e)}e&&yn();let D={cwd:y,stdio:`inherit`};if(h()&&(D.stdio=`ignore`,X(`info`,`Running npm install silently...`)),f.shouldSetupRules&&!h()&&!d&&!f?.yes&&!f.rulesExplicitlyProvided){console.log(j(C.cyan(`Configuring Rule Profiles...`),{padding:.5,margin:{top:1,bottom:.5},borderStyle:`round`,borderColor:`cyan`,width:60})),X(`info`,`Running interactive rules setup. Please select which rule profiles to include.`);try{A(`npx task-master rules --setup`,{stdio:`inherit`,cwd:y}),X(`success`,`Rule profiles configured.`)}catch(e){X(`error`,`Failed to configure rule profiles:`,e.message),X(`warn`,`You may need to run "task-master rules --setup" manually.`)}}else h()||d||f?.yes?f.rulesExplicitlyProvided?X(`debug`,`Skipping interactive rules setup because --rules flag was used.`):X(`debug`,`Skipping interactive rules setup in non-interactive mode.`):f.shouldSetupRules||X(`debug`,`Skipping rules setup - user declined.`);if(f.preferredLanguage&&!d)try{let e=(await import(`./response-language-Dp-q-zl4.js`)).default;e(f.preferredLanguage,{projectRoot:y,silent:!0}),X(`debug`,`Response language set to: ${f.preferredLanguage}`)}catch(e){X(`warn`,`Failed to set response language: ${e.message}`)}else h()&&!d?X(`debug`,`Skipping response language setup in silent (MCP) mode.`):d&&X(`debug`,`DRY RUN: Skipping response language setup.`);if(!h()&&!d&&!f?.yes&&g===`local`){console.log(j(C.cyan(`Configuring AI Models...`),{padding:.5,margin:{top:1,bottom:.5},borderStyle:`round`,borderColor:`cyan`,width:60})),X(`info`,`Running interactive model setup. Please select your preferred AI models.`);try{A(`npx task-master models --setup`,{stdio:`inherit`,cwd:y}),X(`success`,`AI Models configured.`)}catch(e){X(`error`,`Failed to configure AI models:`,e.message),X(`warn`,`You may need to run "task-master models --setup" manually.`)}}else g===`cloud`&&!d?console.log(j(C.green.bold(`✓ AI Models Managed by Hamster - go ham!
3513
+ `),value:`cloud`,short:`Together (Hamster)`}],default:`local`,pageSize:20}]);return e}catch(e){if(e.isTtyError||e.name===`ExitPromptError`)return X(`warn`,`Storage selection cancelled, defaulting to local storage`),`local`;throw e}}async function Tn(e,n,s,d,f,p=N,g=`local`,v=null){let y=process.cwd();X(`debug`,`Initializing project in ${y}`),Z(T.join(y,u)),Z(T.join(y,i)),Z(T.join(y,a)),Z(T.join(y,l)),Z(T.join(y,m)),bn(y);let b={year:new Date().getFullYear()},S=g===`cloud`?`team`:`solo`;function w(e){let t=q(e);t?J(y,t,{mode:S}):X(`warn`,`Unknown rule profile: ${e}`)}Q(`env.example`,T.join(y,c),b),Q(`config.json`,T.join(y,t),{...b});let E=T.join(y,t);fn(E)?X(`debug`,`Updated config with correct maxTokens values`):X(`debug`,`Could not update maxTokens in config`),Cn(E,g,v);try{let e=L(`gitignore`,`utf8`);ye(T.join(y,o),e,s,X)}catch(e){X(`error`,`Failed to create .gitignore: ${e.message}`)}Q(`example_prd.txt`,T.join(y,r)),Q(`example_prd_rpg.txt`,T.join(y,m,`example_prd_rpg.txt`));try{n===!1?X(`info`,`Git initialization skipped due to --no-git flag.`):n===!0?_()?X(`debug`,`Existing Git repository detected – skipping git init despite --git flag.`):(X(`info`,`Initializing Git repository due to --git flag...`),A(`git init`,{cwd:y,stdio:`ignore`}),X(`success`,`Git repository initialized`)):_()?X(`debug`,`Existing Git repository detected – skipping git init.`):(X(`info`,`No Git repository detected. Initializing one in project root...`),A(`git init`,{cwd:y,stdio:`ignore`}),X(`success`,`Git repository initialized`))}catch{X(`warn`,`Git not available, skipping repository initialization`)}if(f.rulesExplicitlyProvided||f.yes){X(`info`,`Generating profile rules from command-line flags...`);for(let e of p)w(e)}e&&yn();let D={cwd:y,stdio:`inherit`};if(h()&&(D.stdio=`ignore`,X(`info`,`Running npm install silently...`)),f.shouldSetupRules&&!h()&&!d&&!f?.yes&&!f.rulesExplicitlyProvided){console.log(j(C.cyan(`Configuring Rule Profiles...`),{padding:.5,margin:{top:1,bottom:.5},borderStyle:`round`,borderColor:`cyan`,width:60})),X(`info`,`Running interactive rules setup. Please select which rule profiles to include.`);try{A(`npx task-master rules --setup`,{stdio:`inherit`,cwd:y}),X(`success`,`Rule profiles configured.`)}catch(e){X(`error`,`Failed to configure rule profiles:`,e.message),X(`warn`,`You may need to run "task-master rules --setup" manually.`)}}else h()||d||f?.yes?f.rulesExplicitlyProvided?X(`debug`,`Skipping interactive rules setup because --rules flag was used.`):X(`debug`,`Skipping interactive rules setup in non-interactive mode.`):f.shouldSetupRules||X(`debug`,`Skipping rules setup - user declined.`);if(f.preferredLanguage&&!d)try{let e=(await import(`./response-language-DvPT9GOn.js`)).default;e(f.preferredLanguage,{projectRoot:y,silent:!0}),X(`debug`,`Response language set to: ${f.preferredLanguage}`)}catch(e){X(`warn`,`Failed to set response language: ${e.message}`)}else h()&&!d?X(`debug`,`Skipping response language setup in silent (MCP) mode.`):d&&X(`debug`,`DRY RUN: Skipping response language setup.`);if(!h()&&!d&&!f?.yes&&g===`local`){console.log(j(C.cyan(`Configuring AI Models...`),{padding:.5,margin:{top:1,bottom:.5},borderStyle:`round`,borderColor:`cyan`,width:60})),X(`info`,`Running interactive model setup. Please select your preferred AI models.`);try{A(`npx task-master models --setup`,{stdio:`inherit`,cwd:y}),X(`success`,`AI Models configured.`)}catch(e){X(`error`,`Failed to configure AI models:`,e.message),X(`warn`,`You may need to run "task-master models --setup" manually.`)}}else g===`cloud`&&!d?console.log(j(C.green.bold(`✓ AI Models Managed by Hamster - go ham!
3514
3514
 
3515
3515
  `)+C.white(`Hamster handles all AI model configuration for you.
3516
3516
  `)+C.dim(`• Optimized model selection for your tasks
@@ -0,0 +1 @@
1
+ import"./ai-services-unified-D47kSPRC.js";import"./config-manager-BHkHj6Wx.js";import"./git-utils-DllbRE35.js";import"./sentry-7KP4mTlv.js";import{A as e}from"./dependency-manager-BPentJE1.js";import"./response-language-eRs_-hFV.js";export{e as performResearch};
@@ -0,0 +1 @@
1
+ import"./config-manager-BHkHj6Wx.js";import"./git-utils-DllbRE35.js";import{t as e}from"./response-language-eRs_-hFV.js";export{e as default};