@hhsw2015/task-master-ai 0.43.7 → 0.43.9

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{o as e,s as t}from"./ai-services-unified-CEEU0EI1.js";import{$t as n,An as r,Dt as i,Ht as a,Kt as o,Mt as s,Nt as c,Qt as l,Sn as u,Tn as d,Tt as f,fn as p,ht as m,in as h,ln as g,m 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,wn as te,wt as T,x as ne,zt as re}from"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";import{r as ie}from"./sentry-Bfs4ROUL.js";import{$ as ae,A as oe,B as E,C as se,D 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 D,R as O,S as ve,U as ye,V as be,W as xe,X as Se,Y as Ce,Z as we,at as Te,ct as Ee,dt as De,gt as Oe,ht as ke,i as Ae,it as je,j as Me,lt as Ne,n as Pe,pt as Fe,r as Ie,rt as Le,st as Re,t as ze,ut as Be,w as Ve,z as He}from"./dependency-manager-Di3zHzuM.js";import{t as Ue}from"./response-language-c-DJJiVH.js";import{a as We,c as Ge,f as Ke,g as qe,h as k,l as A,m as Je,p as Ye,v as j}from"./profiles-DodRTAbX.js";import M from"node:path";import N from"chalk";import P from"fs";import F from"path";import Xe from"os";import I from"node:fs";import{z as L}from"zod";import{fileURLToPath as Ze}from"url";import R from"dotenv";import*as z from"@sentry/node";import{FastMCP as Qe}from"fastmcp";const B={debug:0,info:1,warn:2,error:3,success:4},$e=B[ne().toLowerCase()]??B.info;function et(e,...t){if(w())return;let n={debug:N.gray(`[DEBUG]`),info:N.blue(`[INFO]`),warn:N.yellow(`[WARN]`),error:N.red(`[ERROR]`),success:N.green(`[SUCCESS]`)};if(B[e]!==void 0&&B[e]>=$e){let r=n[e]||``,i=t;try{switch(e){case`error`:i=t.map(e=>typeof e==`string`?N.red(e):e);break;case`warn`:i=t.map(e=>typeof e==`string`?N.yellow(e):e);break;case`success`:i=t.map(e=>typeof e==`string`?N.green(e):e);break;case`info`:i=t.map(e=>typeof e==`string`?N.blue(e):e);break;case`debug`:i=t.map(e=>typeof e==`string`?N.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)=>et(e,...t);return{debug:e(`debug`),info:e(`info`),warn:e(`warn`),error:e(`error`),success:e(`success`),log:et}}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}},nt=class extends H{constructor(e,t={}){super(e,t),this.name=`MCPSessionError`}},rt=class extends H{constructor(e,t={}){super(e,t),this.name=`MCPSamplingError`}};function U(e){if(e instanceof H)return e;let t=e.message||`Unknown MCP error`,n=e;return t.includes(`session`)||t.includes(`connection`)?new nt(t,{cause:n,code:`SESSION_ERROR`}):t.includes(`sampling`)||t.includes(`timeout`)?new rt(t,{cause:n,code:`SAMPLING_ERROR`}):t.includes(`capabilities`)||t.includes(`not supported`)?new nt(t,{cause:n,code:`CAPABILITY_ERROR`}):new H(t,{cause:n,code:`UNKNOWN_ERROR`})}function it(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-D_pA4zzB.js";import{$t as n,An as r,Dt as i,Ht as a,Kt as o,Mt as s,Nt as c,Qt as l,Sn as u,Tn as d,Tt as f,fn as p,ht as m,in as h,ln as g,m 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,wn as te,wt as T,x as ne,zt as re}from"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import{r as ie}from"./sentry-Dbx7-h6F.js";import{$ as ae,A as oe,B as E,C as se,D 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 D,R as O,S as ve,U as ye,V as be,W as xe,X as Se,Y as Ce,Z as we,at as Te,ct as Ee,dt as De,gt as Oe,ht as ke,i as Ae,it as je,j as Me,lt as Ne,n as Pe,pt as Fe,r as Ie,rt as Le,st as Re,t as ze,ut as Be,w as Ve,z as He}from"./dependency-manager-DCJfWg5J.js";import{t as Ue}from"./response-language-DeTA_0Bx.js";import{a as We,c as Ge,f as Ke,g as qe,h as k,l as A,m as Je,p as Ye,v as j}from"./profiles-7-gfpDbJ.js";import M from"node:path";import N from"chalk";import P from"fs";import F from"path";import Xe from"os";import I from"node:fs";import{z as L}from"zod";import{fileURLToPath as Ze}from"url";import R from"dotenv";import*as z from"@sentry/node";import{FastMCP as Qe}from"fastmcp";const B={debug:0,info:1,warn:2,error:3,success:4},$e=B[ne().toLowerCase()]??B.info;function et(e,...t){if(w())return;let n={debug:N.gray(`[DEBUG]`),info:N.blue(`[INFO]`),warn:N.yellow(`[WARN]`),error:N.red(`[ERROR]`),success:N.green(`[SUCCESS]`)};if(B[e]!==void 0&&B[e]>=$e){let r=n[e]||``,i=t;try{switch(e){case`error`:i=t.map(e=>typeof e==`string`?N.red(e):e);break;case`warn`:i=t.map(e=>typeof e==`string`?N.yellow(e):e);break;case`success`:i=t.map(e=>typeof e==`string`?N.green(e):e);break;case`info`:i=t.map(e=>typeof e==`string`?N.blue(e):e);break;case`debug`:i=t.map(e=>typeof e==`string`?N.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)=>et(e,...t);return{debug:e(`debug`),info:e(`info`),warn:e(`warn`),error:e(`error`),success:e(`success`),log:et}}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}},nt=class extends H{constructor(e,t={}){super(e,t),this.name=`MCPSessionError`}},rt=class extends H{constructor(e,t={}){super(e,t),this.name=`MCPSamplingError`}};function U(e){if(e instanceof H)return e;let t=e.message||`Unknown MCP error`,n=e;return t.includes(`session`)||t.includes(`connection`)?new nt(t,{cause:n,code:`SESSION_ERROR`}):t.includes(`sampling`)||t.includes(`timeout`)?new rt(t,{cause:n,code:`SAMPLING_ERROR`}):t.includes(`capabilities`)||t.includes(`not supported`)?new nt(t,{cause:n,code:`CAPABILITY_ERROR`}):new H(t,{cause:n,code:`UNKNOWN_ERROR`})}function it(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 at(e){let t=[],n=``;for(let r of e)r.role===`system`?n=W(r.content):(r.role===`user`||r.role===`assistant`)&&t.push({role:r.role,content:{type:`text`,text:W(r.content)}});return{messages:t,systemPrompt:n}}function ot(e){let t=``,n=null,r=`stop`,i=[];return typeof e==`string`?t=e:e.content?(t=W(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 W(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 st(e,t=`result`){try{let n=G(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-C4XEb2yA.js`);await e(F.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-sbk7Up0i.js`)).default,r=parseInt(l,10);await e(F.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=O(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 ce(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=O(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=O(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 Ve(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=O(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 se(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=O(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 ve(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=O(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 ke(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 P.existsSync(e)?(x(),await Ae(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:L.object({id:L.string().describe(`ID of task that will depend on another task`),dependsOn:L.string().describe(`ID of task that will become a dependency`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Add Dependency`,destructiveHint:!0},execute:Z(`add-dependency`,async(e,{log:t,session:n})=>{try{t.info(`Adding dependency for task ${e.id} to depend on ${e.dependsOn}`);let n=i({projectRoot:e.projectRoot,tag:e.tag}),r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await zt({tasksJsonPath:r,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}`),J({result:a,log:t,errorPrefix:`Error adding dependency`,projectRoot:e.projectRoot,tag:n})}catch(e){return t.error(`Error in addDependency tool: ${e.message}`),q(e.message)}})})}function Sn(e){e.addTool({name:`add_subtask`,description:`Add a subtask to an existing task`,parameters:L.object({id:L.string().describe(`Parent task ID (required)`),taskId:L.string().optional().describe(`Existing task ID to convert to subtask`),title:L.string().optional().describe(`Title for the new subtask (when creating a new subtask)`),description:L.string().optional().describe(`Description for the new subtask`),details:L.string().optional().describe(`Implementation details for the new subtask`),status:L.string().optional().describe(`Status for the new subtask (default: 'pending')`),dependencies:L.string().optional().describe(`Comma-separated list of dependency IDs for the new subtask`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),skipGenerate:L.boolean().optional().describe(`Skip regenerating task files`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Add Subtask`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{let r=i({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}`),q(`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:r},t,{session:n});return o.success?t.info(`Subtask added successfully: ${o.data.message}`):t.error(`Failed to add subtask: ${o.error.message}`),J({result:o,log:t,errorPrefix:`Error adding subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in addSubtask tool: ${e.message}`),q(e.message)}})})}function Cn(e){e.addTool({name:`add_tag`,description:`Create a new tag for organizing tasks in different contexts`,parameters:L.object({name:L.string().describe(`Name of the new tag to create`),copyFromCurrent:L.boolean().optional().describe(`Whether to copy tasks from the current tag (default: false)`),copyFromTag:L.string().optional().describe(`Specific tag to copy tasks from`),fromBranch:L.boolean().optional().describe(`Create tag name from current git branch (ignores name parameter)`),description:L.string().optional().describe(`Optional description for the tag`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Add Tag`,destructiveHint:!1},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(e.message)}})})}function wn(e){e.addTool({name:`add_task`,description:`Add a new task using AI`,parameters:L.object({prompt:L.string().optional().describe(`Description of the task to add (required if not using manual fields)`),title:L.string().optional().describe(`Task title (for manual task creation)`),description:L.string().optional().describe(`Task description (for manual task creation)`),details:L.string().optional().describe(`Implementation details (for manual task creation)`),testStrategy:L.string().optional().describe(`Test strategy (for manual task creation)`),dependencies:L.string().optional().describe(`Comma-separated list of task IDs this task depends on`),priority:L.string().optional().describe(`Task priority (high, medium, low)`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`),research:L.boolean().optional().describe(`Whether to use research capabilities for task creation`)}),annotations:{title:`Add Task`,destructiveHint:!1},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Starting add-task with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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:r},t,{session:n}),log:t,errorPrefix:`Error adding task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in add-task tool: ${e.message}`),q(e.message)}})})}function Tn(e){e.addTool({name:`analyze_project_complexity`,description:`Analyze task complexity and generate expansion recommendations.`,parameters:L.object({threshold:L.coerce.number().int().min(1).max(10).optional().default(5).describe(`Complexity score threshold (1-10) to recommend expansion.`),research:L.boolean().optional().default(!1).describe(`Use Perplexity AI for research-backed analysis.`),output:L.string().optional().describe(`Output file path relative to project root (default: ${c}).`),file:L.string().optional().describe(`Path to the tasks file relative to project root (default: tasks/tasks.json).`),ids:L.string().optional().describe(`Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").`),from:L.coerce.number().int().positive().optional().describe(`Starting task ID in a range to analyze.`),to:L.coerce.number().int().positive().optional().describe(`Ending task ID in a range to analyze.`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Analyze Project Complexity`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{let r=`analyze_project_complexity`;try{t.info(`Executing ${r} tool with args: ${JSON.stringify(e)}`);let a=i({projectRoot:e.projectRoot,tag:e.tag}),o;try{o=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`${r}: Resolved tasks path: ${o}`)}catch(n){return t.error(`${r}: Error finding tasks.json: ${n.message}`),q(`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(`${r}: Report output path: ${s}`);let c=F.dirname(s);try{P.existsSync(c)||(P.mkdirSync(c,{recursive:!0}),t.info(`${r}: Created output directory: ${c}`))}catch(e){return t.error(`${r}: Failed to create output directory ${c}: ${e.message}`),q(`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(`${r}: Direct function result: success=${l.success}`),J({result:l,log:t,errorPrefix:`Error analyzing task complexity`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${r} tool execute: ${e.message}`),q(`Internal tool error (${r}): ${e.message}`)}})})}function En(e){e.addTool({name:`clear_subtasks`,description:`Clear subtasks from specified tasks`,parameters:L.object({id:L.string().optional().describe(`Task IDs (comma-separated) to clear subtasks from`),all:L.boolean().optional().describe(`Clear subtasks from all tasks`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.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:Z(`clear-subtasks`,async(e,t)=>{try{t.log.info(`Clearing subtasks with args: ${JSON.stringify(e)}`);let n=i({projectRoot:e.projectRoot,tag:e.tag}),r;try{r=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await Wt({tasksJsonPath:r,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}`),J({result:a,log:t.log,errorPrefix:`Error clearing subtasks`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in clearSubtasks tool: ${e.message}`),q(e.message)}})})}function Dn(e){e.addTool({name:`complexity_report`,description:`Display the complexity analysis report in a readable format`,parameters:L.object({file:L.string().optional().describe(`Path to the report file (default: ${c})`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Complexity Report`,readOnlyHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Getting complexity report with args: ${JSON.stringify(e)}`);let n=m(e.projectRoot),r=He({projectRoot:e.projectRoot,complexityReport:e.file,tag:n},t);if(t.info(`Reading complexity report from path: `,r),!r)return q(`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}`),J({result:i,log:t,errorPrefix:`Error retrieving complexity report`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in complexity-report tool: ${e.message}`),q(`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:L.object({sourceName:L.string().describe(`Name of the source tag to copy from`),targetName:L.string().describe(`Name of the new tag to create`),description:L.string().optional().describe(`Optional description for the new tag`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Copy Tag`,destructiveHint:!1},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(e.message)}})})}function kn(e){e.addTool({name:`delete_tag`,description:`Delete an existing tag and all its tasks`,parameters:L.object({name:L.string().describe(`Name of the tag to delete`),yes:L.boolean().optional().describe(`Skip confirmation prompts (default: true for MCP)`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Delete Tag`,destructiveHint:!0},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(e.message)}})})}function An(e){e.addTool({name:`expand_all`,description:`Expand all pending tasks into subtasks based on complexity or defaults`,parameters:L.object({num:L.string().optional().describe(`Target number of subtasks per task (uses complexity/defaults otherwise)`),research:L.boolean().optional().describe(`Enable research-backed subtask generation (e.g., using Perplexity)`),prompt:L.string().optional().describe(`Additional context to guide subtask generation for all tasks`),force:L.boolean().optional().describe(`Force regeneration of subtasks for tasks that already have them`),file:L.string().optional().describe(`Absolute path to the tasks file in the /tasks folder inside the project root (default: tasks/tasks.json)`),projectRoot:L.string().optional().describe(`Absolute path to the project root directory (derived from session if possible)`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Expand All Tasks`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Tool expand_all execution started with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}let o=be(null,{projectRoot:e.projectRoot,tag:r},t);return t.info(`Using complexity report path: ${o}`),J({result:await Jt({tasksJsonPath:a,num:e.num,research:e.research,prompt:e.prompt,force:e.force,projectRoot:e.projectRoot,tag:r,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),q(`An unexpected error occurred: ${e.message}`)}})})}function jn(e){e.addTool({name:`expand_task`,description:`Expand a task into subtasks for detailed implementation`,parameters:L.object({id:L.string().describe(`ID of task to expand`),num:L.string().optional().describe(`Number of subtasks to generate`),research:L.boolean().optional().default(!1).describe(`Use research role for generation`),prompt:L.string().optional().describe(`Additional context for subtask generation`),file:L.string().optional().describe(`Path to the tasks file relative to project root (e.g., tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),force:L.boolean().optional().default(!1).describe(`Force expansion even if subtasks exist`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Expand Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Starting expand-task with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}let o=He({...e,tag:r},t);return J({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:r},t,{session:n}),log:t,errorPrefix:`Error expanding task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in expand-task tool: ${e.message}`),q(e.message)}})})}function Mn(e){e.addTool({name:`fix_dependencies`,description:`Fix invalid dependencies in tasks automatically`,parameters:L.object({file:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Fix Dependencies`,destructiveHint:!0},execute:Z(`fix-dependencies`,async(e,t)=>{try{t.log.info(`Fixing dependencies with args: ${JSON.stringify(e)}`);let n=i({projectRoot:e.projectRoot,tag:e.tag}),r;try{r=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await Xt({tasksJsonPath:r,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}`),J({result:a,log:t.log,errorPrefix:`Error fixing dependencies`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in fixDependencies tool: ${e.message}`),q(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.`,parameters:L.object({skipInstall:L.boolean().optional().default(!1).describe(`Skip installing dependencies automatically. Never do this unless you are sure the project is already installed.`),addAliases:L.boolean().optional().default(!0).describe(`Add shell aliases (tm, taskmaster, hamster, ham) to shell config file.`),initGit:L.boolean().optional().default(!0).describe(`Initialize Git repository in project root.`),storeTasksInGit:L.boolean().optional().default(!0).describe(`Store tasks in Git (tasks.json and tasks/ directory).`),yes:L.boolean().optional().default(!0).describe(`Skip prompts and use default values. Always set to true for MCP tools.`),projectRoot:L.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:L.array(L.enum(j)).optional().describe(`List of rule profiles to include at initialization. If omitted, defaults to Cursor profile only. Available options: ${j.join(`, `)}`)}),annotations:{title:`Initialize Project`,destructiveHint:!0},execute:X(async(e,t)=>{let{log:n}=t,r=t.session;try{return n.info(`Executing initialize_project tool with args: ${JSON.stringify(e)}`),J({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),q(t,{details:e.stack})}})})}function Pn(e){e.addTool({name:`list_tags`,description:`List all available tags with task counts and metadata`,parameters:L.object({showMetadata:L.boolean().optional().describe(`Whether to include metadata in the output (default: false)`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`List Tags`,readOnlyHint:!0},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(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:L.object({setMain:L.string().optional().describe(`Set the primary model for task generation/updates. Model provider API key is required in the MCP config ENV.`),setResearch:L.string().optional().describe(`Set the model for research-backed operations. Model provider API key is required in the MCP config ENV.`),setFallback:L.string().optional().describe(`Set the model to use if the primary fails. Model provider API key is required in the MCP config ENV.`),listAvailableModels:L.boolean().optional().describe(`List all available models not currently in use. Input/output costs values are in dollars (3 is $3.00).`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),openrouter:L.boolean().optional().describe(`Indicates the set model ID is a custom OpenRouter model.`),ollama:L.boolean().optional().describe(`Indicates the set model ID is a custom Ollama model.`),bedrock:L.boolean().optional().describe(`Indicates the set model ID is a custom AWS Bedrock model.`),azure:L.boolean().optional().describe(`Indicates the set model ID is a custom Azure OpenAI model.`),vertex:L.boolean().optional().describe(`Indicates the set model ID is a custom Google Vertex AI model.`),"openai-compatible":L.boolean().optional().describe(`Indicates the set model ID is a custom OpenAI-compatible model. Requires baseURL parameter.`),baseURL:L.string().optional().describe(`Custom base URL for providers that support it (e.g., https://api.example.com/v1).`)}),annotations:{title:`Models`,destructiveHint:!0},execute:Z(`models`,async(e,t)=>{try{return t.log.info(`Starting models tool with args: ${JSON.stringify(e)}`),J({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}`),q(e.message)}})})}function In(e){e.addTool({name:`move_task`,description:`Move a task or subtask to a new position`,parameters:L.object({from:L.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:L.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:L.string().optional().describe(`Custom path to tasks.json file`),projectRoot:L.string().describe(`Root directory of the project (typically derived from session)`),tag:L.string().optional().describe(`Tag context to operate on`),fromTag:L.string().optional().describe(`Source tag for cross-tag moves`),toTag:L.string().optional().describe(`Target tag for cross-tag moves`),withDependencies:L.boolean().optional().describe(`Move dependent tasks along with main task`),ignoreDependencies:L.boolean().optional().describe(`Break cross-tag dependencies during move`)}),annotations:{title:`Move Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{if(e.fromTag&&e.toTag&&e.fromTag!==e.toTag){if(!e.from)return q(`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),J({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 q(`Destination ID is required for within-tag moves`,`MISSING_DESTINATION_ID`);let r=i({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 i=[],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:r,generateFiles:f},t,{session:n});p.success?i.push(p.data):t.error(`Failed to move ${u} to ${d}: ${p.error.message}`)}return J({result:{success:!0,data:{moves:i,skipped:c.length>0?c:void 0,message:`Successfully moved ${i.length} tasks${c.length>0?`, skipped ${c.length}`:``}`}},log:t,errorPrefix:`Error moving multiple tasks`,projectRoot:e.projectRoot})}return J({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 J({result:await an({sourceId:e.from,destinationId:e.to,tasksJsonPath:a,projectRoot:e.projectRoot,tag:r,generateFiles:!0},t,{session:n}),log:t,errorPrefix:`Error moving task`,projectRoot:e.projectRoot})}}catch(e){return q(`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:L.object({file:L.string().optional().describe(`Absolute path to the tasks file`),complexityReport:L.string().optional().describe(`Path to the complexity report file (relative to project root or absolute)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Next Task`,readOnlyHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Finding next task with args: ${JSON.stringify(e)}`);let r=i({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=ue(e,n)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let o;try{o=de({...e,tag:r},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:r},t,{session:n});return t.info(`Next task result: ${s.success?`found`:`none`}`),J({result:s,log:t,errorPrefix:`Error finding next task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error finding next task: ${e.message}`),q(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 ${a} directory.`,parameters:L.object({input:L.string().optional().default(re).describe(`Absolute path to the PRD document file (.txt, .md, etc.)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`),destination:L.enum([`local`,`hamster`]).optional().default(`local`).describe(`Where to parse the PRD: "local" writes tasks.json, "hamster" creates a cloud brief and tasks`),output:L.string().optional().describe(`Output path for tasks.json file (default: ${o})`),numTasks:L.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:L.boolean().optional().default(!1).describe(`Overwrite existing output file without prompting.`),research:L.boolean().optional().describe(`Enable Taskmaster to use the research role for potentially more informed task generation. Requires appropriate API key.`),append:L.boolean().optional().describe(`Append generated tasks to existing file.`)}),annotations:{title:`Parse PRD`,destructiveHint:!0},execute:X(async(e,{log:t,session:n,reportProgress:r})=>{try{let a=i({projectRoot:e.projectRoot,tag:e.tag}),o=ft(r,t);return J({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}`),q(`Failed to parse PRD: ${e.message}`)}})})}function zn(e){e.addTool({name:`remove_dependency`,description:`Remove a dependency from a task`,parameters:L.object({id:L.string().describe(`Task ID to remove dependency from`),dependsOn:L.string().describe(`Task ID to remove as a dependency`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Remove Dependency`,destructiveHint:!0},execute:Z(`remove-dependency`,async(e,t)=>{try{let n=i({projectRoot:e.projectRoot,tag:e.tag});t.log.info(`Removing dependency for task ${e.id} from ${e.dependsOn} with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await ln({tasksJsonPath:r,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}`),J({result:a,log:t.log,errorPrefix:`Error removing dependency`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in removeDependency tool: ${e.message}`),q(e.message)}})})}function Bn(e){e.addTool({name:`remove_subtask`,description:`Remove a subtask from its parent task`,parameters:L.object({id:L.string().describe(`Subtask ID to remove in format 'parentId.subtaskId' (required)`),convert:L.boolean().optional().describe(`Convert the subtask to a standalone task instead of deleting it`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),skipGenerate:L.boolean().optional().describe(`Skip regenerating task files`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Remove Subtask`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{let r=i({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}`),q(`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:r},t,{session:n});return o.success?t.info(`Subtask removed successfully: ${o.data.message}`):t.error(`Failed to remove subtask: ${o.error.message}`),J({result:o,log:t,errorPrefix:`Error removing subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in removeSubtask tool: ${e.message}`),q(e.message)}})})}function Vn(e){e.addTool({name:`remove_task`,description:`Remove a task or subtask permanently from the tasks list`,parameters:L.object({id:L.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:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),confirm:L.boolean().optional().describe(`Whether to skip confirmation prompt (default: false)`),tag:L.string().optional().describe(`Specify which tag context to operate on. Defaults to the current active tag.`)}),annotations:{title:`Remove Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Removing task(s) with ID(s): ${e.id}`);let r=i({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}`),q(`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:r},t,{session:n});return o.success?t.info(`Successfully removed task: ${e.id}`):t.error(`Failed to remove task: ${o.error.message}`),J({result:o,log:t,errorPrefix:`Error removing task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in remove-task tool: ${e.message}`),q(`Failed to remove task: ${e.message}`)}})})}function Hn(e){e.addTool({name:`rename_tag`,description:`Rename an existing tag`,parameters:L.object({oldName:L.string().describe(`Current name of the tag to rename`),newName:L.string().describe(`New name for the tag`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Rename Tag`,destructiveHint:!0},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(e.message)}})})}function Un(e){e.addTool({name:`research`,description:`Perform AI-powered research queries with project context`,parameters:L.object({query:L.string().describe(`Research query/prompt (required)`),taskIds:L.string().optional().describe(`Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17")`),filePaths:L.string().optional().describe(`Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md")`),customContext:L.string().optional().describe(`Additional custom context text to include in the research`),includeProjectTree:L.boolean().optional().describe(`Include project file tree structure in context (default: false)`),detailLevel:L.enum([`low`,`medium`,`high`]).optional().describe(`Detail level for the research response (default: medium)`),saveTo:L.string().optional().describe(`Automatically save research results to specified task/subtask ID (e.g., "15" or "15.2")`),saveToFile:L.boolean().optional().describe(`Save research results to .taskmaster/docs/research/ directory (default: false)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Research`,destructiveHint:!0,openWorldHint:!0},execute:X(async(e,{log:t,session:n})=>{try{let r=i({projectRoot:e.projectRoot,tag:e.tag});return t.info(`Starting research with query: "${e.query.substring(0,100)}${e.query.length>100?`...`:``}"`),J({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:r},t,{session:n}),log:t,errorPrefix:`Error performing research`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in research tool: ${e.message}`),q(e.message)}})})}async function Wn(e,t,n={}){let{projectRoot:r,language:i}=e,a=O(t);t.info(`Executing response-language_direct with args: ${JSON.stringify(e)}`),t.info(`Using project root: ${r}`);try{return x(),Ue(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:L.object({projectRoot:L.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:L.string().describe(`The new response language to set. like "中文" "English" or "español".`)}),annotations:{title:`Response Language`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{return t.info(`Executing response-language tool with args: ${JSON.stringify(e)}`),J({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}`),q(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===A.REMOVE){if(!a&&Ge(r,n)){let e=We(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(!k(e)){o.push({profileName:e,success:!1,error:`The requested rule profile for '${e}' is unavailable. Supported profiles are: ${j.join(`, `)}.`});continue}let t=qe(r,Je(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===A.ADD){for(let e of n){if(!k(e)){s.push({profileName:e,success:!1,error:`Profile not found: static import missing for '${e}'. Valid profiles: ${j.join(`, `)}`});continue}let t=Je(e),{success:n,failed:i}=Ye(r,t),a=t.rulesDir,o=F.join(r,a),c=t.profileDir,l=t.mcpConfig!==!1,u=l&&t.mcpConfigPath?F.join(r,t.mcpConfigPath):null,d=l&&u?P.existsSync(u):void 0,f=P.existsSync(o),p=P.existsSync(F.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 "${A.ADD}" or "${A.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:L.object({action:L.enum([`add`,`remove`]).describe(`Whether to add or remove rule profiles.`),profiles:L.array(L.enum(j)).min(1).describe(`List of rule profiles to add or remove (e.g., [\"cursor\", \"roo\"]). Available options: ${j.join(`, `)}`),projectRoot:L.string().describe(`The root directory of the project. Must be an absolute path.`),force:L.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:X(async(e,{log:t,session:n})=>{try{return t.info(`[rules tool] Executing action: ${e.action} for profiles: ${e.profiles.join(`, `)} in ${e.projectRoot}`),J({result:await Kn(e,t,{session:n}),log:t,projectRoot:e.projectRoot})}catch(e){return t.error(`[rules tool] Error: ${e.message}`),q(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:L.object({id:L.string().describe(`Comma-separated list of task IDs to scope down (e.g., "1,3,5")`),strength:L.string().optional().describe(`Strength level: light, regular, or heavy (default: regular)`),prompt:L.string().optional().describe(`Custom prompt for specific scoping adjustments`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`),research:L.boolean().optional().describe(`Whether to use research capabilities for scoping`)}),annotations:{title:`Scope Down Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Starting scope-down with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({result:await mn({tasksJsonPath:a,id:e.id,strength:e.strength,prompt:e.prompt,research:e.research,projectRoot:e.projectRoot,tag:r},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}`),q(e.message)}})})}function Yn(e){e.addTool({name:`scope_up_task`,description:`Increase the complexity of one or more tasks using AI`,parameters:L.object({id:L.string().describe(`Comma-separated list of task IDs to scope up (e.g., "1,3,5")`),strength:L.string().optional().describe(`Strength level: light, regular, or heavy (default: regular)`),prompt:L.string().optional().describe(`Custom prompt for specific scoping adjustments`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`),research:L.boolean().optional().describe(`Whether to use research capabilities for scoping`)}),annotations:{title:`Scope Up Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Starting scope-up with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({result:await hn({tasksJsonPath:a,id:e.id,strength:e.strength,prompt:e.prompt,research:e.research,projectRoot:e.projectRoot,tag:r},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}`),q(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:L.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:L.string().optional().describe(`Information to add to the subtask. Required unless only updating metadata.`),research:L.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),metadata:L.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:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Subtask`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{let r=`update_subtask`;try{let a=i({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(`${r}: Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let s=Q(e.metadata,q);if(s.error)return s.error;let c=s.parsedMetadata;if(!e.prompt&&!c)return q(`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`}`),J({result:l,log:t,errorPrefix:`Error updating subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${r} tool execute: ${e.message}`),q(`Internal tool error (${r}): ${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:L.object({id:L.string().describe(`ID of the task (e.g., '15') to update. Subtasks are supported using the update-subtask tool.`),prompt:L.string().optional().describe(`New information or context to incorporate into the task. Required unless only updating metadata.`),research:L.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),append:L.boolean().optional().describe(`Append timestamped information to task details instead of full update`),metadata:L.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:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{let r=`update_task`;try{let a=i({projectRoot:e.projectRoot,tag:e.tag});t.info(`Executing ${r} tool with args: ${JSON.stringify(e)}`);let o;try{o=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`${r}: Resolved tasks path: ${o}`)}catch(e){return t.error(`${r}: Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let s=Q(e.metadata,q);if(s.error)return s.error;let c=s.parsedMetadata;if(!e.prompt&&!c)return q(`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(`${r}: Direct function result: success=${l.success}`),J({result:l,log:t,errorPrefix:`Error updating task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${r} tool execute: ${e.message}`),q(`Internal tool error (${r}): ${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:L.object({from:L.string().describe(`Task ID from which to start updating (inclusive). IMPORTANT: This tool uses 'from', not 'id'`),prompt:L.string().describe(`Explanation of changes or new context to apply`),research:L.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),file:L.string().optional().describe(`Path to the tasks file relative to project root`),projectRoot:L.string().optional().describe(`The directory of the project. (Optional, usually from session)`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Tasks`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{let r=`update`,{from:a,prompt:o,research:s,file:c,projectRoot:l,tag:u}=e,d=i({projectRoot:e.projectRoot,tag:e.tag});try{t.info(`Executing ${r} tool with normalized root: ${l}`);let i;try{i=E({projectRoot:l,file:c},t),t.info(`${r}: Resolved tasks path: ${i}`)}catch(e){return t.error(`${r}: Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json within project root '${l}': ${e.message}`)}let u=await vn({tasksJsonPath:i,from:a,prompt:o,research:s,projectRoot:l,tag:d},t,{session:n});return t.info(`${r}: Direct function result: success=${u.success}`),J({result:u,log:t,errorPrefix:`Error updating tasks`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${r} tool execute: ${e.message}`),q(`Internal tool error (${r}): ${e.message}`)}})})}function $n(e){e.addTool({name:`use_tag`,description:`Switch to a different tag context for task operations`,parameters:L.object({name:L.string().describe(`Name of the tag to switch to`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Use Tag`,destructiveHint:!0},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(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:L.object({file:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Validate Dependencies`,readOnlyHint:!0},execute:Z(`validate-dependencies`,async(e,{log:t,session:n})=>{try{let n=i({projectRoot:e.projectRoot,tag:e.tag});t.info(`Validating dependencies 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}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await bn({tasksJsonPath:r,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}`),J({result:a,log:t,errorPrefix:`Error validating dependencies`,projectRoot:e.projectRoot,tag:n})}catch(e){return t.error(`Error in validateDependencies tool: ${e.message}`),q(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`}}}R.config(),ie();const or=Ze(import.meta.url);F.dirname(or);var sr=class{constructor(){this.options={name:`Task Master MCP Server`,version:d};let e=new Qe(this.options);if(e._mcpServer&&z.wrapMcpServerWithSentry)try{e._mcpServer=z.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 dt;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()}};R.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-OR7LPqsO.js`);await e(F.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-mhULzJWi.js`)).default,r=parseInt(l,10);await e(F.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=O(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 ce(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=O(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=O(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 Ve(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=O(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 se(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=O(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 ve(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=O(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 ke(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 P.existsSync(e)?(x(),await Ae(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:L.object({id:L.string().describe(`ID of task that will depend on another task`),dependsOn:L.string().describe(`ID of task that will become a dependency`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Add Dependency`,destructiveHint:!0},execute:Z(`add-dependency`,async(e,{log:t,session:n})=>{try{t.info(`Adding dependency for task ${e.id} to depend on ${e.dependsOn}`);let n=i({projectRoot:e.projectRoot,tag:e.tag}),r;try{r=E({projectRoot:e.projectRoot,file:e.file},t)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await zt({tasksJsonPath:r,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}`),J({result:a,log:t,errorPrefix:`Error adding dependency`,projectRoot:e.projectRoot,tag:n})}catch(e){return t.error(`Error in addDependency tool: ${e.message}`),q(e.message)}})})}function Sn(e){e.addTool({name:`add_subtask`,description:`Add a subtask to an existing task`,parameters:L.object({id:L.string().describe(`Parent task ID (required)`),taskId:L.string().optional().describe(`Existing task ID to convert to subtask`),title:L.string().optional().describe(`Title for the new subtask (when creating a new subtask)`),description:L.string().optional().describe(`Description for the new subtask`),details:L.string().optional().describe(`Implementation details for the new subtask`),status:L.string().optional().describe(`Status for the new subtask (default: 'pending')`),dependencies:L.string().optional().describe(`Comma-separated list of dependency IDs for the new subtask`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),skipGenerate:L.boolean().optional().describe(`Skip regenerating task files`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Add Subtask`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{let r=i({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}`),q(`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:r},t,{session:n});return o.success?t.info(`Subtask added successfully: ${o.data.message}`):t.error(`Failed to add subtask: ${o.error.message}`),J({result:o,log:t,errorPrefix:`Error adding subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in addSubtask tool: ${e.message}`),q(e.message)}})})}function Cn(e){e.addTool({name:`add_tag`,description:`Create a new tag for organizing tasks in different contexts`,parameters:L.object({name:L.string().describe(`Name of the new tag to create`),copyFromCurrent:L.boolean().optional().describe(`Whether to copy tasks from the current tag (default: false)`),copyFromTag:L.string().optional().describe(`Specific tag to copy tasks from`),fromBranch:L.boolean().optional().describe(`Create tag name from current git branch (ignores name parameter)`),description:L.string().optional().describe(`Optional description for the tag`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Add Tag`,destructiveHint:!1},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(e.message)}})})}function wn(e){e.addTool({name:`add_task`,description:`Add a new task using AI`,parameters:L.object({prompt:L.string().optional().describe(`Description of the task to add (required if not using manual fields)`),title:L.string().optional().describe(`Task title (for manual task creation)`),description:L.string().optional().describe(`Task description (for manual task creation)`),details:L.string().optional().describe(`Implementation details (for manual task creation)`),testStrategy:L.string().optional().describe(`Test strategy (for manual task creation)`),dependencies:L.string().optional().describe(`Comma-separated list of task IDs this task depends on`),priority:L.string().optional().describe(`Task priority (high, medium, low)`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`),research:L.boolean().optional().describe(`Whether to use research capabilities for task creation`)}),annotations:{title:`Add Task`,destructiveHint:!1},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Starting add-task with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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:r},t,{session:n}),log:t,errorPrefix:`Error adding task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in add-task tool: ${e.message}`),q(e.message)}})})}function Tn(e){e.addTool({name:`analyze_project_complexity`,description:`Analyze task complexity and generate expansion recommendations.`,parameters:L.object({threshold:L.coerce.number().int().min(1).max(10).optional().default(5).describe(`Complexity score threshold (1-10) to recommend expansion.`),research:L.boolean().optional().default(!1).describe(`Use Perplexity AI for research-backed analysis.`),output:L.string().optional().describe(`Output file path relative to project root (default: ${c}).`),file:L.string().optional().describe(`Path to the tasks file relative to project root (default: tasks/tasks.json).`),ids:L.string().optional().describe(`Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").`),from:L.coerce.number().int().positive().optional().describe(`Starting task ID in a range to analyze.`),to:L.coerce.number().int().positive().optional().describe(`Ending task ID in a range to analyze.`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Analyze Project Complexity`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{let r=`analyze_project_complexity`;try{t.info(`Executing ${r} tool with args: ${JSON.stringify(e)}`);let a=i({projectRoot:e.projectRoot,tag:e.tag}),o;try{o=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`${r}: Resolved tasks path: ${o}`)}catch(n){return t.error(`${r}: Error finding tasks.json: ${n.message}`),q(`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(`${r}: Report output path: ${s}`);let c=F.dirname(s);try{P.existsSync(c)||(P.mkdirSync(c,{recursive:!0}),t.info(`${r}: Created output directory: ${c}`))}catch(e){return t.error(`${r}: Failed to create output directory ${c}: ${e.message}`),q(`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(`${r}: Direct function result: success=${l.success}`),J({result:l,log:t,errorPrefix:`Error analyzing task complexity`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${r} tool execute: ${e.message}`),q(`Internal tool error (${r}): ${e.message}`)}})})}function En(e){e.addTool({name:`clear_subtasks`,description:`Clear subtasks from specified tasks`,parameters:L.object({id:L.string().optional().describe(`Task IDs (comma-separated) to clear subtasks from`),all:L.boolean().optional().describe(`Clear subtasks from all tasks`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.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:Z(`clear-subtasks`,async(e,t)=>{try{t.log.info(`Clearing subtasks with args: ${JSON.stringify(e)}`);let n=i({projectRoot:e.projectRoot,tag:e.tag}),r;try{r=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await Wt({tasksJsonPath:r,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}`),J({result:a,log:t.log,errorPrefix:`Error clearing subtasks`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in clearSubtasks tool: ${e.message}`),q(e.message)}})})}function Dn(e){e.addTool({name:`complexity_report`,description:`Display the complexity analysis report in a readable format`,parameters:L.object({file:L.string().optional().describe(`Path to the report file (default: ${c})`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Complexity Report`,readOnlyHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Getting complexity report with args: ${JSON.stringify(e)}`);let n=m(e.projectRoot),r=He({projectRoot:e.projectRoot,complexityReport:e.file,tag:n},t);if(t.info(`Reading complexity report from path: `,r),!r)return q(`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}`),J({result:i,log:t,errorPrefix:`Error retrieving complexity report`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in complexity-report tool: ${e.message}`),q(`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:L.object({sourceName:L.string().describe(`Name of the source tag to copy from`),targetName:L.string().describe(`Name of the new tag to create`),description:L.string().optional().describe(`Optional description for the new tag`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Copy Tag`,destructiveHint:!1},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(e.message)}})})}function kn(e){e.addTool({name:`delete_tag`,description:`Delete an existing tag and all its tasks`,parameters:L.object({name:L.string().describe(`Name of the tag to delete`),yes:L.boolean().optional().describe(`Skip confirmation prompts (default: true for MCP)`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Delete Tag`,destructiveHint:!0},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(e.message)}})})}function An(e){e.addTool({name:`expand_all`,description:`Expand all pending tasks into subtasks based on complexity or defaults`,parameters:L.object({num:L.string().optional().describe(`Target number of subtasks per task (uses complexity/defaults otherwise)`),research:L.boolean().optional().describe(`Enable research-backed subtask generation (e.g., using Perplexity)`),prompt:L.string().optional().describe(`Additional context to guide subtask generation for all tasks`),force:L.boolean().optional().describe(`Force regeneration of subtasks for tasks that already have them`),file:L.string().optional().describe(`Absolute path to the tasks file in the /tasks folder inside the project root (default: tasks/tasks.json)`),projectRoot:L.string().optional().describe(`Absolute path to the project root directory (derived from session if possible)`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Expand All Tasks`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Tool expand_all execution started with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}let o=be(null,{projectRoot:e.projectRoot,tag:r},t);return t.info(`Using complexity report path: ${o}`),J({result:await Jt({tasksJsonPath:a,num:e.num,research:e.research,prompt:e.prompt,force:e.force,projectRoot:e.projectRoot,tag:r,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),q(`An unexpected error occurred: ${e.message}`)}})})}function jn(e){e.addTool({name:`expand_task`,description:`Expand a task into subtasks for detailed implementation`,parameters:L.object({id:L.string().describe(`ID of task to expand`),num:L.string().optional().describe(`Number of subtasks to generate`),research:L.boolean().optional().default(!1).describe(`Use research role for generation`),prompt:L.string().optional().describe(`Additional context for subtask generation`),file:L.string().optional().describe(`Path to the tasks file relative to project root (e.g., tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),force:L.boolean().optional().default(!1).describe(`Force expansion even if subtasks exist`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Expand Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Starting expand-task with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}let o=He({...e,tag:r},t);return J({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:r},t,{session:n}),log:t,errorPrefix:`Error expanding task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in expand-task tool: ${e.message}`),q(e.message)}})})}function Mn(e){e.addTool({name:`fix_dependencies`,description:`Fix invalid dependencies in tasks automatically`,parameters:L.object({file:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Fix Dependencies`,destructiveHint:!0},execute:Z(`fix-dependencies`,async(e,t)=>{try{t.log.info(`Fixing dependencies with args: ${JSON.stringify(e)}`);let n=i({projectRoot:e.projectRoot,tag:e.tag}),r;try{r=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await Xt({tasksJsonPath:r,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}`),J({result:a,log:t.log,errorPrefix:`Error fixing dependencies`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in fixDependencies tool: ${e.message}`),q(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.`,parameters:L.object({skipInstall:L.boolean().optional().default(!1).describe(`Skip installing dependencies automatically. Never do this unless you are sure the project is already installed.`),addAliases:L.boolean().optional().default(!0).describe(`Add shell aliases (tm, taskmaster, hamster, ham) to shell config file.`),initGit:L.boolean().optional().default(!0).describe(`Initialize Git repository in project root.`),storeTasksInGit:L.boolean().optional().default(!0).describe(`Store tasks in Git (tasks.json and tasks/ directory).`),yes:L.boolean().optional().default(!0).describe(`Skip prompts and use default values. Always set to true for MCP tools.`),projectRoot:L.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:L.array(L.enum(j)).optional().describe(`List of rule profiles to include at initialization. If omitted, defaults to Cursor profile only. Available options: ${j.join(`, `)}`)}),annotations:{title:`Initialize Project`,destructiveHint:!0},execute:X(async(e,t)=>{let{log:n}=t,r=t.session;try{return n.info(`Executing initialize_project tool with args: ${JSON.stringify(e)}`),J({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),q(t,{details:e.stack})}})})}function Pn(e){e.addTool({name:`list_tags`,description:`List all available tags with task counts and metadata`,parameters:L.object({showMetadata:L.boolean().optional().describe(`Whether to include metadata in the output (default: false)`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`List Tags`,readOnlyHint:!0},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(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:L.object({setMain:L.string().optional().describe(`Set the primary model for task generation/updates. Model provider API key is required in the MCP config ENV.`),setResearch:L.string().optional().describe(`Set the model for research-backed operations. Model provider API key is required in the MCP config ENV.`),setFallback:L.string().optional().describe(`Set the model to use if the primary fails. Model provider API key is required in the MCP config ENV.`),listAvailableModels:L.boolean().optional().describe(`List all available models not currently in use. Input/output costs values are in dollars (3 is $3.00).`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),openrouter:L.boolean().optional().describe(`Indicates the set model ID is a custom OpenRouter model.`),ollama:L.boolean().optional().describe(`Indicates the set model ID is a custom Ollama model.`),bedrock:L.boolean().optional().describe(`Indicates the set model ID is a custom AWS Bedrock model.`),azure:L.boolean().optional().describe(`Indicates the set model ID is a custom Azure OpenAI model.`),vertex:L.boolean().optional().describe(`Indicates the set model ID is a custom Google Vertex AI model.`),"openai-compatible":L.boolean().optional().describe(`Indicates the set model ID is a custom OpenAI-compatible model. Requires baseURL parameter.`),baseURL:L.string().optional().describe(`Custom base URL for providers that support it (e.g., https://api.example.com/v1).`)}),annotations:{title:`Models`,destructiveHint:!0},execute:Z(`models`,async(e,t)=>{try{return t.log.info(`Starting models tool with args: ${JSON.stringify(e)}`),J({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}`),q(e.message)}})})}function In(e){e.addTool({name:`move_task`,description:`Move a task or subtask to a new position`,parameters:L.object({from:L.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:L.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:L.string().optional().describe(`Custom path to tasks.json file`),projectRoot:L.string().describe(`Root directory of the project (typically derived from session)`),tag:L.string().optional().describe(`Tag context to operate on`),fromTag:L.string().optional().describe(`Source tag for cross-tag moves`),toTag:L.string().optional().describe(`Target tag for cross-tag moves`),withDependencies:L.boolean().optional().describe(`Move dependent tasks along with main task`),ignoreDependencies:L.boolean().optional().describe(`Break cross-tag dependencies during move`)}),annotations:{title:`Move Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{if(e.fromTag&&e.toTag&&e.fromTag!==e.toTag){if(!e.from)return q(`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),J({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 q(`Destination ID is required for within-tag moves`,`MISSING_DESTINATION_ID`);let r=i({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 i=[],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:r,generateFiles:f},t,{session:n});p.success?i.push(p.data):t.error(`Failed to move ${u} to ${d}: ${p.error.message}`)}return J({result:{success:!0,data:{moves:i,skipped:c.length>0?c:void 0,message:`Successfully moved ${i.length} tasks${c.length>0?`, skipped ${c.length}`:``}`}},log:t,errorPrefix:`Error moving multiple tasks`,projectRoot:e.projectRoot})}return J({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 J({result:await an({sourceId:e.from,destinationId:e.to,tasksJsonPath:a,projectRoot:e.projectRoot,tag:r,generateFiles:!0},t,{session:n}),log:t,errorPrefix:`Error moving task`,projectRoot:e.projectRoot})}}catch(e){return q(`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:L.object({file:L.string().optional().describe(`Absolute path to the tasks file`),complexityReport:L.string().optional().describe(`Path to the complexity report file (relative to project root or absolute)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Next Task`,readOnlyHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Finding next task with args: ${JSON.stringify(e)}`);let r=i({projectRoot:e.projectRoot,tag:e.tag}),a;try{a=ue(e,n)}catch(e){return t.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let o;try{o=de({...e,tag:r},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:r},t,{session:n});return t.info(`Next task result: ${s.success?`found`:`none`}`),J({result:s,log:t,errorPrefix:`Error finding next task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error finding next task: ${e.message}`),q(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 ${a} directory.`,parameters:L.object({input:L.string().optional().default(re).describe(`Absolute path to the PRD document file (.txt, .md, etc.)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`),destination:L.enum([`local`,`hamster`]).optional().default(`local`).describe(`Where to parse the PRD: "local" writes tasks.json, "hamster" creates a cloud brief and tasks`),output:L.string().optional().describe(`Output path for tasks.json file (default: ${o})`),numTasks:L.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:L.boolean().optional().default(!1).describe(`Overwrite existing output file without prompting.`),research:L.boolean().optional().describe(`Enable Taskmaster to use the research role for potentially more informed task generation. Requires appropriate API key.`),append:L.boolean().optional().describe(`Append generated tasks to existing file.`)}),annotations:{title:`Parse PRD`,destructiveHint:!0},execute:X(async(e,{log:t,session:n,reportProgress:r})=>{try{let a=i({projectRoot:e.projectRoot,tag:e.tag}),o=ft(r,t);return J({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}`),q(`Failed to parse PRD: ${e.message}`)}})})}function zn(e){e.addTool({name:`remove_dependency`,description:`Remove a dependency from a task`,parameters:L.object({id:L.string().describe(`Task ID to remove dependency from`),dependsOn:L.string().describe(`Task ID to remove as a dependency`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Remove Dependency`,destructiveHint:!0},execute:Z(`remove-dependency`,async(e,t)=>{try{let n=i({projectRoot:e.projectRoot,tag:e.tag});t.log.info(`Removing dependency for task ${e.id} from ${e.dependsOn} with args: ${JSON.stringify(e)}`);let r;try{r=E({projectRoot:e.projectRoot,file:e.file},t.log)}catch(e){return t.log.error(`Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await ln({tasksJsonPath:r,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}`),J({result:a,log:t.log,errorPrefix:`Error removing dependency`,projectRoot:e.projectRoot})}catch(e){return t.log.error(`Error in removeDependency tool: ${e.message}`),q(e.message)}})})}function Bn(e){e.addTool({name:`remove_subtask`,description:`Remove a subtask from its parent task`,parameters:L.object({id:L.string().describe(`Subtask ID to remove in format 'parentId.subtaskId' (required)`),convert:L.boolean().optional().describe(`Convert the subtask to a standalone task instead of deleting it`),file:L.string().optional().describe(`Absolute path to the tasks file (default: tasks/tasks.json)`),skipGenerate:L.boolean().optional().describe(`Skip regenerating task files`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Remove Subtask`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{let r=i({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}`),q(`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:r},t,{session:n});return o.success?t.info(`Subtask removed successfully: ${o.data.message}`):t.error(`Failed to remove subtask: ${o.error.message}`),J({result:o,log:t,errorPrefix:`Error removing subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in removeSubtask tool: ${e.message}`),q(e.message)}})})}function Vn(e){e.addTool({name:`remove_task`,description:`Remove a task or subtask permanently from the tasks list`,parameters:L.object({id:L.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:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),confirm:L.boolean().optional().describe(`Whether to skip confirmation prompt (default: false)`),tag:L.string().optional().describe(`Specify which tag context to operate on. Defaults to the current active tag.`)}),annotations:{title:`Remove Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Removing task(s) with ID(s): ${e.id}`);let r=i({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}`),q(`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:r},t,{session:n});return o.success?t.info(`Successfully removed task: ${e.id}`):t.error(`Failed to remove task: ${o.error.message}`),J({result:o,log:t,errorPrefix:`Error removing task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in remove-task tool: ${e.message}`),q(`Failed to remove task: ${e.message}`)}})})}function Hn(e){e.addTool({name:`rename_tag`,description:`Rename an existing tag`,parameters:L.object({oldName:L.string().describe(`Current name of the tag to rename`),newName:L.string().describe(`New name for the tag`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Rename Tag`,destructiveHint:!0},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(e.message)}})})}function Un(e){e.addTool({name:`research`,description:`Perform AI-powered research queries with project context`,parameters:L.object({query:L.string().describe(`Research query/prompt (required)`),taskIds:L.string().optional().describe(`Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17")`),filePaths:L.string().optional().describe(`Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md")`),customContext:L.string().optional().describe(`Additional custom context text to include in the research`),includeProjectTree:L.boolean().optional().describe(`Include project file tree structure in context (default: false)`),detailLevel:L.enum([`low`,`medium`,`high`]).optional().describe(`Detail level for the research response (default: medium)`),saveTo:L.string().optional().describe(`Automatically save research results to specified task/subtask ID (e.g., "15" or "15.2")`),saveToFile:L.boolean().optional().describe(`Save research results to .taskmaster/docs/research/ directory (default: false)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Research`,destructiveHint:!0,openWorldHint:!0},execute:X(async(e,{log:t,session:n})=>{try{let r=i({projectRoot:e.projectRoot,tag:e.tag});return t.info(`Starting research with query: "${e.query.substring(0,100)}${e.query.length>100?`...`:``}"`),J({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:r},t,{session:n}),log:t,errorPrefix:`Error performing research`,projectRoot:e.projectRoot})}catch(e){return t.error(`Error in research tool: ${e.message}`),q(e.message)}})})}async function Wn(e,t,n={}){let{projectRoot:r,language:i}=e,a=O(t);t.info(`Executing response-language_direct with args: ${JSON.stringify(e)}`),t.info(`Using project root: ${r}`);try{return x(),Ue(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:L.object({projectRoot:L.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:L.string().describe(`The new response language to set. like "中文" "English" or "español".`)}),annotations:{title:`Response Language`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{return t.info(`Executing response-language tool with args: ${JSON.stringify(e)}`),J({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}`),q(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===A.REMOVE){if(!a&&Ge(r,n)){let e=We(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(!k(e)){o.push({profileName:e,success:!1,error:`The requested rule profile for '${e}' is unavailable. Supported profiles are: ${j.join(`, `)}.`});continue}let t=qe(r,Je(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===A.ADD){for(let e of n){if(!k(e)){s.push({profileName:e,success:!1,error:`Profile not found: static import missing for '${e}'. Valid profiles: ${j.join(`, `)}`});continue}let t=Je(e),{success:n,failed:i}=Ye(r,t),a=t.rulesDir,o=F.join(r,a),c=t.profileDir,l=t.mcpConfig!==!1,u=l&&t.mcpConfigPath?F.join(r,t.mcpConfigPath):null,d=l&&u?P.existsSync(u):void 0,f=P.existsSync(o),p=P.existsSync(F.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 "${A.ADD}" or "${A.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:L.object({action:L.enum([`add`,`remove`]).describe(`Whether to add or remove rule profiles.`),profiles:L.array(L.enum(j)).min(1).describe(`List of rule profiles to add or remove (e.g., [\"cursor\", \"roo\"]). Available options: ${j.join(`, `)}`),projectRoot:L.string().describe(`The root directory of the project. Must be an absolute path.`),force:L.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:X(async(e,{log:t,session:n})=>{try{return t.info(`[rules tool] Executing action: ${e.action} for profiles: ${e.profiles.join(`, `)} in ${e.projectRoot}`),J({result:await Kn(e,t,{session:n}),log:t,projectRoot:e.projectRoot})}catch(e){return t.error(`[rules tool] Error: ${e.message}`),q(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:L.object({id:L.string().describe(`Comma-separated list of task IDs to scope down (e.g., "1,3,5")`),strength:L.string().optional().describe(`Strength level: light, regular, or heavy (default: regular)`),prompt:L.string().optional().describe(`Custom prompt for specific scoping adjustments`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`),research:L.boolean().optional().describe(`Whether to use research capabilities for scoping`)}),annotations:{title:`Scope Down Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Starting scope-down with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({result:await mn({tasksJsonPath:a,id:e.id,strength:e.strength,prompt:e.prompt,research:e.research,projectRoot:e.projectRoot,tag:r},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}`),q(e.message)}})})}function Yn(e){e.addTool({name:`scope_up_task`,description:`Increase the complexity of one or more tasks using AI`,parameters:L.object({id:L.string().describe(`Comma-separated list of task IDs to scope up (e.g., "1,3,5")`),strength:L.string().optional().describe(`Strength level: light, regular, or heavy (default: regular)`),prompt:L.string().optional().describe(`Custom prompt for specific scoping adjustments`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`),research:L.boolean().optional().describe(`Whether to use research capabilities for scoping`)}),annotations:{title:`Scope Up Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{try{t.info(`Starting scope-up with args: ${JSON.stringify(e)}`);let r=i({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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({result:await hn({tasksJsonPath:a,id:e.id,strength:e.strength,prompt:e.prompt,research:e.research,projectRoot:e.projectRoot,tag:r},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}`),q(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:L.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:L.string().optional().describe(`Information to add to the subtask. Required unless only updating metadata.`),research:L.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),metadata:L.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:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Subtask`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{let r=`update_subtask`;try{let a=i({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(`${r}: Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let s=Q(e.metadata,q);if(s.error)return s.error;let c=s.parsedMetadata;if(!e.prompt&&!c)return q(`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`}`),J({result:l,log:t,errorPrefix:`Error updating subtask`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${r} tool execute: ${e.message}`),q(`Internal tool error (${r}): ${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:L.object({id:L.string().describe(`ID of the task (e.g., '15') to update. Subtasks are supported using the update-subtask tool.`),prompt:L.string().optional().describe(`New information or context to incorporate into the task. Required unless only updating metadata.`),research:L.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),append:L.boolean().optional().describe(`Append timestamped information to task details instead of full update`),metadata:L.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:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Task`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{let r=`update_task`;try{let a=i({projectRoot:e.projectRoot,tag:e.tag});t.info(`Executing ${r} tool with args: ${JSON.stringify(e)}`);let o;try{o=E({projectRoot:e.projectRoot,file:e.file},t),t.info(`${r}: Resolved tasks path: ${o}`)}catch(e){return t.error(`${r}: Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json: ${e.message}`)}let s=Q(e.metadata,q);if(s.error)return s.error;let c=s.parsedMetadata;if(!e.prompt&&!c)return q(`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(`${r}: Direct function result: success=${l.success}`),J({result:l,log:t,errorPrefix:`Error updating task`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${r} tool execute: ${e.message}`),q(`Internal tool error (${r}): ${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:L.object({from:L.string().describe(`Task ID from which to start updating (inclusive). IMPORTANT: This tool uses 'from', not 'id'`),prompt:L.string().describe(`Explanation of changes or new context to apply`),research:L.boolean().optional().describe(`Use Perplexity AI for research-backed updates`),file:L.string().optional().describe(`Path to the tasks file relative to project root`),projectRoot:L.string().optional().describe(`The directory of the project. (Optional, usually from session)`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Update Tasks`,destructiveHint:!0},execute:X(async(e,{log:t,session:n})=>{let r=`update`,{from:a,prompt:o,research:s,file:c,projectRoot:l,tag:u}=e,d=i({projectRoot:e.projectRoot,tag:e.tag});try{t.info(`Executing ${r} tool with normalized root: ${l}`);let i;try{i=E({projectRoot:l,file:c},t),t.info(`${r}: Resolved tasks path: ${i}`)}catch(e){return t.error(`${r}: Error finding tasks.json: ${e.message}`),q(`Failed to find tasks.json within project root '${l}': ${e.message}`)}let u=await vn({tasksJsonPath:i,from:a,prompt:o,research:s,projectRoot:l,tag:d},t,{session:n});return t.info(`${r}: Direct function result: success=${u.success}`),J({result:u,log:t,errorPrefix:`Error updating tasks`,projectRoot:e.projectRoot})}catch(e){return t.error(`Critical error in ${r} tool execute: ${e.message}`),q(`Internal tool error (${r}): ${e.message}`)}})})}function $n(e){e.addTool({name:`use_tag`,description:`Switch to a different tag context for task operations`,parameters:L.object({name:L.string().describe(`Name of the tag to switch to`),file:L.string().optional().describe(`Path to the tasks file (default: tasks/tasks.json)`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`)}),annotations:{title:`Use Tag`,destructiveHint:!0},execute:X(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}`),q(`Failed to find tasks.json: ${e.message}`)}return J({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}`),q(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:L.object({file:L.string().optional().describe(`Absolute path to the tasks file`),projectRoot:L.string().describe(`The directory of the project. Must be an absolute path.`),tag:L.string().optional().describe(`Tag context to operate on`)}),annotations:{title:`Validate Dependencies`,readOnlyHint:!0},execute:Z(`validate-dependencies`,async(e,{log:t,session:n})=>{try{let n=i({projectRoot:e.projectRoot,tag:e.tag});t.info(`Validating dependencies 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}`),q(`Failed to find tasks.json: ${e.message}`)}let a=await bn({tasksJsonPath:r,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}`),J({result:a,log:t,errorPrefix:`Error validating dependencies`,projectRoot:e.projectRoot,tag:n})}catch(e){return t.error(`Error in validateDependencies tool: ${e.message}`),q(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`}}}R.config(),ie();const or=Ze(import.meta.url);F.dirname(or);var sr=class{constructor(){this.options={name:`Task Master MCP Server`,version:d};let e=new Qe(this.options);if(e._mcpServer&&z.wrapMcpServerWithSentry)try{e._mcpServer=z.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 dt;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()}};R.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-CEEU0EI1.js";import{Bt as t,E 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,qt as p,vt as m,yt as h}from"./config-manager-Bl_NTZXB.js";import{r as g}from"./git-utils-DllbRE35.js";import{Ct as _,St as v,Tt as y,x as ee}from"./dependency-manager-Di3zHzuM.js";import*as b from"node:path";import x from"chalk";import S from"fs";import C from"path";import{randomUUID as w}from"crypto";import T from"os";import*as E from"node:fs";import*as te from"node:os";import{execSync as D}from"child_process";import{fileURLToPath as ne}from"url";import O from"boxen";import k from"readline";import re from"figlet";import ie from"gradient-string";import ae from"inquirer";import oe from"ora";import se from"open";const A=[`amp`,`claude`,`cline`,`codex`,`cursor`,`gemini`,`kiro`,`opencode`,`kilo`,`roo`,`trae`,`vscode`,`windsurf`,`zed`],ce=[`architect`,`ask`,`orchestrator`,`code`,`debug`,`test`],j=`# Task files`,M=`tasks.json`,N=`tasks/`;function le(e){return e.trim().replace(/^#/,``).trim()}function P(e){let t=le(e);return t===M||t===N}function ue(e,t){return e.map(e=>{if(P(e)){let n=le(e),r=e.match(/\s*$/)[0];return t?`# ${n}${r}`:`${n}${r}`}return e})}function de(e){let t=[],n=!1;for(let r of e){if(r.trim()===j){n=!0;continue}P(r)||n&&!r.trim()||(n&&r.trim()&&!P(r)&&(n=!1),n||t.push(r))}return t}function fe(e,t){return e.filter(e=>{let n=e.trim();return!n||P(e)||n===j?!1:!t.has(n)})}function pe(e){let t=[j];return e?t.push(`# ${M}`,`# ${N} `):t.push(M,`${N} `),t}function me(e){if(e.some(e=>e.trim())){let t=e[e.length-1];t&&t.trim()&&e.push(``)}}function he(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 ge(e,t,n){try{S.writeFileSync(e,t.join(`
1
+ import{c as e}from"./ai-services-unified-D_pA4zzB.js";import{Bt as t,E 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,qt as p,vt as m,yt as h}from"./config-manager-Dn_JApjY.js";import{r as g}from"./git-utils-DllbRE35.js";import{Ct as _,St as v,Tt as y,x as ee}from"./dependency-manager-DCJfWg5J.js";import*as b from"node:path";import x from"chalk";import S from"fs";import C from"path";import{randomUUID as w}from"crypto";import T from"os";import*as E from"node:fs";import*as te from"node:os";import{execSync as D}from"child_process";import{fileURLToPath as ne}from"url";import O from"boxen";import k from"readline";import re from"figlet";import ie from"gradient-string";import ae from"inquirer";import oe from"ora";import se from"open";const A=[`amp`,`claude`,`cline`,`codex`,`cursor`,`gemini`,`kiro`,`opencode`,`kilo`,`roo`,`trae`,`vscode`,`windsurf`,`zed`],ce=[`architect`,`ask`,`orchestrator`,`code`,`debug`,`test`],j=`# Task files`,M=`tasks.json`,N=`tasks/`;function le(e){return e.trim().replace(/^#/,``).trim()}function P(e){let t=le(e);return t===M||t===N}function ue(e,t){return e.map(e=>{if(P(e)){let n=le(e),r=e.match(/\s*$/)[0];return t?`# ${n}${r}`:`${n}${r}`}return e})}function de(e){let t=[],n=!1;for(let r of e){if(r.trim()===j){n=!0;continue}P(r)||n&&!r.trim()||(n&&r.trim()&&!P(r)&&(n=!1),n||t.push(r))}return t}function fe(e,t){return e.filter(e=>{let n=e.trim();return!n||P(e)||n===j?!1:!t.has(n)})}function pe(e){let t=[j];return e?t.push(`# ${M}`,`# ${N} `):t.push(M,`${N} `),t}function me(e){if(e.some(e=>e.trim())){let t=e[e.length-1];t&&t.trim()&&e.push(``)}}function he(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 ge(e,t,n){try{S.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 _e(e,t,n,r){try{let i=de(S.readFileSync(e,`utf8`).split(`
4
4
  `)),a=fe(t,new Set(i.map(e=>e.trim()).filter(e=>e))),o=[...i];a.length>0&&(me(o),o.push(...a)),me(o),o.push(...pe(n)),S.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 ae.prompt([{type:`list`,name:`storageType`,message:x.white(`How do you want to build it?
3511
3511
  `),choices:[{name:[x.bold(`Solo (Taskmaster)`),``,x.white(` • Parse your own PRDs into structured task lists and build with any IDE or background agents`),x.white(` • Agents execute tasks with precision, no scope creep, no going off-track`),x.white(` • Tasks live in a local JSON file, everything stays in your repo`),x.white(` • Upgrade to Hamster to bring the Taskmaster experience to your team`),``].join(`
3512
3512
  `),value:`local`,short:`Solo (Taskmaster)`},{name:[x.bold(`Together (Hamster)`),``,x.white(` • Write a brief with your team. Hamster refines it into a plan.`),x.white(` • Your team drafts, refines, and aligns on the same page before executing`),x.white(` • One brief, one plan, one source of truth for execution`),x.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 bn(e,n,s,d,f,h=A,_=`local`,v=null){let y=process.cwd();X(`debug`,`Initializing project in ${y}`),Z(C.join(y,u)),Z(C.join(y,i)),Z(C.join(y,a)),Z(C.join(y,l)),Z(C.join(y,p)),hn(y);let b={year:new Date().getFullYear()},S=_===`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`,C.join(y,c),b),Q(`config.json`,C.join(y,t),{...b});let T=C.join(y,t);dn(T)?X(`debug`,`Updated config with correct maxTokens values`):X(`debug`,`Could not update maxTokens in config`),vn(T,_,v);try{let e=L(`gitignore`,`utf8`);ve(C.join(y,o),e,s,X)}catch(e){X(`error`,`Failed to create .gitignore: ${e.message}`)}Q(`example_prd.txt`,C.join(y,r)),Q(`example_prd_rpg.txt`,C.join(y,p,`example_prd_rpg.txt`));try{n===!1?X(`info`,`Git initialization skipped due to --no-git flag.`):n===!0?g()?X(`debug`,`Existing Git repository detected – skipping git init despite --git flag.`):(X(`info`,`Initializing Git repository due to --git flag...`),D(`git init`,{cwd:y,stdio:`ignore`}),X(`success`,`Git repository initialized`)):g()?X(`debug`,`Existing Git repository detected – skipping git init.`):(X(`info`,`No Git repository detected. Initializing one in project root...`),D(`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 h)w(e)}e&&mn();let E={cwd:y,stdio:`inherit`};if(m()&&(E.stdio=`ignore`,X(`info`,`Running npm install silently...`)),f.shouldSetupRules&&!m()&&!d&&!f?.yes&&!f.rulesExplicitlyProvided){console.log(O(x.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{D(`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 m()||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-DQanNEl4.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 m()&&!d?X(`debug`,`Skipping response language setup in silent (MCP) mode.`):d&&X(`debug`,`DRY RUN: Skipping response language setup.`);if(!m()&&!d&&!f?.yes&&_===`local`){console.log(O(x.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{D(`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 _===`cloud`&&!d?console.log(O(x.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 bn(e,n,s,d,f,h=A,_=`local`,v=null){let y=process.cwd();X(`debug`,`Initializing project in ${y}`),Z(C.join(y,u)),Z(C.join(y,i)),Z(C.join(y,a)),Z(C.join(y,l)),Z(C.join(y,p)),hn(y);let b={year:new Date().getFullYear()},S=_===`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`,C.join(y,c),b),Q(`config.json`,C.join(y,t),{...b});let T=C.join(y,t);dn(T)?X(`debug`,`Updated config with correct maxTokens values`):X(`debug`,`Could not update maxTokens in config`),vn(T,_,v);try{let e=L(`gitignore`,`utf8`);ve(C.join(y,o),e,s,X)}catch(e){X(`error`,`Failed to create .gitignore: ${e.message}`)}Q(`example_prd.txt`,C.join(y,r)),Q(`example_prd_rpg.txt`,C.join(y,p,`example_prd_rpg.txt`));try{n===!1?X(`info`,`Git initialization skipped due to --no-git flag.`):n===!0?g()?X(`debug`,`Existing Git repository detected – skipping git init despite --git flag.`):(X(`info`,`Initializing Git repository due to --git flag...`),D(`git init`,{cwd:y,stdio:`ignore`}),X(`success`,`Git repository initialized`)):g()?X(`debug`,`Existing Git repository detected – skipping git init.`):(X(`info`,`No Git repository detected. Initializing one in project root...`),D(`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 h)w(e)}e&&mn();let E={cwd:y,stdio:`inherit`};if(m()&&(E.stdio=`ignore`,X(`info`,`Running npm install silently...`)),f.shouldSetupRules&&!m()&&!d&&!f?.yes&&!f.rulesExplicitlyProvided){console.log(O(x.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{D(`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 m()||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-B4B6uk8r.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 m()&&!d?X(`debug`,`Skipping response language setup in silent (MCP) mode.`):d&&X(`debug`,`DRY RUN: Skipping response language setup.`);if(!m()&&!d&&!f?.yes&&_===`local`){console.log(O(x.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{D(`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 _===`cloud`&&!d?console.log(O(x.green.bold(`✓ AI Models Managed by Hamster - go ham!
3514
3514
 
3515
3515
  `)+x.white(`Hamster handles all AI model configuration for you.
3516
3516
  `)+x.dim(`• Optimized model selection for your tasks
@@ -0,0 +1 @@
1
+ import"./ai-services-unified-D_pA4zzB.js";import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{A as e}from"./dependency-manager-DCJfWg5J.js";import"./response-language-DeTA_0Bx.js";export{e as performResearch};
@@ -0,0 +1 @@
1
+ import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import{t as e}from"./response-language-DeTA_0Bx.js";export{e as default};
@@ -1 +1 @@
1
- import{B as e,X as t,f as n,q as r,yt as i}from"./config-manager-Bl_NTZXB.js";function a(a,o={}){let{mcpLog:s,projectRoot:c}=o,l=(e,...t)=>{s&&typeof s[e]==`function`&&s[e](...t)},u=t(null,{projectRoot:c}),d=e(c);if(i(`debug`,`Checking for config file using findConfigPath, found: ${u}`),i(`debug`,`Checking config file using isConfigFilePresent(), exists: ${d}`),!d)return{success:!1,error:{code:`CONFIG_MISSING`,message:`The configuration file is missing. Run "task-master init" to create it.`}};if(typeof a!=`string`||a.trim()===``)return{success:!1,error:{code:`INVALID_RESPONSE_LANGUAGE`,message:`Invalid response language: ${a}. Must be a non-empty string.`}};try{let e=n(c);return e.global.responseLanguage=a,r(e,c)?{success:!0,data:{responseLanguage:a,message:successMessage}}:{success:!1,error:{code:`WRITE_ERROR`,message:`Error writing updated configuration to configuration file`}}}catch(e){return l(`error`,`Error setting response language: ${e.message}`),{success:!1,error:{code:`SET_RESPONSE_LANGUAGE_ERROR`,message:e.message}}}}var o=a;export{o as t};
1
+ import{B as e,X as t,f as n,q as r,yt as i}from"./config-manager-Dn_JApjY.js";function a(a,o={}){let{mcpLog:s,projectRoot:c}=o,l=(e,...t)=>{s&&typeof s[e]==`function`&&s[e](...t)},u=t(null,{projectRoot:c}),d=e(c);if(i(`debug`,`Checking for config file using findConfigPath, found: ${u}`),i(`debug`,`Checking config file using isConfigFilePresent(), exists: ${d}`),!d)return{success:!1,error:{code:`CONFIG_MISSING`,message:`The configuration file is missing. Run "task-master init" to create it.`}};if(typeof a!=`string`||a.trim()===``)return{success:!1,error:{code:`INVALID_RESPONSE_LANGUAGE`,message:`Invalid response language: ${a}. Must be a non-empty string.`}};try{let e=n(c);return e.global.responseLanguage=a,r(e,c)?{success:!0,data:{responseLanguage:a,message:successMessage}}:{success:!1,error:{code:`WRITE_ERROR`,message:`Error writing updated configuration to configuration file`}}}catch(e){return l(`error`,`Error setting response language: ${e.message}`),{success:!1,error:{code:`SET_RESPONSE_LANGUAGE_ERROR`,message:e.message}}}}var o=a;export{o as t};
@@ -1 +1 @@
1
- import{U as e,r as t}from"./config-manager-Bl_NTZXB.js";import{createHash as n}from"crypto";import*as r from"@sentry/node";let i=!1;function a(e){if(e)return n(`sha256`).update(e).digest(`hex`).substring(0,8)}function o(n={}){if(i)return;e(!0);try{if(!t(n.projectRoot)){console.log(`✓ Anonymous telemetry disabled per user preference. Set anonymousTelemetry: true in .taskmaster/config.json to re-enable.`);return}}catch{}finally{e(!1)}let a=n.dsn||`https://ce8c03ca1dd0da5b9837c6ba1b3a0f9d@o4510099843776512.ingest.us.sentry.io/4510381945585664`;if(a)try{r.init({dsn:a,environment:n.environment||process.env.NODE_ENV||`production`,integrations:[r.vercelAIIntegration({recordInputs:!0,recordOutputs:!0}),r.zodErrorsIntegration()],tracesSampleRate:n.tracesSampleRate??1,sendDefaultPii:n.sendDefaultPii??!0,debug:process.env.SENTRY_DEBUG===`true`}),i=!0,process.env.SENTRY_DEBUG===`true`&&(console.log(` DSN: ${a.substring(0,40)}...`),console.log(` Environment: ${n.environment||process.env.NODE_ENV||`production`}`),console.log(` Traces Sample Rate: ${n.tracesSampleRate??1}`))}catch(e){console.error(`Failed to initialize telemetry: ${e.message}`)}}function s(e,t={}){if(!i)return process.env.SENTRY_DEBUG===`true`&&console.log(`⚠️ Sentry not initialized, telemetry config not available`),null;let n={isEnabled:!0,recordInputs:!0,recordOutputs:!0};return e&&(n.functionId=e),Object.keys(t).length>0&&(n.metadata={},t.command&&(n.metadata.command=t.command),t.outputType&&(n.metadata.outputType=t.outputType),t.tag&&(n.metadata.tag=t.tag),t.taskId&&(n.metadata.taskId=t.taskId),t.userId&&(n.metadata.userId=t.userId),t.briefId&&(n.metadata.briefId=t.briefId),t.projectHash&&(n.metadata.projectHash=t.projectHash)),process.env.SENTRY_DEBUG===`true`&&console.log(`📊 Sentry telemetry config created:`,JSON.stringify(n,null,2)),n}export{a as n,o as r,s as t};
1
+ import{U as e,r as t}from"./config-manager-Dn_JApjY.js";import{createHash as n}from"crypto";import*as r from"@sentry/node";let i=!1;function a(e){if(e)return n(`sha256`).update(e).digest(`hex`).substring(0,8)}function o(n={}){if(i)return;e(!0);try{if(!t(n.projectRoot)){console.log(`✓ Anonymous telemetry disabled per user preference. Set anonymousTelemetry: true in .taskmaster/config.json to re-enable.`);return}}catch{}finally{e(!1)}let a=n.dsn||`https://ce8c03ca1dd0da5b9837c6ba1b3a0f9d@o4510099843776512.ingest.us.sentry.io/4510381945585664`;if(a)try{r.init({dsn:a,environment:n.environment||process.env.NODE_ENV||`production`,integrations:[r.vercelAIIntegration({recordInputs:!0,recordOutputs:!0}),r.zodErrorsIntegration()],tracesSampleRate:n.tracesSampleRate??1,sendDefaultPii:n.sendDefaultPii??!0,debug:process.env.SENTRY_DEBUG===`true`}),i=!0,process.env.SENTRY_DEBUG===`true`&&(console.log(` DSN: ${a.substring(0,40)}...`),console.log(` Environment: ${n.environment||process.env.NODE_ENV||`production`}`),console.log(` Traces Sample Rate: ${n.tracesSampleRate??1}`))}catch(e){console.error(`Failed to initialize telemetry: ${e.message}`)}}function s(e,t={}){if(!i)return process.env.SENTRY_DEBUG===`true`&&console.log(`⚠️ Sentry not initialized, telemetry config not available`),null;let n={isEnabled:!0,recordInputs:!0,recordOutputs:!0};return e&&(n.functionId=e),Object.keys(t).length>0&&(n.metadata={},t.command&&(n.metadata.command=t.command),t.outputType&&(n.metadata.outputType=t.outputType),t.tag&&(n.metadata.tag=t.tag),t.taskId&&(n.metadata.taskId=t.taskId),t.userId&&(n.metadata.userId=t.userId),t.briefId&&(n.metadata.briefId=t.briefId),t.projectHash&&(n.metadata.projectHash=t.projectHash)),process.env.SENTRY_DEBUG===`true`&&console.log(`📊 Sentry telemetry config created:`,JSON.stringify(n,null,2)),n}export{a as n,o as r,s as t};
@@ -0,0 +1 @@
1
+ import"./ai-services-unified-D_pA4zzB.js";import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{ct as e,dt as t,ft as n,ht as r,lt as i,mt as a,pt as o,st as s,ut as c}from"./dependency-manager-DCJfWg5J.js";import"./response-language-DeTA_0Bx.js";export{s as copyTag,e as createTag,i as createTagFromBranch,c as deleteTag,t as renameTag,n as switchCurrentTag,o as tags,a as updateBranchTagMapping,r as useTag};
@@ -1 +1 @@
1
- import"./ai-services-unified-CEEU0EI1.js";import{dt as e,wt as t}from"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";import"./sentry-Bfs4ROUL.js";import{$ as n,A as r,C as i,D as a,E as o,I as s,J as c,K as l,L as u,M as d,N as f,O as p,P as m,Q as h,S as g,T as _,X as v,Y as y,Z as b,gt as x,j as S,k as C,q as w,w as T}from"./dependency-manager-Di3zHzuM.js";import{t as E}from"./response-language-c-DJJiVH.js";export{n as addSubtask,h as addTask,b as analyzeTaskComplexity,v as clearSubtasks,c as expandAllTasks,y as expandTask,x as findNextTask,e as findTaskById,w as isTaskDependentOn,l as listTasks,u as migrateProject,s as moveTask,m as parsePRD,r as performResearch,t as readComplexityReport,f as removeSubtask,S as removeTask,a as scopeDownTask,p as scopeUpTask,E as setResponseLanguage,_ as setTaskStatus,d as taskExists,o as updateSingleTaskStatus,T as updateSubtaskById,i as updateTaskById,g as updateTasks,C as validateStrength};
1
+ import"./ai-services-unified-D_pA4zzB.js";import{dt as e,wt as t}from"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{$ as n,A as r,C as i,D as a,E as o,I as s,J as c,K as l,L as u,M as d,N as f,O as p,P as m,Q as h,S as g,T as _,X as v,Y as y,Z as b,gt as x,j as S,k as C,q as w,w as T}from"./dependency-manager-DCJfWg5J.js";import{t as E}from"./response-language-DeTA_0Bx.js";export{n as addSubtask,h as addTask,b as analyzeTaskComplexity,v as clearSubtasks,c as expandAllTasks,y as expandTask,x as findNextTask,e as findTaskById,w as isTaskDependentOn,l as listTasks,u as migrateProject,s as moveTask,m as parsePRD,r as performResearch,t as readComplexityReport,f as removeSubtask,S as removeTask,a as scopeDownTask,p as scopeUpTask,E as setResponseLanguage,_ as setTaskStatus,d as taskExists,o as updateSingleTaskStatus,T as updateSubtaskById,i as updateTaskById,g as updateTasks,C as validateStrength};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{U as e,cn as t,hn as n}from"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";import{r}from"./sentry-Bfs4ROUL.js";import{join as i}from"node:path";import a from"dotenv";const o=process.cwd(),s=t();a.config({path:i(s,`.env`)}),r({projectRoot:s}),process.env.TASKMASTER_ORIGINAL_CWD=o,process.env.DEBUG===`1`&&console.error(`DEBUG - dev.js received args:`,process.argv.slice(2));try{await n.getInstance().hasValidSession()&&e(!0)}catch{e(!1)}const{runCLI:c}=await import(`./commands-Dmu6mYBF.js`);c(process.argv);export{};
2
+ import{U as e,cn as t,hn as n}from"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import{r}from"./sentry-Dbx7-h6F.js";import{join as i}from"node:path";import a from"dotenv";const o=process.cwd(),s=t();a.config({path:i(s,`.env`)}),r({projectRoot:s}),process.env.TASKMASTER_ORIGINAL_CWD=o,process.env.DEBUG===`1`&&console.error(`DEBUG - dev.js received args:`,process.argv.slice(2));try{await n.getInstance().hasValidSession()&&e(!0)}catch{e(!1)}const{runCLI:c}=await import(`./commands-Y2xHjinr.js`);c(process.argv);export{};
@@ -0,0 +1 @@
1
+ import"./ai-services-unified-D_pA4zzB.js";import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{w as e}from"./dependency-manager-DCJfWg5J.js";import"./response-language-DeTA_0Bx.js";export{e as default};
@@ -0,0 +1 @@
1
+ import"./ai-services-unified-D_pA4zzB.js";import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{C as e}from"./dependency-manager-DCJfWg5J.js";import"./response-language-DeTA_0Bx.js";export{e as default};
@@ -1 +1 @@
1
- import{At as e,Ct as t,Dt as n,Et as r,Mt as i,Ot as a,St as o,Tt as s,_t as c,at as l,bt as u,ct as d,dt as f,ft as p,gt as m,ht as h,it as g,jt as _,kt as v,lt as y,mt as b,nt as x,ot as S,pt as C,rt as w,st as T,ut as E,vt as D,wt as O,xt as k,yt as A}from"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";export{x as LOG_LEVELS,w as addComplexityToTask,g as aggregateTelemetry,l as createStateJson,S as disableSilentMode,T as enableSilentMode,d as ensureTagMetadata,y as findCycles,E as findProjectRoot,f as findTaskById,p as findTaskInComplexityReport,C as flattenTasksWithSubtasks,b as formatTaskId,h as getCurrentTag,m as getTasksForTag,c as isEmpty,D as isSilentMode,A as log,u as markMigrationForNotice,k as migrateConfigJson,o as normalizeTaskIds,t as performCompleteTagMigration,O as readComplexityReport,s as readJSON,r as resolveEnvVariable,n as resolveTag,a as taskExists,v as traverseDependencies,e as truncate,_ as withFileLockSync,i as writeJSON};
1
+ import{At as e,Ct as t,Dt as n,Et as r,Mt as i,Ot as a,St as o,Tt as s,_t as c,at as l,bt as u,ct as d,dt as f,ft as p,gt as m,ht as h,it as g,jt as _,kt as v,lt as y,mt as b,nt as x,ot as S,pt as C,rt as w,st as T,ut as E,vt as D,wt as O,xt as k,yt as A}from"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";export{x as LOG_LEVELS,w as addComplexityToTask,g as aggregateTelemetry,l as createStateJson,S as disableSilentMode,T as enableSilentMode,d as ensureTagMetadata,y as findCycles,E as findProjectRoot,f as findTaskById,p as findTaskInComplexityReport,C as flattenTasksWithSubtasks,b as formatTaskId,h as getCurrentTag,m as getTasksForTag,c as isEmpty,D as isSilentMode,A as log,u as markMigrationForNotice,k as migrateConfigJson,o as normalizeTaskIds,t as performCompleteTagMigration,O as readComplexityReport,s as readJSON,r as resolveEnvVariable,n as resolveTag,a as taskExists,v as traverseDependencies,e as truncate,_ as withFileLockSync,i as writeJSON};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hhsw2015/task-master-ai",
3
- "version": "0.43.7",
3
+ "version": "0.43.9",
4
4
  "description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{a as e,i as t,n,r,t as i}from"./ai-services-unified-CEEU0EI1.js";import"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";import"./sentry-Bfs4ROUL.js";export{i as generateObjectService,n as generateTextService,r as logAiUsage,t as streamObjectService,e as streamTextService};
@@ -1,7 +0,0 @@
1
- import{A as e,C as t,D as n,Et as r,F as i,H as a,I as o,J as s,M as c,N as l,P as u,S as d,T as f,_ as p,a as m,b as h,d as g,ht as ee,j as _,l as v,o as te,p as y,s as ne,ut as b,v as x,yt as S}from"./config-manager-Bl_NTZXB.js";import{n as C,t as w}from"./sentry-Bfs4ROUL.js";import{createRequire as T}from"node:module";import{promises as E}from"fs";import{join as D}from"path";import{homedir as O}from"os";import{execSync as k,spawn as A}from"child_process";import*as j from"ai";import{jsonrepair as M}from"jsonrepair";import{EnvHttpProxyAgent as re}from"undici";import{createAnthropic as N}from"@ai-sdk/anthropic";import{createPerplexity as P}from"@ai-sdk/perplexity";import{createGoogleGenerativeAI as ie}from"@ai-sdk/google";import{createOpenAI as ae}from"@ai-sdk/openai";import{createXai as oe}from"@ai-sdk/xai";import{createGroq as se}from"@ai-sdk/groq";import{createOpenRouter as ce}from"@openrouter/ai-sdk-provider";import{createOllama as le}from"ollama-ai-provider-v2";import{createAmazonBedrock as ue}from"@ai-sdk/amazon-bedrock";import{fromNodeProviderChain as de}from"@aws-sdk/credential-providers";import{createAzure as fe}from"@ai-sdk/azure";import{createVertex as pe}from"@ai-sdk/google-vertex";import{createClaudeCode as me}from"ai-sdk-provider-claude-code";import{createGeminiProvider as he}from"ai-sdk-provider-gemini-cli";import{APICallError as F,LoadAPIKeyError as ge,NoSuchModelError as I}from"@ai-sdk/provider";import{generateId as L}from"@ai-sdk/provider-utils";import{parse as _e}from"jsonc-parser";import{createCodexCli as ve}from"ai-sdk-provider-codex-cli";import{createOpenAICompatible as ye}from"@ai-sdk/openai-compatible";var be=Object.defineProperty,xe=e=>{let t={};for(var n in e)be(t,n,{get:e[n],enumerable:!0});return t},R=T(import.meta.url);let z=null;var B=class e{constructor(){this._providers=new Map,this._initialized=!1}static getInstance(){return z||=new e,z}initialize(){return this._initialized||=!0,this}registerProvider(e,t,n={}){if(!e||typeof e!=`string`)throw Error(`Provider name must be a non-empty string`);if(!t)throw Error(`Provider instance is required`);if(typeof t.generateText!=`function`||typeof t.streamText!=`function`||typeof t.generateObject!=`function`)throw Error(`Provider must implement BaseAIProvider interface`);return this._providers.set(e,{instance:t,options:n,registeredAt:new Date}),this}hasProvider(e){return this._providers.has(e)}getProvider(e){let t=this._providers.get(e);return t?t.instance:null}getAllProviders(){return new Map(this._providers)}unregisterProvider(e){return this._providers.has(e)?(this._providers.delete(e),!0):!1}reset(){this._providers.clear(),this._initialized=!1}};B.getInstance().initialize();var V=B;const{JSONParseError:Se,NoObjectGeneratedError:Ce,generateObject:we,generateText:Te,streamObject:Ee,streamText:De,zodSchema:Oe}=j,H=j.jsonSchema,ke=new Set([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`]),Ae=[`additionalProperties`,`contains`,`if`,`then`,`else`,`not`,`propertyNames`],je=[`allOf`,`anyOf`,`oneOf`,`prefixItems`],Me=[`definitions`,`$defs`,`dependentSchemas`,`patternProperties`,`properties`],Ne=e=>e?Array.isArray(e)?e.includes(`integer`):e===`integer`:!1,U=e=>{if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return e.map(U);let t={...e};if(Ne(t.type))for(let e of ke)e in t&&delete t[e];for(let e of Ae)t[e]&&(t[e]=U(t[e]));for(let e of je)Array.isArray(t[e])&&(t[e]=t[e].map(U));for(let e of Me)if(t[e]&&typeof t[e]==`object`){let n={};for(let[r,i]of Object.entries(t[e]))n[r]=U(i);t[e]=n}return t.items&&=U(t.items),t},W=e=>{if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return e.map(W);let t={};for(let[n,r]of Object.entries(e))t[n]=W(r);let n=t.type===`object`,r=t.properties&&typeof t.properties==`object`&&!Array.isArray(t.properties),i=Object.prototype.hasOwnProperty.call(t,`additionalProperties`);return n&&r&&!i&&(t.additionalProperties=!1),t},G=e=>{let t=Oe(e);if(!t||typeof t!=`object`||!t.jsonSchema)return t;let n=W(U(t.jsonSchema));return typeof H==`function`?H(n,{validate:t.validate}):{...t,jsonSchema:n}};var K=class e{constructor(){if(this.constructor===e)throw Error(`BaseAIProvider cannot be instantiated directly`);this.name=this.constructor.name,this._proxyAgent=null,this.needsExplicitJsonSchema=!1,this.supportsTemperature=!0}validateAuth(e){if(!e.apiKey)throw Error(`${this.name} API key is required`)}createProxyFetch(){this._projectRoot||=b();let e=this._projectRoot;if(a(null,e))return this._proxyAgent||=new re,(e,t={})=>fetch(e,{...t,dispatcher:this._proxyAgent})}validateParams(e){if(this.validateAuth(e),!e.modelId)throw Error(`${this.name} Model ID is required`);this.validateOptionalParams(e)}validateOptionalParams(e){if(e.temperature!==void 0&&(e.temperature<0||e.temperature>1))throw Error(`Temperature must be between 0 and 1`);if(e.maxTokens!==void 0){let t=Number(e.maxTokens);if(!Number.isFinite(t)||t<=0)throw Error(`maxTokens must be a finite number greater than 0`)}}validateMessages(e){if(!e||!Array.isArray(e)||e.length===0)throw Error(`Invalid or empty messages array provided`);for(let t of e)if(!t.role||!t.content)throw Error(`Invalid message format. Each message must have role and content`)}handleError(e,t){let n=t.message||`Unknown error occurred`;throw S(`error`,`${this.name} ${e} failed: ${n}`,{error:t}),Error(`${this.name} API error during ${e}: ${n}`)}getClient(e){throw Error(`getClient must be implemented by provider`)}isRequiredApiKey(){return!0}getRequiredApiKeyName(){throw Error(`getRequiredApiKeyName must be implemented by provider`)}prepareTokenParam(e,t){return t===void 0?{}:{maxOutputTokens:Math.floor(Number(t))}}async generateText(e){try{this.validateParams(e),this.validateMessages(e.messages),S(`debug`,`Generating ${this.name} text with model: ${e.modelId}`);let t=await this.getClient(e),n=e.commandName||`unknown`,r=w(`${this.name}.${e.modelId}.${n}.generateText`,{command:n,outputType:e.outputType,tag:e.tag,projectHash:C(e.projectRoot),userId:e.userId,briefId:e.briefId}),i=await Te({model:t(e.modelId),messages:e.messages,...this.prepareTokenParam(e.modelId,e.maxTokens),...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{},...r&&{experimental_telemetry:r}});S(`debug`,`${this.name} generateText completed successfully for model: ${e.modelId}`);let a=i.usage?.inputTokens??i.usage?.promptTokens??0,o=i.usage?.outputTokens??i.usage?.completionTokens??0,s=i.usage?.totalTokens??a+o;return{text:i.text,usage:{inputTokens:a,outputTokens:o,totalTokens:s}}}catch(e){this.handleError(`text generation`,e)}}async streamText(e){try{this.validateParams(e),this.validateMessages(e.messages),S(`debug`,`Streaming ${this.name} text with model: ${e.modelId}`);let t=await this.getClient(e),n=e.commandName||`unknown`,r=w(`${this.name}.${e.modelId}.${n}.streamText`,{command:n,outputType:e.outputType,tag:e.tag,projectHash:C(e.projectRoot),userId:e.userId,briefId:e.briefId}),i=await De({model:t(e.modelId),messages:e.messages,...this.prepareTokenParam(e.modelId,e.maxTokens),...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{},...r&&{experimental_telemetry:r},...e.experimental_transform&&{experimental_transform:e.experimental_transform}});return S(`debug`,`${this.name} streamText initiated successfully for model: ${e.modelId}`),i}catch(e){this.handleError(`text streaming`,e)}}async streamObject(e){try{if(this.validateParams(e),this.validateMessages(e.messages),!e.schema)throw Error(`Schema is required for object streaming`);S(`debug`,`Streaming ${this.name} object with model: ${e.modelId}`);let t=await this.getClient(e),n=e.commandName||`unknown`,r=w(`${this.name}.${e.modelId}.${n}.streamObject`,{command:n,outputType:e.outputType,tag:e.tag,projectHash:C(e.projectRoot),userId:e.userId,briefId:e.briefId}),i=G(e.schema),a=await Ee({model:t(e.modelId),messages:e.messages,schema:i,mode:e.mode||`auto`,maxOutputTokens:e.maxTokens,...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{},...r&&{experimental_telemetry:r}});return S(`debug`,`${this.name} streamObject initiated successfully for model: ${e.modelId}`),a}catch(e){this.handleError(`object streaming`,e)}}async generateObject(e){try{if(this.validateParams(e),this.validateMessages(e.messages),!e.schema)throw Error(`Schema is required for object generation`);if(!e.objectName)throw Error(`Object name is required for object generation`);S(`debug`,`Generating ${this.name} object ('${e.objectName}') with model: ${e.modelId}`);let t=await this.getClient(e),n=e.commandName||`unknown`,r=w(`${this.name}.${e.modelId}.${n}.generateObject.${e.objectName}`,{command:n,outputType:e.outputType,tag:e.tag,projectHash:C(e.projectRoot),userId:e.userId,briefId:e.briefId}),i=G(e.schema),a=await we({model:t(e.modelId),messages:e.messages,schema:i,mode:this.needsExplicitJsonSchema?`json`:`auto`,schemaName:e.objectName,schemaDescription:`Generate a valid JSON object for ${e.objectName}`,maxTokens:e.maxTokens,...this.supportsTemperature&&e.temperature!==void 0?{temperature:e.temperature}:{},...r&&{experimental_telemetry:r}});S(`debug`,`${this.name} generateObject completed successfully for model: ${e.modelId}`);let o=a.usage?.inputTokens??a.usage?.promptTokens??0,s=a.usage?.outputTokens??a.usage?.completionTokens??0,c=a.usage?.totalTokens??o+s;return{object:a.object,usage:{inputTokens:o,outputTokens:s,totalTokens:c}}}catch(e){if(Ce.isInstance(e)&&e.cause instanceof Se&&e.cause.text){S(`warn`,`${this.name} generated malformed JSON, attempting to repair...`);try{let t=M(e.cause.text),n=JSON.parse(t);return S(`info`,`Successfully repaired ${this.name} JSON output`),{object:n,usage:{inputTokens:e.usage?.promptTokens||e.usage?.inputTokens||0,outputTokens:e.usage?.completionTokens||e.usage?.outputTokens||0,totalTokens:e.usage?.totalTokens||0}}}catch(e){S(`error`,`Failed to repair ${this.name} JSON: ${e.message}`)}}this.handleError(`object generation`,e)}}},Pe=class extends K{constructor(){super(),this.name=`Anthropic`}getRequiredApiKeyName(){return`ANTHROPIC_API_KEY`}getClient(e){try{let{apiKey:t,baseURL:n}=e,r=this.createProxyFetch();return N({apiKey:t,...n&&{baseURL:n},headers:{"anthropic-beta":`output-128k-2025-02-19`},...r&&{fetch:r}})}catch(e){this.handleError(`client initialization`,e)}}},Fe=class extends K{constructor(){super(),this.name=`Perplexity`}getRequiredApiKeyName(){return`PERPLEXITY_API_KEY`}getClient(e){try{let{apiKey:t,baseURL:n}=e,r=this.createProxyFetch();return P({apiKey:t,baseURL:n||`https://api.perplexity.ai`,...r&&{fetch:r}})}catch(e){this.handleError(`client initialization`,e)}}async generateObject(e){return super.generateObject({...e,mode:`json`})}},Ie=class extends K{constructor(){super(),this.name=`Google`}getRequiredApiKeyName(){return`GOOGLE_API_KEY`}getClient(e){try{let{apiKey:t,baseURL:n}=e,r=this.createProxyFetch();return ie({apiKey:t,...n&&{baseURL:n},...r&&{fetch:r}})}catch(e){this.handleError(`client initialization`,e)}}},Le=class extends K{constructor(){super(),this.name=`OpenAI`}getRequiredApiKeyName(){return`OPENAI_API_KEY`}getClient(e){try{let{apiKey:t,baseURL:n}=e,r=this.createProxyFetch();return ae({apiKey:t,...n&&{baseURL:n},...r&&{fetch:r}})}catch(e){this.handleError(`client initialization`,e)}}},Re=class extends K{constructor(){super(),this.name=`xAI`}getRequiredApiKeyName(){return`XAI_API_KEY`}getClient(e){try{let{apiKey:t,baseURL:n}=e;return oe({apiKey:t,baseURL:n||`https://api.x.ai/v1`})}catch(e){this.handleError(`client initialization`,e)}}},ze=class extends K{constructor(){super(),this.name=`Groq`}getRequiredApiKeyName(){return`GROQ_API_KEY`}getClient(e){try{let{apiKey:t,baseURL:n}=e;return se({apiKey:t,...n&&{baseURL:n}})}catch(e){this.handleError(`client initialization`,e)}}},Be=class extends K{constructor(){super(),this.name=`OpenRouter`}getRequiredApiKeyName(){return`OPENROUTER_API_KEY`}getClient(e){try{let{apiKey:t,baseURL:n}=e;return ce({apiKey:t,...n&&{baseURL:n}})}catch(e){this.handleError(`client initialization`,e)}}},Ve=class extends K{constructor(){super(),this.name=`Ollama`}validateAuth(e){}getClient(e){try{let{baseURL:t}=e;return le({...t&&{baseURL:t}})}catch(e){this.handleError(`client initialization`,e)}}isRequiredApiKey(){return!1}getRequiredApiKeyName(){return`OLLAMA_API_KEY`}},He=class extends K{constructor(){super(),this.name=`Bedrock`}isRequiredApiKey(){return!1}getRequiredApiKeyName(){return`AWS_ACCESS_KEY_ID`}validateAuth(e){}getClient(e){try{let e=de(),t=this.createProxyFetch();return ue({credentialProvider:e,...t&&{fetch:t}})}catch(e){this.handleError(`client initialization`,e)}}},Ue=class extends K{constructor(){super(),this.name=`Azure OpenAI`}getRequiredApiKeyName(){return`AZURE_OPENAI_API_KEY`}validateAuth(e){if(!e.apiKey)throw Error(`Azure API key is required`);if(!e.baseURL)throw Error(`Azure endpoint URL is required. Set it in .taskmasterconfig global.azureBaseURL or models.[role].baseURL`)}normalizeBaseURL(e){if(!e)return e;try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return n.endsWith(`/openai`)||(n=`${n}/openai`),t.pathname=n,t.toString()}catch{let t=e.replace(/\/+$/,``);return t.endsWith(`/openai`)?t:`${t}/openai`}}getClient(e){try{let{apiKey:t,baseURL:n}=e,r=this.normalizeBaseURL(n),i=this.createProxyFetch();return fe({apiKey:t,baseURL:r,...i&&{fetch:i}})}catch(e){this.handleError(`client initialization`,e)}}},q=class extends Error{constructor(e){super(e),this.name=`VertexAuthError`,this.code=`vertex_auth_error`}},J=class extends Error{constructor(e){super(e),this.name=`VertexConfigError`,this.code=`vertex_config_error`}},We=class extends Error{constructor(e,t){super(e),this.name=`VertexApiError`,this.code=`vertex_api_error`,this.statusCode=t}},Ge=class extends K{constructor(){super(),this.name=`Google Vertex AI`}getRequiredApiKeyName(){return`GOOGLE_API_KEY`}isRequiredApiKey(){return!1}isAuthenticationRequired(){return!0}isValidCredential(e){return e?typeof e==`string`?e.trim().length>0:typeof e==`object`:!1}validateAuth(e){let{apiKey:t,projectId:n,location:r,credentials:i}=e,a=this.isValidCredential(t),o=this.isValidCredential(i);if(!a&&!o)throw new q(`Vertex AI requires authentication. Provide one of the following:
2
- • GOOGLE_API_KEY environment variable (typical for API-based auth), OR
3
- • GOOGLE_APPLICATION_CREDENTIALS pointing to a service account JSON file (recommended for production)`);if(!n||typeof n==`string`&&n.trim().length===0)throw new J(`Google Cloud project ID is required for Vertex AI. Set VERTEX_PROJECT_ID environment variable.`);if(!r||typeof r==`string`&&r.trim().length===0)throw new J(`Google Cloud location is required for Vertex AI. Set VERTEX_LOCATION environment variable (e.g., "us-central1").`)}getClient(e){try{let{apiKey:t,projectId:n,location:r,credentials:i,baseURL:a}=e,o=this.createProxyFetch(),s={};return t?s.googleAuthOptions={...i,apiKey:t}:i&&(s.googleAuthOptions=i),pe({...s,project:n,location:r,...a&&{baseURL:a},...o&&{fetch:o}})}catch(e){this.handleError(`client initialization`,e)}}handleError(e,t){if(S(`error`,`Vertex AI ${e} error:`,t),t.name===`VertexAuthError`||t.name===`VertexConfigError`||t.name===`VertexApiError`)throw t;if(t.response){let e=t.response.status,n=t.response.data?.error?.message||t.message;throw e===401||e===403?new q(`Authentication failed: ${n}`):e===400?new J(`Invalid request: ${n}`):new We(`API error (${e}): ${n}`,e)}throw Error(`Vertex AI ${e} failed: ${t.message}`)}};let Y=!1;var Ke=class extends K{constructor(){super(),this.name=`Claude Code`,this.supportedModels=l(`claude-code`),this.supportedModels.length===0&&S(`warn`,`No supported models found for claude-code provider. Check supported-models.json configuration.`),this.needsExplicitJsonSchema=!0,this.supportsTemperature=!1}getRequiredApiKeyName(){return`CLAUDE_CODE_API_KEY`}isRequiredApiKey(){return!1}validateAuth(e){if(process.env.NODE_ENV!==`test`&&!Y&&!process.env.CLAUDE_CODE_OAUTH_TOKEN)try{k(`claude --version`,{stdio:`pipe`,timeout:1e3})}catch{S(`warn`,`Claude Code CLI not detected. Install it with: npm install -g @anthropic-ai/claude-code`)}finally{Y=!0}}getClient(e={}){try{let t=v(e.commandName)||{},n=process.env.ANTHROPIC_API_KEY,r=process.env.CLAUDE_CODE_API_KEY;try{return r?process.env.ANTHROPIC_API_KEY=r:n&&delete process.env.ANTHROPIC_API_KEY,me({defaultSettings:{systemPrompt:{type:`preset`,preset:`claude_code`},settingSources:[`user`,`project`,`local`],...t}})}finally{n?process.env.ANTHROPIC_API_KEY=n:delete process.env.ANTHROPIC_API_KEY}}catch(e){let t=String(e?.message||``);if(e?.code===`ENOENT`||/claude/i.test(t)){let t=Error(`Claude Code CLI not available. Please install Claude Code CLI first. Original error: ${e.message}`);t.cause=e,this.handleError(`Claude Code CLI initialization`,t)}else this.handleError(`client initialization`,e)}}getSupportedModels(){return this.supportedModels}isModelSupported(e){return e?this.supportedModels.includes(String(e).toLowerCase()):!1}},qe=class extends K{constructor(){super(),this.name=`Gemini CLI`,this.supportsTemperature=!1}validateAuth(e){}async getClient(e){try{let t={};return t=e.apiKey&&e.apiKey!==`gemini-cli-no-key-required`?{authType:`api-key`,apiKey:e.apiKey}:{authType:`oauth-personal`},e.baseURL&&(t.baseURL=e.baseURL),he(t)}catch(e){this.handleError(`client initialization`,e)}}getRequiredApiKeyName(){return`GEMINI_API_KEY`}isRequiredApiKey(){return!1}};function X({message:e,code:t,exitCode:n,stderr:r,stdout:i,promptExcerpt:a,isRetryable:o=!1}){return new F({message:e,isRetryable:o,url:`grok-cli://command`,requestBodyValues:a?{prompt:a}:void 0,data:{code:t,exitCode:n,stderr:r,stdout:i,promptExcerpt:a}})}function Z({message:e}){return new ge({message:e||`Authentication failed. Please ensure Grok CLI is properly configured with API key.`})}function Je({message:e,promptExcerpt:t,timeoutMs:n}){return new F({message:e,isRetryable:!0,url:`grok-cli://command`,requestBodyValues:t?{prompt:t}:void 0,data:{code:`TIMEOUT`,promptExcerpt:t,timeoutMs:n}})}function Ye({message:e}){return new F({message:e||`Grok CLI is not installed or not found in PATH. Please install with: npm install -g @vibe-kit/grok-cli`,isRetryable:!1,url:`grok-cli://installation`,requestBodyValues:void 0})}function Xe(e){let t=e.trim(),n=/```(?:json)?\s*([\s\S]*?)\s*```/i.exec(t);n&&(t=n[1]);let r=/^\s*(?:const|let|var)\s+\w+\s*=\s*([\s\S]*)/i.exec(t);r&&(t=r[1],t.trim().endsWith(`;`)&&(t=t.trim().slice(0,-1)));let i=t.indexOf(`{`),a=t.indexOf(`[`);if(i===-1&&a===-1)return e;let o=a===-1?i:i===-1?a:Math.min(i,a);t=t.slice(o);let s=e=>{let t=[];try{let n=_e(e,t,{allowTrailingComma:!0});if(t.length===0)return JSON.stringify(n,null,2)}catch{}},c=s(t);if(c!==void 0)return c;let l=t[0],u=l===`{`?`}`:`]`,d=[],f=0,p=!1,m=!1;for(let e=0;e<t.length;e++){let n=t[e];if(m){m=!1;continue}if(n===`\\`){m=!0;continue}if(n===`"`&&!p){p=!0;continue}if(n===`"`&&p){p=!1;continue}p||(n===l?f++:n===u&&(f--,f===0&&d.push(e+1)))}for(let e=d.length-1;e>=0;e--){let n=s(t.slice(0,d[e]));if(n!==void 0)return n}let h=Math.max(0,t.length-1e3);for(let e=t.length-1;e>h;e--){let n=s(t.slice(0,e));if(n!==void 0)return n}return e}function Ze(e){return e.map(e=>{let t=``;return typeof e.content==`string`?t=e.content:Array.isArray(e.content)?t=e.content.filter(e=>e.type===`text`).map(e=>e.text||``).join(`
4
- `):e.content&&typeof e.content==`object`&&(t=e.content.text||JSON.stringify(e.content)),{role:e.role,content:t.trim()}})}function Qe(e){try{let t=e.trim().split(`
5
- `).filter(e=>e.trim()),n=[];for(let e of t)try{let t=JSON.parse(e);n.push(t)}catch{continue}let r=n.filter(e=>e.role===`assistant`).pop();return r&&r.content?{text:r.content,usage:r.usage?{promptTokens:r.usage.prompt_tokens||0,completionTokens:r.usage.completion_tokens||0,totalTokens:r.usage.total_tokens||0}:void 0}:{text:e.trim(),usage:void 0}}catch{return{text:e.trim(),usage:void 0}}}function $e(e){return Ze(e).map(e=>{switch(e.role){case`system`:return`System: ${e.content}`;case`user`:return`User: ${e.content}`;case`assistant`:return`Assistant: ${e.content}`;default:return`${e.role}: ${e.content}`}}).join(`
6
-
7
- `)}function et(e){return typeof e!=`string`&&(e=String(e)),`'`+e.replace(/'/g,`'\\''`)+`'`}var tt=class{specificationVersion=`v2`;defaultObjectGenerationMode=`json`;supportsImageUrls=!1;supportsStructuredOutputs=!1;supportedUrls={};modelId;settings;constructor(e){if(this.modelId=e.id,this.settings=e.settings??{},!this.modelId||typeof this.modelId!=`string`||this.modelId.trim()===``)throw new I({modelId:this.modelId,modelType:`languageModel`})}get provider(){return`grok-cli`}async checkGrokCliInstallation(){return new Promise(e=>{let t=A(`grok`,[`--version`],{stdio:`pipe`});t.on(`error`,()=>e(!1)),t.on(`exit`,t=>e(t===0))})}async getApiKey(){if(this.settings.apiKey)return this.settings.apiKey;if(process.env.GROK_CLI_API_KEY)return process.env.GROK_CLI_API_KEY;try{let e=D(O(),`.grok`,`user-settings.json`),t=await E.readFile(e,`utf8`);return JSON.parse(t).apiKey||null}catch{return null}}async executeGrokCli(e,t={}){let n=12e4;this.modelId.includes(`grok-4`)&&(n=6e5);let r=t.timeout??this.settings.timeout??n;return new Promise((n,i)=>{let a=A(`grok`,e,{stdio:`pipe`,cwd:this.settings.workingDirectory||process.cwd(),env:t.apiKey===void 0?process.env:{...process.env,GROK_CLI_API_KEY:t.apiKey}}),o=``,s=``,c;r>0&&(c=setTimeout(()=>{a.kill(`SIGTERM`),i(Je({message:`Grok CLI command timed out after ${r}ms`,timeoutMs:r,promptExcerpt:e.join(` `).substring(0,200)}))},r)),a.stdout?.on(`data`,e=>{let t=e.toString();o+=t}),a.stderr?.on(`data`,e=>{let t=e.toString();s+=t}),a.on(`error`,e=>{c&&clearTimeout(c),e.code===`ENOENT`?i(Ye({})):i(X({message:`Failed to execute Grok CLI: ${e.message}`,code:e.code,stderr:e.message,isRetryable:!1}))}),a.on(`exit`,e=>{c&&clearTimeout(c),n({stdout:o.trim(),stderr:s.trim(),exitCode:e||0})})})}generateAllWarnings(e,t){let n=[],r=[];if(e.temperature!==void 0&&r.push(`temperature`),e.topP!==void 0&&r.push(`topP`),e.topK!==void 0&&r.push(`topK`),e.presencePenalty!==void 0&&r.push(`presencePenalty`),e.frequencyPenalty!==void 0&&r.push(`frequencyPenalty`),e.stopSequences!==void 0&&e.stopSequences.length>0&&r.push(`stopSequences`),e.seed!==void 0&&r.push(`seed`),r.length>0)for(let e of r)n.push({type:`unsupported-setting`,setting:e,details:`Grok CLI does not support the ${e} parameter. It will be ignored.`});return(!this.modelId||this.modelId.trim()===``)&&n.push({type:`other`,message:`Model ID is empty or invalid`}),(!t||t.trim()===``)&&n.push({type:`other`,message:`Prompt is empty`}),n}async doGenerate(e){if(e.abortSignal?.aborted)throw e.abortSignal.reason||Error(`Request aborted`);if(!await this.checkGrokCliInstallation())throw Ye({});let t=await this.getApiKey();if(!t)throw Z({message:`Grok CLI API key not found. Set GROK_CLI_API_KEY environment variable or configure grok-cli.`});let n=$e(e.prompt),r=this.generateAllWarnings(e,n),i=[`--prompt`,et(n)];this.modelId&&this.modelId!==`default`&&i.push(`--model`,this.modelId),this.settings.baseURL&&i.push(`--base-url`,this.settings.baseURL),this.settings.workingDirectory&&i.push(`--directory`,this.settings.workingDirectory);try{let a=await this.executeGrokCli(i,{apiKey:t});if(a.exitCode!==0)throw a.stderr.toLowerCase().includes(`unauthorized`)||a.stderr.toLowerCase().includes(`authentication`)?Z({message:`Grok CLI authentication failed: ${a.stderr}`}):X({message:`Grok CLI failed with exit code ${a.exitCode}: ${a.stderr||`Unknown error`}`,exitCode:a.exitCode,stderr:a.stderr,stdout:a.stdout,promptExcerpt:n.substring(0,200),isRetryable:!1});let o=Qe(a.stdout),s=o.text||``;return(e=>!!e&&typeof e==`object`&&`mode`in e&&e.mode?.type===`object-json`)(e)&&s&&(s=Xe(s)),{content:[{type:`text`,text:s||``}],usage:o.usage?{inputTokens:o.usage.promptTokens,outputTokens:o.usage.completionTokens,totalTokens:o.usage.totalTokens}:{inputTokens:0,outputTokens:0,totalTokens:0},finishReason:`stop`,rawCall:{rawPrompt:n,rawSettings:i},warnings:r,response:{id:L(),timestamp:new Date,modelId:this.modelId},request:{body:n},providerMetadata:{"grok-cli":{exitCode:a.exitCode,...a.stderr&&{stderr:a.stderr}}}}}catch(e){throw e.name===`APICallError`||e.name===`LoadAPIKeyError`?e:X({message:`Grok CLI execution failed: ${e.message}`,code:e.code,promptExcerpt:n.substring(0,200),isRetryable:!1})}}async doStream(e){let t=$e(e.prompt),n=this.generateAllWarnings(e,t);return{stream:new ReadableStream({start:async t=>{let r;try{if(e.abortSignal?.aborted)throw e.abortSignal.reason||Error(`Request aborted`);e.abortSignal&&(r=()=>{t.enqueue({type:`error`,error:e.abortSignal?.reason||Error(`Request aborted`)}),t.close()},e.abortSignal.addEventListener(`abort`,r,{once:!0})),t.enqueue({type:`stream-start`,warnings:n});let i=await this.doGenerate(e);t.enqueue({type:`response-metadata`,id:i.response.id,timestamp:i.response.timestamp,modelId:i.response.modelId});let a=i.content||[],o=a.length>0&&a[0].type===`text`?a[0].text:``,s;o.length>0&&(s=L(),t.enqueue({type:`text-start`,id:s}));for(let n=0;n<o.length;n+=50){if(e.abortSignal?.aborted)throw e.abortSignal.reason||Error(`Request aborted`);let r=o.slice(n,n+50);t.enqueue({type:`text-delta`,id:s,delta:r}),await new Promise(e=>setTimeout(e,20))}s&&t.enqueue({type:`text-end`,id:s}),t.enqueue({type:`finish`,finishReason:i.finishReason,usage:i.usage,providerMetadata:i.providerMetadata}),t.close()}catch(e){t.enqueue({type:`error`,error:e}),t.close()}finally{e.abortSignal&&r&&e.abortSignal.removeEventListener(`abort`,r)}},cancel:()=>{}}),request:{body:t}}}};function nt(e={}){let t=(t,n={})=>new tt({id:t,settings:{...e.defaultSettings,...n}}),n=function(e,n){if(new.target)throw Error(`The Grok CLI model function cannot be called with the new keyword.`);return t(e,n)};return n.languageModel=t,n.chat=t,n.textEmbeddingModel=e=>{throw new I({modelId:e,modelType:`textEmbeddingModel`})},n.imageModel=e=>{throw new I({modelId:e,modelType:`imageModel`})},n}nt();var rt=class extends K{constructor(){super(),this.name=`Grok CLI`,this.needsExplicitJsonSchema=!0,this.supportsTemperature=!1}getRequiredApiKeyName(){return`GROK_CLI_API_KEY`}isRequiredApiKey(){return!1}validateAuth(e){}getClient(e){try{let{apiKey:t,baseURL:n,workingDirectory:r,timeout:i,commandName:a}=e,o=h(a);return nt({defaultSettings:{apiKey:t,baseURL:n,workingDirectory:r||o.workingDirectory,timeout:i||o.timeout,defaultModel:o.defaultModel}})}catch(e){this.handleError(`client initialization`,e)}}};const it={"gpt-5.1":[`none`,`low`,`medium`,`high`],"gpt-5.1-codex-max":[`none`,`low`,`medium`,`high`,`xhigh`],"gpt-5.2":[`none`,`low`,`medium`,`high`,`xhigh`],"gpt-5.3-codex":[`none`,`low`,`medium`,`high`,`xhigh`],"gpt-5.2-pro":[`medium`,`high`,`xhigh`],"gpt-5":[`none`,`low`,`medium`,`high`,`xhigh`]},at=[`none`,`low`,`medium`,`high`],ot=[`none`,`low`,`medium`,`high`,`xhigh`];var st=class extends K{constructor(){super(),this.name=`Codex CLI`,this.needsExplicitJsonSchema=!1,this.supportsTemperature=!1,this.supportedModels=l(`codex-cli`),this.supportedModels.length===0&&S(`warn`,`No supported models found for codex-cli provider. Check supported-models.json configuration.`),this._codexCliChecked=!1,this._codexCliAvailable=null}isRequiredApiKey(){return!1}getRequiredApiKeyName(){return`OPENAI_CODEX_API_KEY`}validateAuth(){if(process.env.NODE_ENV!==`test`&&!this._codexCliChecked)try{k(`codex --version`,{stdio:`pipe`,timeout:1e3}),this._codexCliAvailable=!0}catch{this._codexCliAvailable=!1,S(`warn`,`Codex CLI not detected. Install with: npm i -g @openai/codex or enable fallback with allowNpx.`)}finally{this._codexCliChecked=!0}}_getValidatedReasoningEffort(e,t){let n=it[e]||at,r=n.reduce((e,t)=>ot.indexOf(t)>ot.indexOf(e)?t:e,n[0]);return t?n.includes(t)?t:(S(`warn`,`Reasoning effort '${t}' not supported by ${e}. Using '${r}' instead.`),r):(S(`debug`,`No reasoning effort specified for ${e}. Using '${r}'.`),r)}getClient(e={}){try{let t=g(e.commandName)||{},n=this._getValidatedReasoningEffort(e.modelId,t.reasoningEffort);return ve({defaultSettings:{...t,reasoningEffort:n,...e.apiKey?{env:{...t.env||{},OPENAI_API_KEY:e.apiKey}}:{}}})}catch(e){let t=String(e?.message||``);if(e?.code===`ENOENT`||/codex/i.test(t)){let t=Error(`Codex CLI not available. Please install Codex CLI first. Original error: ${e.message}`);t.cause=e,this.handleError(`Codex CLI initialization`,t)}else this.handleError(`client initialization`,e)}}},Q=class extends K{constructor(e){if(super(),!e.name)throw Error(`Provider name is required`);if(!e.apiKeyEnvVar)throw Error(`API key environment variable name is required`);this.name=e.name,this.apiKeyEnvVar=e.apiKeyEnvVar,this.requiresApiKey=e.requiresApiKey!==!1,this.defaultBaseURL=e.defaultBaseURL,this.getBaseURLFromParams=e.getBaseURL,this.supportsStructuredOutputs=e.supportsStructuredOutputs}getRequiredApiKeyName(){return this.apiKeyEnvVar}isRequiredApiKey(){return this.requiresApiKey}validateAuth(e){if(this.requiresApiKey&&!e.apiKey)throw Error(`${this.name} API key is required`)}getBaseURL(e){return e.baseURL?e.baseURL:this.getBaseURLFromParams?this.getBaseURLFromParams(e):this.defaultBaseURL}getClient(e){try{let{apiKey:t}=e,n=this.createProxyFetch(),r=this.getBaseURL(e),i={name:this.name.toLowerCase().replace(/[^a-z0-9]/g,`-`)};return this.requiresApiKey&&t&&(i.apiKey=t),r&&(i.baseURL=r),this.supportsStructuredOutputs!==void 0&&(i.supportsStructuredOutputs=this.supportsStructuredOutputs),n&&(i.fetch=n),ye(i)}catch(e){this.handleError(`client initialization`,e)}}},ct=class extends Q{constructor(){super({name:`Z.ai`,apiKeyEnvVar:`ZAI_API_KEY`,requiresApiKey:!0,defaultBaseURL:`https://api.z.ai/api/paas/v4/`,supportsStructuredOutputs:!0})}prepareTokenParam(){return{}}findArrayPropertyInSchema(e){try{let t=e._zod.def;if(!(t?.type===`object`||t?.typeName===`ZodObject`))return null;let n=t.shape;if(typeof n==`function`&&(n=n()),!n||typeof n!=`object`)return null;for(let[e,t]of Object.entries(n)){let n=t._zod.def;if(n?.type===`array`||n?.typeName===`ZodArray`)return e}return null}catch(e){return console.warn(`Failed to introspect Zod schema:`,e.message),null}}async generateObject(e){let t=await super.generateObject(e);if(Array.isArray(t.object)){let n=this.findArrayPropertyInSchema(e.schema);return n?{...t,object:{[n]:t.object}}:(console.warn(`GLM returned a bare array for '${e.objectName}' but could not determine wrapper property from schema. Using objectName as fallback.`),{...t,object:{[e.objectName]:t.object}})}return t}},lt=class extends ct{constructor(){super(),this.name=`Z.ai (Coding Plan)`,this.defaultBaseURL=`https://api.z.ai/api/coding/paas/v4/`}},ut=class extends Q{constructor(){super({name:`LM Studio`,apiKeyEnvVar:`LMSTUDIO_API_KEY`,requiresApiKey:!1,defaultBaseURL:`http://localhost:1234/v1`,supportsStructuredOutputs:!0})}};const dt={anthropic:new Pe,perplexity:new Fe,google:new Ie,zai:new ct,"zai-coding":new lt,lmstudio:new ut,openai:new Le,xai:new Re,groq:new ze,openrouter:new Be,ollama:new Ve,"openai-compatible":new Q({name:`OpenAI Compatible`,apiKeyEnvVar:`OPENAI_COMPATIBLE_API_KEY`,requiresApiKey:!0}),bedrock:new He,azure:new Ue,vertex:new Ge,"claude-code":new Ke,"codex-cli":new st,"gemini-cli":new qe,"grok-cli":new rt};function ft(e){if(dt[e])return dt[e];let t=V.getInstance();return t.hasProvider(e)?(S(`debug`,`Provider "${e}" found in dynamic registry`),t.getProvider(e)):null}function pt(e,t){let n={inputCost:0,outputCost:0,currency:`USD`,isUnknown:!1};if(!s||!s[e])return S(`warn`,`Provider "${e}" not found in MODEL_MAP. Cannot determine cost for model ${t}.`),{...n,isUnknown:!0};let r=s[e].find(e=>e.id===t);if(!r)return S(`debug`,`Model "${t}" not found under provider "${e}". Assuming unknown cost.`),{...n,isUnknown:!0};if(r.cost_per_1m_tokens===null)return S(`debug`,`Cost data is null for model "${t}" under provider "${e}". Pricing unknown.`),{...n,isUnknown:!0};if(r.cost_per_1m_tokens===void 0)return S(`debug`,`Cost data not found for model "${t}" under provider "${e}". Pricing unknown.`),{...n,isUnknown:!0};let i=r.cost_per_1m_tokens;return{inputCost:i.input||0,outputCost:i.output||0,currency:i.currency||`USD`,isUnknown:!1}}function mt(e,t,n,r){let i=(e||0)/1e6*n+(t||0)/1e6*r;return parseFloat(i.toFixed(6))}function ht(e){let t={currentTag:`master`,availableTags:[`master`]};try{return e?{currentTag:ee(e)||`master`,availableTags:gt(e)}:t}catch(e){return y()&&S(`debug`,`Error getting tag information: ${e.message}`),t}}function gt(e){let t=[`master`];try{let n=R(`path`),r=R(`fs`),i=n.join(e,`.taskmaster`,`tasks`,`tasks.json`);if(!r.existsSync(i))return t;let a=JSON.parse(r.readFileSync(i,`utf8`));if(!a||typeof a!=`object`)return t;let o=Object.keys(a).filter(e=>_t(a[e]));return o.length>0?o:t}catch(e){return y()&&S(`debug`,`Could not read tasks file for available tags: ${e.message}`),t}}function _t(e){return e&&typeof e==`object`&&Array.isArray(e.tasks)}function vt(e){let t=e.message?.toLowerCase()||``;return t.includes(`rate limit`)||t.includes(`overloaded`)||t.includes(`service temporarily unavailable`)||t.includes(`timeout`)||t.includes(`network error`)||e.status===429||e.status>=500}function yt(e){try{if(e?.data?.error?.message)return e.data.error.message;if(e?.error?.message)return e.error.message;if(typeof e?.responseBody==`string`)try{let t=JSON.parse(e.responseBody);if(t?.error?.message)return t.error.message}catch{}return typeof e?.message==`string`&&e.message?e.message:typeof e==`string`?e:`An unknown AI service error occurred.`}catch{return`Failed to extract error message.`}}function bt(n,r){return{main:{provider:t(r),modelId:d(r)},research:{provider:_(r),modelId:e(r)},fallback:{provider:x(r),modelId:p(r)}}[n]||null}function xt(e,t){let n=o(e)||r(`VERTEX_PROJECT_ID`,t,e),a=i(e)||r(`VERTEX_LOCATION`,t,e)||`us-central1`,s=r(`GOOGLE_APPLICATION_CREDENTIALS`,t,e);S(`debug`,`Using Vertex AI configuration: Project ID=${n}, Location=${a}`);let c=s?{keyFile:s}:void 0;return{projectId:n,location:a,...c&&{credentials:c}}}function St(e,t,n=null){let i=ft(e);if(!i)throw Error(`Unknown provider '${e}' for API key resolution.`);let a=i.getRequiredApiKeyName();if(a===null)return null;let o=r(a,t,n);if(!i.isRequiredApiKey())return o||null;if(!o)throw Error(`Required API key ${a} for provider '${e}' is not set in environment, session, or .env file.`);return o}async function Ct(e,t,n,r,i,a){let o=0,s=t;for(;o<=2;)try{y()&&S(`info`,`Attempt ${o+1}/3 calling ${s} (Provider: ${r}, Model: ${i}, Role: ${a})`);let c=await e[t](n);return y()&&S(`info`,`${s} succeeded for role ${a} (Provider: ${r}) on attempt ${o+1}`),c}catch(e){if(S(`warn`,`Attempt ${o+1} failed for role ${a} (${s} / ${r}): ${e.message}`),vt(e)&&o<2){o++;let e=1e3*2**(o-1);S(`info`,`Something went wrong on the provider side. Retrying in ${e/1e3}s...`),await new Promise(t=>setTimeout(t,e))}else throw S(`error`,`Something went wrong on the provider side. Max retries reached for role ${a} (${s} / ${r}).`),e}throw Error(`Exhausted all retries for role ${a} (${s} / ${r})`)}async function $(e,t){let{role:r,session:i,projectRoot:a,systemPrompt:o,prompt:s,schema:l,objectName:d,commandName:p,outputType:h,experimental_transform:g,...ee}=t;y()&&S(`info`,`${e}Service called`,{role:r,commandName:p,outputType:h,projectRoot:a});let _=a||b(),v=u(_),x=i?.user?.id||i?.userId,C=i?.context?.briefId||i?.briefId,w;r===`main`?w=[`main`,`fallback`,`research`]:r===`research`?w=[`research`,`fallback`,`main`]:r===`fallback`?w=[`fallback`,`main`,`research`]:(S(`warn`,`Unknown initial role: ${r}. Defaulting to main -> fallback -> research sequence.`),w=[`main`,`fallback`,`research`]);let T=null,E=`AI service call failed for all configured roles.`;for(let t of w){let r,u,y,b,w,D,O,k=null;try{S(`debug`,`New AI service call with role: ${t}`);let E=bt(t,_);if(!E){S(`error`,`Unknown role encountered in _unifiedServiceRunner: ${t}`),T||=Error(`Unknown AI role specified: ${t}`);continue}if(r=E.provider,u=E.modelId,!r||!u){S(`warn`,`Skipping role '${t}': Provider or Model ID not configured.`),T||=Error(`Configuration missing for role '${t}'. Provider: ${r}, Model: ${u}`);continue}if(w=ft(r?.toLowerCase()),!w){S(`warn`,`Skipping role '${t}': Provider '${r}' not supported.`),T||=Error(`Unsupported provider configured: ${r}`);continue}D=te(t,_),r?.toLowerCase()===`azure`&&!D?(D=m(_),S(`debug`,`Using global Azure base URL: ${D}`)):r?.toLowerCase()===`ollama`&&!D?(D=f(_),S(`debug`,`Using global Ollama base URL: ${D}`)):r?.toLowerCase()===`bedrock`&&!D&&(D=ne(_),S(`debug`,`Using global Bedrock base URL: ${D}`)),b=n(t,_),y=St(r?.toLowerCase(),i,_);let A={};r?.toLowerCase()===`vertex`&&(A=xt(_,i));let j=[],M=`${o} \n\n Always respond in ${c(_)}.`;if(j.push({role:`system`,content:M.trim()}),s)j.push({role:`user`,content:s});else throw Error(`User prompt content is missing.`);let re={apiKey:y,modelId:u,maxTokens:b.maxTokens,temperature:b.temperature,messages:j,...D&&{baseURL:D},...(e===`generateObject`||e===`streamObject`)&&{schema:l,objectName:d},...p&&{commandName:p},...h&&{outputType:h},...a&&{projectRoot:a},...x&&{userId:x},...C&&{briefId:C},...g&&{experimental_transform:g},...A,...ee};if(O=await Ct(w,e,re,r,u,t),v&&O&&O.usage)try{k=await Ot({userId:v,commandName:p,providerName:r,modelId:u,inputTokens:O.usage.inputTokens,outputTokens:O.usage.outputTokens,outputType:h})}catch{}else v&&O&&!O.usage&&S(`warn`,`Cannot log telemetry for ${p} (${r}/${u}): AI result missing 'usage' data. (May be expected for streams)`);let N;e===`generateText`?N=O.text:e===`generateObject`?N=O.object:(e===`streamText`||e===`streamObject`||S(`error`,`Unknown serviceType in _unifiedServiceRunner: ${e}`),N=O);let P=ht(_);return{mainResult:N,telemetryData:k,tagInfo:P,providerName:r,modelId:u}}catch(n){let i=yt(n);if(S(`error`,`Service call failed for role ${t} (Provider: ${r||`unknown`}, Model: ${u||`unknown`}): ${i}`),T=n,E=i,e===`generateObject`){let e=i.toLowerCase();if(e.includes(`no endpoints found that support tool use`)||e.includes(`does not support tool_use`)||e.includes(`tool use is not supported`)||e.includes(`tools are not supported`)||e.includes(`function calling is not supported`)||e.includes(`tool use is not supported`)){let e=`Model '${u||`unknown`}' via provider '${r||`unknown`}' does not support the 'tool use' required by generateObjectService. Please configure a model that supports tool/function calling for the '${t}' role, or use generateTextService if structured output is not strictly required.`;throw S(`error`,`[Tool Support Error] ${e}`),Error(e)}}}}throw S(`error`,`All roles in the sequence [${w.join(`, `)}] failed.`),Error(E)}async function wt(e){return $(`generateText`,{outputType:`cli`,...e})}async function Tt(e){return $(`streamText`,{outputType:`cli`,...e})}async function Et(e){let t={outputType:`cli`,...e};if(!t.schema)throw Error(`streamObjectService requires a schema parameter`);return $(`streamObject`,t)}async function Dt(e){return $(`generateObject`,{objectName:`generated_object`,maxRetries:3,outputType:`cli`,...e})}async function Ot({userId:e,commandName:t,providerName:n,modelId:r,inputTokens:i,outputTokens:a,outputType:o}){try{let o=new Date().toISOString(),s=(i||0)+(a||0),{inputCost:c,outputCost:l,currency:u,isUnknown:d}=pt(n,r),f=mt(i,a,c,l),p={timestamp:o,userId:e,commandName:t,modelUsed:r,providerName:n,inputTokens:i||0,outputTokens:a||0,totalTokens:s,totalCost:f,currency:u,isUnknownCost:d};return y()&&S(`info`,`AI Usage Telemetry:`,p),p}catch(e){return S(`error`,`Failed to log AI usage telemetry: ${e.message}`,{error:e}),null}}export{Tt as a,xe as c,Et as i,R as l,wt as n,K as o,Ot as r,V as s,Dt as t};
@@ -1 +0,0 @@
1
- import"./ai-services-unified-CEEU0EI1.js";import"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";import"./sentry-Bfs4ROUL.js";import{A as e}from"./dependency-manager-Di3zHzuM.js";import"./response-language-c-DJJiVH.js";export{e as performResearch};
@@ -1 +0,0 @@
1
- import"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";import{t as e}from"./response-language-c-DJJiVH.js";export{e as default};
@@ -1 +0,0 @@
1
- import"./ai-services-unified-CEEU0EI1.js";import"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";import"./sentry-Bfs4ROUL.js";import{ct as e,dt as t,ft as n,ht as r,lt as i,mt as a,pt as o,st as s,ut as c}from"./dependency-manager-Di3zHzuM.js";import"./response-language-c-DJJiVH.js";export{s as copyTag,e as createTag,i as createTagFromBranch,c as deleteTag,t as renameTag,n as switchCurrentTag,o as tags,a as updateBranchTagMapping,r as useTag};
@@ -1 +0,0 @@
1
- import"./ai-services-unified-CEEU0EI1.js";import"./config-manager-Bl_NTZXB.js";import"./git-utils-DllbRE35.js";import"./sentry-Bfs4ROUL.js";import{w as e}from"./dependency-manager-Di3zHzuM.js";import"./response-language-c-DJJiVH.js";export{e as default};