@hhsw2015/task-master-ai 0.43.7 → 0.43.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-services-unified--KinsHuW.js +1 -0
- package/dist/{ai-services-unified-CEEU0EI1.js → ai-services-unified-D0SWrwB5.js} +1 -1
- package/dist/{commands-Dmu6mYBF.js → commands-D_wCc0QR.js} +5 -5
- package/dist/{config-manager-Bqyvl0WP.js → config-manager-BiA1Lh9-.js} +1 -1
- package/dist/{config-manager-Bl_NTZXB.js → config-manager-Dn_JApjY.js} +1 -1
- package/dist/{dependency-manager-Di3zHzuM.js → dependency-manager-D_uegoOJ.js} +4 -4
- package/dist/mcp-server.js +2 -2
- package/dist/{profiles-DodRTAbX.js → profiles-BVhvTqG7.js} +2 -2
- package/dist/research-CubqvgZX.js +1 -0
- package/dist/response-language-B4B6uk8r.js +1 -0
- package/dist/{response-language-c-DJJiVH.js → response-language-DeTA_0Bx.js} +1 -1
- package/dist/{sentry-Bfs4ROUL.js → sentry-Dbx7-h6F.js} +1 -1
- package/dist/tag-management-ByKA_1s5.js +1 -0
- package/dist/{task-manager-s99ri27l.js → task-manager-CmxFUtnm.js} +1 -1
- package/dist/task-master.js +1 -1
- package/dist/update-subtask-by-id-D56bbaA6.js +1 -0
- package/dist/update-task-by-id-rlGR5O_g.js +1 -0
- package/dist/{utils-DCRCLfrh.js → utils-CtCI5DEr.js} +1 -1
- package/package.json +1 -1
- package/dist/ai-services-unified-BxDYeox6.js +0 -1
- package/dist/research-2ldvEeTf.js +0 -1
- package/dist/response-language-DQanNEl4.js +0 -1
- package/dist/tag-management-CaAbUOu8.js +0 -1
- package/dist/update-subtask-by-id-C4XEb2yA.js +0 -1
- package/dist/update-task-by-id-sbk7Up0i.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,i as t,n,r,t as i}from"./ai-services-unified-D0SWrwB5.js";import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";export{i as generateObjectService,n as generateTextService,r as logAiUsage,t as streamObjectService,e as streamTextService};
|
|
@@ -1,4 +1,4 @@
|
|
|
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:
|
|
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-Dn_JApjY.js";import{n as C,t as w}from"./sentry-Dbx7-h6F.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`),a=r?Object.keys(t.properties):[],o=Array.isArray(t.required),s=o?new Set(t.required):new Set,c=o&&a.every(e=>s.has(e))&&t.required.length===a.length;return n&&r&&!i&&(t.additionalProperties=!1),n&&r&&!c&&(t.required=a),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
2
|
• GOOGLE_API_KEY environment variable (typical for API-based auth), OR
|
|
3
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
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(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./ai-services-unified-
|
|
1
|
+
import"./ai-services-unified-D0SWrwB5.js";import{An as e,B as t,Bt as n,E as r,Ht as i,Kt as a,Lt as o,Nt as s,Q as c,R as l,Rt as u,Tt as d,U as f,Ut as p,Vt as m,dt as h,f as g,hn as _,ln as ee,m as v,mn as te,p as y,t as b,ut as ne,yt as x}from"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{$ as S,C,D as w,F as T,I as E,J as re,L as ie,M as ae,N as oe,O as se,P as ce,Q as le,S as ue,St as de,X as D,Y as fe,Z as pe,_ as me,_t as he,a as ge,at as O,b as _e,bt as ve,c as ye,ct as be,d as k,dt as xe,et as Se,f as Ce,g as we,h as Te,ht as Ee,i as De,it as Oe,j as ke,k as A,l as Ae,m as je,n as Me,nt as Ne,o as Pe,ot as Fe,p as j,r as Ie,rt as Le,s as Re,st as ze,t as Be,tt as Ve,u as He,ut as Ue,v as M,vt as We,w as Ge,wt as Ke,xt as qe,y as Je,yt as Ye}from"./dependency-manager-D_uegoOJ.js";import{t as Xe}from"./response-language-DeTA_0Bx.js";import{_ as Ze,a as Qe,c as $e,d as et,f as tt,g as nt,h as rt,i as it,l as N,m as at,n as ot,o as P,p as st,r as ct,s as F,t as I,u as L,v as R}from"./profiles-BVhvTqG7.js";import z from"chalk";import B from"fs";import V from"path";import H from"boxen";import{Command as lt}from"commander";import U from"inquirer";const W={AUTHENTICATION:`authentication`,VALIDATION:`validation`,NETWORK:`network`,API:`api`,FILE_SYSTEM:`file_system`,TASK:`task`,PERMISSION:`permission`,TIMEOUT:`timeout`,GENERIC:`generic`},ut=[/\b[A-Za-z0-9_-]{20,}\b/g,/sk-[A-Za-z0-9]{32,}/g,/api[_-]?key[:\s=]+[^\s]+/gi,/bearer\s+[^\s]+/gi,/token[:\s=]+[^\s]+/gi,/\/Users\/[^/]+/g,/C:\\Users\\[^\\]+/g,/\/home\/[^/]+/g,/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,/https?:\/\/[^:]+:[^@]+@/g];function G(e){if(!e||typeof e!=`string`)return e;let t=e;for(let e of ut)t=t.replace(e,`***REDACTED***`);return t}function dt(e){if(!e)return W.GENERIC;let t=(e.message||``).toLowerCase(),n=(e.code||``).toLowerCase();return t.includes(`auth`)||t.includes(`unauthorized`)||t.includes(`forbidden`)||t.includes(`api key`)||t.includes(`token`)||n.includes(`auth`)?W.AUTHENTICATION:t.includes(`invalid`)||t.includes(`validation`)||t.includes(`required`)||t.includes(`must be`)||n.includes(`validation`)?W.VALIDATION:t.includes(`network`)||t.includes(`connection`)||t.includes(`econnrefused`)||t.includes(`enotfound`)||n.includes(`network`)||n.includes(`econnrefused`)||n.includes(`enotfound`)?W.NETWORK:t.includes(`timeout`)||t.includes(`timed out`)||n.includes(`timeout`)?W.TIMEOUT:t.includes(`api`)||t.includes(`rate limit`)||t.includes(`quota`)||n.includes(`api`)?W.API:t.includes(`enoent`)||t.includes(`eacces`)||t.includes(`file`)||t.includes(`directory`)||n.includes(`enoent`)||n.includes(`eacces`)?W.FILE_SYSTEM:t.includes(`permission`)||t.includes(`access denied`)||n.includes(`eperm`)?W.PERMISSION:t.includes(`task`)||t.includes(`subtask`)?W.TASK:W.GENERIC}function ft(e,t,n){let r=[],i=(t.message||``).toLowerCase();switch(e){case W.AUTHENTICATION:i.includes(`api key`)?(r.push(`Check that your API key is correctly set in the .env file`),r.push(`Verify the API key has not expired or been revoked`)):i.includes(`token`)?(r.push(`Your authentication token may have expired`),r.push(`Try running: tm auth refresh`)):(r.push(`Verify your credentials are correctly configured`),r.push(`Check the authentication status with: tm auth status`));break;case W.VALIDATION:i.includes(`brief id`)?(r.push(`Brief IDs are case-insensitive (e.g., "ham32" = "HAM-32")`),r.push(`Check the brief ID format: usually LETTERS-NUMBERS`)):i.includes(`task id`)||i.includes(`invalid id`)?(r.push(`Task IDs should be numbers (e.g., 1, 2, 3)`),r.push(`Subtask IDs use dot notation (e.g., 1.1, 2.3)`)):(r.push(`Check that all required parameters are provided`),r.push(`Verify parameter values match expected formats`));break;case W.NETWORK:i.includes(`econnrefused`)?(r.push(`Could not connect to the server`),r.push(`Check your internet connection`),r.push(`Verify the API endpoint URL is correct`)):i.includes(`enotfound`)?(r.push(`Could not resolve the server hostname`),r.push(`Check your internet connection`)):(r.push(`Check your network connection`),r.push(`Verify firewall settings are not blocking the request`));break;case W.TIMEOUT:r.push(`The operation took too long to complete`),r.push(`Try again with a simpler request`),r.push(`Check your network speed and stability`);break;case W.API:i.includes(`rate limit`)?(r.push(`You have exceeded the API rate limit`),r.push(`Wait a few minutes before trying again`)):i.includes(`quota`)?(r.push(`You have reached your API quota`),r.push(`Check your account usage and limits`)):(r.push(`The API returned an error`),r.push(`Try again in a few moments`));break;case W.FILE_SYSTEM:i.includes(`enoent`)?(r.push(`The specified file or directory does not exist`),r.push(`Check the file path and ensure it is correct`),n.includes(`tasks.json`)&&r.push(`Initialize the project with: tm init`)):i.includes(`eacces`)?(r.push(`Permission denied to access the file`),r.push(`Check file permissions or run with appropriate privileges`)):r.push(`Check that the file or directory exists and is accessible`);break;case W.PERMISSION:r.push(`You do not have permission to perform this operation`),r.push(`Check file/directory permissions`),r.push(`You may need elevated privileges (sudo)`);break;case W.TASK:i.includes(`not found`)?(r.push(`The specified task does not exist`),r.push(`Use: tm list to see all available tasks`)):i.includes(`dependency`)||i.includes(`circular`)?(r.push(`Task dependencies form a circular reference`),r.push(`Use: tm validate-dependencies to identify issues`)):(r.push(`Check that the task ID is correct`),r.push(`Use: tm show <id> to view task details`));break;default:r.push(`Check the error message for specific details`),n&&r.push(`Operation failed while: ${n}`)}return r.slice(0,2)}function pt(e,t={}){let{context:n=``,debug:r=!1,command:i=``}=t;typeof e==`string`&&(e=Error(e)),(!e||typeof e!=`object`)&&(e=Error(`An unknown error occurred`));let a=G(e.message||`Unknown error`),o=dt(e),s=ft(o,e,n);return{type:o,message:a,context:n||`Unknown operation`,hints:s,command:i||null,code:e.code||null,stack:r?G(e.stack):null}}function K(e,t={}){let n=pt(e,t),r=z.red.bold(`✗ Error
|
|
2
2
|
|
|
3
3
|
`);r+=z.white(n.message)+`
|
|
4
4
|
|
|
@@ -103,7 +103,7 @@ Subtask update was not completed. Review the messages above for details.`))}catc
|
|
|
103
103
|
To fix this issue:`)),console.log(` 1. Run task-master list --with-subtasks to see all available subtask IDs`),console.log(` 2. Use a valid subtask ID with the --id parameter in format "parentId.subtaskId"`)):e.message.includes(`API key`)&&console.log(z.yellow(`
|
|
104
104
|
This error is related to API keys. Check your environment variables.`)),y()&&console.error(e),process.exit(1)}}),n.command(`scope-up`).description(`Increase task complexity with AI assistance`).option(`-f, --file <file>`,`Path to the tasks file`,a).option(`-i, --id <ids>`,`Comma-separated task/subtask IDs to scope up (required)`).option(`-s, --strength <level>`,`Complexity increase strength: light, regular, heavy`,`regular`).option(`-p, --prompt <text>`,`Custom instructions for targeted scope adjustments`).option(`-r, --research`,`Use research AI for more informed adjustments`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{try{let t=q({tasksPath:e.file||!0,tag:e.tag}),n=t.getTasksPath(),r=t.getCurrentTag();await k(r),e.id||(console.error(z.red(`Error: --id parameter is required`)),console.log(z.yellow(`Usage example: task-master scope-up --id=1,2,3 --strength=regular`)),process.exit(1));let i=e.id.split(`,`).map(e=>{let t=parseInt(e.trim(),10);return(Number.isNaN(t)||t<=0)&&(console.error(z.red(`Error: Invalid task ID: ${e.trim()}`)),process.exit(1)),t});A(e.strength)||(console.error(z.red(`Error: Invalid strength level: ${e.strength}. Must be one of: light, regular, heavy`)),process.exit(1)),B.existsSync(n)||(console.error(z.red(`Error: Tasks file not found at path: ${n}`)),process.exit(1)),console.log(z.blue(`Scoping up ${i.length} task(s): ${i.join(`, `)}`)),console.log(z.blue(`Strength level: ${e.strength}`)),e.prompt&&console.log(z.blue(`Custom instructions: ${e.prompt}`));let a={projectRoot:t.getProjectRoot(),tag:r,commandName:`scope-up`,outputType:`cli`,research:e.research||!1},o=await se(n,i,e.strength,e.prompt||null,a,`text`);console.log(z.green(`✅ Successfully scoped up ${o.updatedTasks.length} task(s)`))}catch(e){console.error(z.red(`Error: ${e.message}`)),e.message.includes(`not found`)&&(console.log(z.yellow(`
|
|
105
105
|
To fix this issue:`)),console.log(` 1. Run task-master list to see all available task IDs`),console.log(` 2. Use valid task IDs with the --id parameter`)),y()&&console.error(e),process.exit(1)}}),n.command(`scope-down`).description(`Decrease task complexity with AI assistance`).option(`-f, --file <file>`,`Path to the tasks file`,a).option(`-i, --id <ids>`,`Comma-separated task/subtask IDs to scope down (required)`).option(`-s, --strength <level>`,`Complexity decrease strength: light, regular, heavy`,`regular`).option(`-p, --prompt <text>`,`Custom instructions for targeted scope adjustments`).option(`-r, --research`,`Use research AI for more informed adjustments`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{try{let t=q({tasksPath:e.file||!0,tag:e.tag}),n=t.getTasksPath(),r=t.getCurrentTag();await k(r),e.id||(console.error(z.red(`Error: --id parameter is required`)),console.log(z.yellow(`Usage example: task-master scope-down --id=1,2,3 --strength=regular`)),process.exit(1));let i=e.id.split(`,`).map(e=>{let t=parseInt(e.trim(),10);return(Number.isNaN(t)||t<=0)&&(console.error(z.red(`Error: Invalid task ID: ${e.trim()}`)),process.exit(1)),t});A(e.strength)||(console.error(z.red(`Error: Invalid strength level: ${e.strength}. Must be one of: light, regular, heavy`)),process.exit(1)),B.existsSync(n)||(console.error(z.red(`Error: Tasks file not found at path: ${n}`)),process.exit(1)),console.log(z.blue(`Scoping down ${i.length} task(s): ${i.join(`, `)}`)),console.log(z.blue(`Strength level: ${e.strength}`)),e.prompt&&console.log(z.blue(`Custom instructions: ${e.prompt}`));let a={projectRoot:t.getProjectRoot(),tag:r,commandName:`scope-down`,outputType:`cli`,research:e.research||!1},o=await w(n,i,e.strength,e.prompt||null,a,`text`);console.log(z.green(`✅ Successfully scoped down ${o.updatedTasks.length} task(s)`))}catch(e){console.error(z.red(`Error: ${e.message}`)),e.message.includes(`not found`)&&(console.log(z.yellow(`
|
|
106
|
-
To fix this issue:`)),console.log(` 1. Run task-master list to see all available task IDs`),console.log(` 2. Use valid task IDs with the --id parameter`)),y()&&console.error(e),process.exit(1)}}),Fe(n),n.command(`expand`).description(`Expand a task into subtasks using AI`).option(`-i, --id <id>`,`ID of the task to expand`).option(`-a, --all`,`Expand all pending tasks based on complexity analysis`).option(`-n, --num <number>`,`Number of subtasks to generate (uses complexity analysis by default if available)`).option(`-r, --research`,`Enable research-backed generation (e.g., using Perplexity)`,!1).option(`-p, --prompt <text>`,`Additional context for subtask generation`).option(`-f, --force`,`Force expansion even if subtasks exist`,!1).option(`--file <file>`,`Path to the tasks file (relative to project root)`,a).option(`-cr, --complexity-report <file>`,`Path to the complexity report file (use this to specify the complexity report, not --file)`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t={tasksPath:e.file||!0,tag:e.tag};e.complexityReport&&(t.complexityReportPath=e.complexityReport);let r=q(t),i=r.getCurrentTag();if(await k(i),e.all){console.log(z.blue(`Expanding all pending tasks...`));try{await re(r.getTasksPath(),e.num,e.research,e.prompt,e.force,{projectRoot:r.getProjectRoot(),tag:i,complexityReportPath:r.getComplexityReportPath()})}catch(e){console.error(z.red(`Error expanding all tasks: ${e.message}`)),process.exit(1)}}else if(e.id){e.id||(console.error(z.red(`Error: Task ID is required unless using --all.`)),process.exit(1)),console.log(z.blue(`Expanding task ${e.id}...`));try{await fe(r.getTasksPath(),e.id,e.num,e.research,e.prompt,{projectRoot:r.getProjectRoot(),tag:i,complexityReportPath:r.getComplexityReportPath()},e.force)}catch(t){console.error(z.red(`Error expanding task ${e.id}: ${t.message}`)),process.exit(1)}}else console.error(z.red(`Error: You must specify either a task ID (--id) or --all.`)),n.help()}),n.command(`analyze-complexity`).description(`Analyze tasks and generate expansion recommendations${z.reset(``)}`).option(`-o, --output <file>`,`Output file path for the report`).option(`-m, --model <model>`,`LLM model to use for analysis (defaults to configured model)`).option(`-t, --threshold <number>`,`Minimum complexity score to recommend expansion (1-10)`,`5`).option(`-f, --file <file>`,`Path to the tasks file`,a).option(`-r, --research`,`Use configured research model for research-backed complexity analysis`).option(`-i, --id <ids>`,`Comma-separated list of specific task IDs to analyze (e.g., "1,3,5")`).option(`--from <id>`,`Starting task ID in a range to analyze`).option(`--to <id>`,`Ending task ID in a range to analyze`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t={tasksPath:e.file||!0,tag:e.tag};e.output&&(t.complexityReportPath=e.output);let n=q(t);e.model,parseFloat(e.threshold);let r=e.research||!1,i=n.getCurrentTag();await k(i);let a=n.getComplexityReportPath();if(console.log(z.blue(`Analyzing task complexity from: ${n.getTasksPath()}`)),console.log(z.blue(`Output report will be saved to: ${a}`)),e.id)console.log(z.blue(`Analyzing specific task IDs: ${e.id}`));else if(e.from||e.to){let t=e.from?e.from:`first`,n=e.to?e.to:`last`;console.log(z.blue(`Analyzing tasks in range: ${t} to ${n}`))}r&&console.log(z.blue(`Using Perplexity AI for research-backed complexity analysis`)),await pe({...e,output:a,tag:i,projectRoot:n.getProjectRoot(),file:n.getTasksPath()})}),n.command(`research`).description(`Perform AI-powered research queries with project context`).argument(`[prompt]`,`Research prompt to investigate`).option(`--file <file>`,`Path to the tasks file`).option(`-i, --id <ids>`,`Comma-separated task/subtask IDs to include as context (e.g., "15,16.2")`).option(`-f, --files <paths>`,`Comma-separated file paths to include as context`).option(`-c, --context <text>`,`Additional custom context to include in the research prompt`).option(`-t, --tree`,`Include project file tree structure in the research context`).option(`-s, --save <file>`,`Save research results to the specified task/subtask(s)`).option(`-d, --detail <level>`,`Output detail level: low, medium, high`,`medium`).option(`--save-to <id>`,`Automatically save research results to specified task/subtask ID (e.g., "15" or "15.2")`).option(`--save-file`,`Save research results to .taskmaster/docs/research/ directory`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async(e,t)=>{let n=q({tasksPath:t.file||!0,tag:t.tag});(!e||typeof e!=`string`||e.trim().length===0)&&(console.error(z.red(`Error: Research prompt is required and cannot be empty`)),m(),process.exit(1));let r=[`low`,`medium`,`high`];t.detail&&!r.includes(t.detail.toLowerCase())&&(console.error(z.red(`Error: Detail level must be one of: ${r.join(`, `)}`)),process.exit(1));let i=[];if(t.id)try{i=t.id.split(`,`).map(e=>{let t=e.trim();if(!/^\d+(\.\d+)?$/.test(t))throw Error(`Invalid task ID format: "${t}". Expected format: "15" or "15.2"`);return t})}catch(e){console.error(z.red(`Error parsing task IDs: ${e.message}`)),process.exit(1)}let a=[];if(t.files)try{a=t.files.split(`,`).map(e=>{let t=e.trim();if(t.length===0)throw Error(`Empty file path provided`);return t})}catch(e){console.error(z.red(`Error parsing file paths: ${e.message}`)),process.exit(1)}if(t.saveTo){let e=t.saveTo.trim();e.length===0&&(console.error(z.red(`Error: Save-to ID cannot be empty`)),process.exit(1)),/^\d+(\.\d+)?$/.test(e)||(console.error(z.red(`Error: Save-to ID must be in format "15" for task or "15.2" for subtask`)),process.exit(1))}if(t.save){let e=t.save.trim();e.length===0&&(console.error(z.red(`Error: Save target cannot be empty`)),process.exit(1)),(e.includes(`..`)||e.startsWith(`/`))&&(console.error(z.red(`Error: Save path must be relative and cannot contain ".."`)),process.exit(1))}let o=n.getCurrentTag();if(await k(o),i.length>0)try{let e=d(n.getTasksPath(),n.getProjectRoot(),o);(!e||!e.tasks)&&(console.error(z.red(`Error: No valid tasks found in ${n.getTasksPath()} for tag '${o}'`)),process.exit(1))}catch(e){console.error(z.red(`Error reading tasks file: ${e.message}`)),process.exit(1)}if(a.length>0)for(let e of a){let t=V.isAbsolute(e)?e:V.join(n.getProjectRoot(),e);B.existsSync(t)||(console.error(z.red(`Error: File not found: ${e}`)),process.exit(1))}let s={prompt:e.trim(),taskIds:i,filePaths:a,customContext:t.context?t.context.trim():null,includeProjectTree:!!t.tree,saveTarget:t.save?t.save.trim():null,saveToId:t.saveTo?t.saveTo.trim():null,allowFollowUp:!0,detailLevel:t.detail?t.detail.toLowerCase():`medium`,tasksPath:n.getTasksPath(),projectRoot:n.getProjectRoot()};console.log(z.blue(`Researching: "${s.prompt}"`)),s.taskIds.length>0&&console.log(z.gray(`Task context: ${s.taskIds.join(`, `)}`)),s.filePaths.length>0&&console.log(z.gray(`File context: ${s.filePaths.join(`, `)}`)),s.customContext&&console.log(z.gray(`Custom context: ${s.customContext.substring(0,50)}${s.customContext.length>50?`...`:``}`)),s.includeProjectTree&&console.log(z.gray(`Including project file tree`)),console.log(z.gray(`Detail level: ${s.detailLevel}`));try{let{performResearch:e}=await import(`./research-
|
|
106
|
+
To fix this issue:`)),console.log(` 1. Run task-master list to see all available task IDs`),console.log(` 2. Use valid task IDs with the --id parameter`)),y()&&console.error(e),process.exit(1)}}),Fe(n),n.command(`expand`).description(`Expand a task into subtasks using AI`).option(`-i, --id <id>`,`ID of the task to expand`).option(`-a, --all`,`Expand all pending tasks based on complexity analysis`).option(`-n, --num <number>`,`Number of subtasks to generate (uses complexity analysis by default if available)`).option(`-r, --research`,`Enable research-backed generation (e.g., using Perplexity)`,!1).option(`-p, --prompt <text>`,`Additional context for subtask generation`).option(`-f, --force`,`Force expansion even if subtasks exist`,!1).option(`--file <file>`,`Path to the tasks file (relative to project root)`,a).option(`-cr, --complexity-report <file>`,`Path to the complexity report file (use this to specify the complexity report, not --file)`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t={tasksPath:e.file||!0,tag:e.tag};e.complexityReport&&(t.complexityReportPath=e.complexityReport);let r=q(t),i=r.getCurrentTag();if(await k(i),e.all){console.log(z.blue(`Expanding all pending tasks...`));try{await re(r.getTasksPath(),e.num,e.research,e.prompt,e.force,{projectRoot:r.getProjectRoot(),tag:i,complexityReportPath:r.getComplexityReportPath()})}catch(e){console.error(z.red(`Error expanding all tasks: ${e.message}`)),process.exit(1)}}else if(e.id){e.id||(console.error(z.red(`Error: Task ID is required unless using --all.`)),process.exit(1)),console.log(z.blue(`Expanding task ${e.id}...`));try{await fe(r.getTasksPath(),e.id,e.num,e.research,e.prompt,{projectRoot:r.getProjectRoot(),tag:i,complexityReportPath:r.getComplexityReportPath()},e.force)}catch(t){console.error(z.red(`Error expanding task ${e.id}: ${t.message}`)),process.exit(1)}}else console.error(z.red(`Error: You must specify either a task ID (--id) or --all.`)),n.help()}),n.command(`analyze-complexity`).description(`Analyze tasks and generate expansion recommendations${z.reset(``)}`).option(`-o, --output <file>`,`Output file path for the report`).option(`-m, --model <model>`,`LLM model to use for analysis (defaults to configured model)`).option(`-t, --threshold <number>`,`Minimum complexity score to recommend expansion (1-10)`,`5`).option(`-f, --file <file>`,`Path to the tasks file`,a).option(`-r, --research`,`Use configured research model for research-backed complexity analysis`).option(`-i, --id <ids>`,`Comma-separated list of specific task IDs to analyze (e.g., "1,3,5")`).option(`--from <id>`,`Starting task ID in a range to analyze`).option(`--to <id>`,`Ending task ID in a range to analyze`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async e=>{let t={tasksPath:e.file||!0,tag:e.tag};e.output&&(t.complexityReportPath=e.output);let n=q(t);e.model,parseFloat(e.threshold);let r=e.research||!1,i=n.getCurrentTag();await k(i);let a=n.getComplexityReportPath();if(console.log(z.blue(`Analyzing task complexity from: ${n.getTasksPath()}`)),console.log(z.blue(`Output report will be saved to: ${a}`)),e.id)console.log(z.blue(`Analyzing specific task IDs: ${e.id}`));else if(e.from||e.to){let t=e.from?e.from:`first`,n=e.to?e.to:`last`;console.log(z.blue(`Analyzing tasks in range: ${t} to ${n}`))}r&&console.log(z.blue(`Using Perplexity AI for research-backed complexity analysis`)),await pe({...e,output:a,tag:i,projectRoot:n.getProjectRoot(),file:n.getTasksPath()})}),n.command(`research`).description(`Perform AI-powered research queries with project context`).argument(`[prompt]`,`Research prompt to investigate`).option(`--file <file>`,`Path to the tasks file`).option(`-i, --id <ids>`,`Comma-separated task/subtask IDs to include as context (e.g., "15,16.2")`).option(`-f, --files <paths>`,`Comma-separated file paths to include as context`).option(`-c, --context <text>`,`Additional custom context to include in the research prompt`).option(`-t, --tree`,`Include project file tree structure in the research context`).option(`-s, --save <file>`,`Save research results to the specified task/subtask(s)`).option(`-d, --detail <level>`,`Output detail level: low, medium, high`,`medium`).option(`--save-to <id>`,`Automatically save research results to specified task/subtask ID (e.g., "15" or "15.2")`).option(`--save-file`,`Save research results to .taskmaster/docs/research/ directory`).option(`--tag <tag>`,`Specify tag context for task operations`).action(async(e,t)=>{let n=q({tasksPath:t.file||!0,tag:t.tag});(!e||typeof e!=`string`||e.trim().length===0)&&(console.error(z.red(`Error: Research prompt is required and cannot be empty`)),m(),process.exit(1));let r=[`low`,`medium`,`high`];t.detail&&!r.includes(t.detail.toLowerCase())&&(console.error(z.red(`Error: Detail level must be one of: ${r.join(`, `)}`)),process.exit(1));let i=[];if(t.id)try{i=t.id.split(`,`).map(e=>{let t=e.trim();if(!/^\d+(\.\d+)?$/.test(t))throw Error(`Invalid task ID format: "${t}". Expected format: "15" or "15.2"`);return t})}catch(e){console.error(z.red(`Error parsing task IDs: ${e.message}`)),process.exit(1)}let a=[];if(t.files)try{a=t.files.split(`,`).map(e=>{let t=e.trim();if(t.length===0)throw Error(`Empty file path provided`);return t})}catch(e){console.error(z.red(`Error parsing file paths: ${e.message}`)),process.exit(1)}if(t.saveTo){let e=t.saveTo.trim();e.length===0&&(console.error(z.red(`Error: Save-to ID cannot be empty`)),process.exit(1)),/^\d+(\.\d+)?$/.test(e)||(console.error(z.red(`Error: Save-to ID must be in format "15" for task or "15.2" for subtask`)),process.exit(1))}if(t.save){let e=t.save.trim();e.length===0&&(console.error(z.red(`Error: Save target cannot be empty`)),process.exit(1)),(e.includes(`..`)||e.startsWith(`/`))&&(console.error(z.red(`Error: Save path must be relative and cannot contain ".."`)),process.exit(1))}let o=n.getCurrentTag();if(await k(o),i.length>0)try{let e=d(n.getTasksPath(),n.getProjectRoot(),o);(!e||!e.tasks)&&(console.error(z.red(`Error: No valid tasks found in ${n.getTasksPath()} for tag '${o}'`)),process.exit(1))}catch(e){console.error(z.red(`Error reading tasks file: ${e.message}`)),process.exit(1)}if(a.length>0)for(let e of a){let t=V.isAbsolute(e)?e:V.join(n.getProjectRoot(),e);B.existsSync(t)||(console.error(z.red(`Error: File not found: ${e}`)),process.exit(1))}let s={prompt:e.trim(),taskIds:i,filePaths:a,customContext:t.context?t.context.trim():null,includeProjectTree:!!t.tree,saveTarget:t.save?t.save.trim():null,saveToId:t.saveTo?t.saveTo.trim():null,allowFollowUp:!0,detailLevel:t.detail?t.detail.toLowerCase():`medium`,tasksPath:n.getTasksPath(),projectRoot:n.getProjectRoot()};console.log(z.blue(`Researching: "${s.prompt}"`)),s.taskIds.length>0&&console.log(z.gray(`Task context: ${s.taskIds.join(`, `)}`)),s.filePaths.length>0&&console.log(z.gray(`File context: ${s.filePaths.join(`, `)}`)),s.customContext&&console.log(z.gray(`Custom context: ${s.customContext.substring(0,50)}${s.customContext.length>50?`...`:``}`)),s.includeProjectTree&&console.log(z.gray(`Including project file tree`)),console.log(z.gray(`Detail level: ${s.detailLevel}`));try{let{performResearch:e}=await import(`./research-CubqvgZX.js`),n={taskIds:s.taskIds,filePaths:s.filePaths,customContext:s.customContext||``,includeProjectTree:s.includeProjectTree,detailLevel:s.detailLevel,projectRoot:s.projectRoot,saveToFile:!!t.saveFile,tag:o},r=await e(s.prompt,n,{commandName:`research`,outputType:`cli`,tag:o},`text`,s.allowFollowUp);if(s.saveToId&&!r.interactiveSaveOccurred)try{let e=s.saveToId.includes(`.`),t=`## Research Query: ${s.prompt}
|
|
107
107
|
|
|
108
108
|
**Detail Level:** ${r.detailLevel}
|
|
109
109
|
**Context Size:** ${r.contextSize} characters
|
|
@@ -111,7 +111,7 @@ To fix this issue:`)),console.log(` 1. Run task-master list to see all availabl
|
|
|
111
111
|
|
|
112
112
|
### Results
|
|
113
113
|
|
|
114
|
-
${r.result}`;if(e){let{updateSubtaskById:e}=await import(`./update-subtask-by-id-
|
|
114
|
+
${r.result}`;if(e){let{updateSubtaskById:e}=await import(`./update-subtask-by-id-D56bbaA6.js`);await e(s.tasksPath,s.saveToId,t,!1,{commandName:`research-save`,outputType:`cli`,projectRoot:s.projectRoot,tag:o},`text`),console.log(z.green(`✅ Research saved to subtask ${s.saveToId}`))}else{let e=(await import(`./update-task-by-id-rlGR5O_g.js`)).default,n=parseInt(s.saveToId,10);await e(s.tasksPath,n,t,!1,{commandName:`research-save`,outputType:`cli`,projectRoot:s.projectRoot,tag:o},`text`,!0),console.log(z.green(`✅ Research saved to task ${s.saveToId}`))}}catch(e){console.log(z.red(`❌ Error saving to task/subtask: ${e.message}`))}if(s.saveTarget){let e=`# Research Query: ${s.prompt}
|
|
115
115
|
|
|
116
116
|
**Detail Level:** ${r.detailLevel}
|
|
117
117
|
**Context Size:** ${r.contextSize} characters
|
|
@@ -306,14 +306,14 @@ Or specify profiles directly:
|
|
|
306
306
|
`));for(let e of t)console.log(` • ${e.displayName} ${z.gray(`(${e.markerPath})`)}`);console.log(``),e=t.map(e=>e.profileName)}else e=await F(i);if(!e||e.length===0){console.log(z.yellow(`No profiles selected. Exiting.`));return}console.log(z.blue(`Installing ${e.length} selected profile(s)...`));let{allSuccessfulProfiles:t,totalSuccess:r,totalFailed:a}=I(await P(e,i,n.mode));console.log(z.green(`\n✓ Successfully installed ${t.length} profile(s)`)),r>0&&console.log(z.gray(` ${r} files processed, ${a} failed`));return}(!t||t.length===0)&&(console.error(`Please specify at least one rule profile (e.g., windsurf, roo).`),process.exit(1));let a=t.flatMap(e=>e.split(`,`).map(e=>e.trim())).filter(Boolean);if(e===N.REMOVE){let e=!0;if(n.force||(e=$e(i,a)?await _t(a,Qe(i)):await gt(a)),!e){console.log(z.yellow(`Aborted: No rules were removed.`));return}}let o=[],s=[];for(let t of a){if(!rt(t)){console.warn(`Rule profile for "${t}" not found. Valid profiles: ${R.join(`, `)}. Skipping.`);continue}let a=at(t);if(e===N.ADD){console.log(z.blue(`Adding rules for profile: ${t}...`));let e=st(i,a,{mode:await r(n.mode)});console.log(z.blue(`Completed adding rules for profile: ${t}`)),s.push({profileName:t,success:e.success,failed:e.failed}),console.log(z.green(it(t,e)))}else if(e===N.REMOVE){console.log(z.blue(`Removing rules for profile: ${t}...`));let e=nt(i,a);o.push(e),console.log(z.green(ct(t,e)))}else console.error(`Unknown action. Use "${N.ADD}" or "${N.REMOVE}".`),process.exit(1)}if(e===N.ADD&&s.length>0){let{allSuccessfulProfiles:e,totalSuccess:t,totalFailed:n}=I(s);e.length>0&&(console.log(z.green(`\nSuccessfully processed profiles: ${e.join(`, `)}`)),t>0?console.log(z.green(`Total: ${t} files processed, ${n} failed.`)):console.log(z.green(`Total: ${e.length} profile(s) set up successfully.`)))}if(e===N.REMOVE&&o.length>0){let{successfulRemovals:e,skippedRemovals:t,failedRemovals:n,removalsWithNotices:r}=ot(o);e.length>0&&console.log(z.green(`\nSuccessfully removed profiles for: ${e.join(`, `)}`)),t.length>0&&console.log(z.yellow(`Skipped (default or protected): ${t.join(`, `)}`)),n.length>0&&(console.log(z.red(`
|
|
307
307
|
Errors occurred:`)),n.forEach(e=>{console.log(z.red(` ${e.profileName}: ${e.error}`))})),r.length>0&&(console.log(z.cyan(`
|
|
308
308
|
Notices:`)),r.forEach(e=>{console.log(z.cyan(` ${e.profileName}: ${e.notice}`))}));let i=o.length,a=e.length,s=t.length,c=n.length;console.log(z.blue(`\nTotal: ${i} profile(s) processed - ${a} removed, ${s} skipped, ${c} failed.`))}}),n.command(`migrate`).description(`Migrate existing project to use the new .taskmaster directory structure`).option(`-f, --force`,`Force migration even if .taskmaster directory already exists`).option(`--backup`,`Create backup of old files before migration (default: false)`,!1).option(`--cleanup`,`Remove old files after successful migration (default: true)`,!0).option(`-y, --yes`,`Skip confirmation prompts`).option(`--dry-run`,`Show what would be migrated without actually moving files`).action(async e=>{try{await ie(e)}catch(e){console.error(z.red(`Error during migration:`),e.message),process.exit(1)}}),n.command(`sync-readme`).description(`Sync the current task list to README.md in the project root`).option(`-f, --file <file>`,`Path to the tasks file`,a).option(`--with-subtasks`,`Include subtasks in the README output`).option(`-s, --status <status>`,`Show only tasks matching this status (e.g., pending, done)`).option(`-t, --tag <tag>`,`Tag to use for the task list (default: master)`).action(async e=>{let t=q({tasksPath:e.file||!0,tag:e.tag}),n=e.withSubtasks||!1,r=e.status||null,i=t.getCurrentTag();console.log(z.blue(`📝 Syncing tasks to README.md${n?` (with subtasks)`:``}${r?` (status: ${r})`:``}...`)),await syncTasksToReadme(t.getProjectRoot(),{withSubtasks:n,status:r,tasksPath:t.getTasksPath(),tag:i})||(console.error(z.red(`❌ Failed to sync tasks to README.md`)),process.exit(1))}),n.command(`add-tag`).description(`[DEPRECATED] Create a new tag context for organizing tasks (use "tm tags add" instead)`).argument(`[tagName]`,`Name of the new tag to create (optional when using --from-branch)`).option(`-f, --file <file>`,`Path to the tasks file`,a).option(`--copy-from-current`,`Copy tasks from the current tag to the new tag`).option(`--copy-from <tag>`,`Copy tasks from the specified tag to the new tag`).option(`--from-branch`,`Create tag name from current git branch (ignores tagName argument)`).option(`-d, --description <text>`,`Optional description for the tag`).action(async(e,t)=>{console.warn(z.yellow(`⚠ Warning: "tm add-tag" is deprecated. Use "tm tags add" instead.`)),console.log(z.gray(` This command will be removed in a future version.
|
|
309
|
-
`));try{let n=q({tasksPath:t.file||!0}),r=n.getTasksPath();B.existsSync(r)||(console.error(z.red(`Error: Tasks file not found at path: ${r}`)),console.log(z.yellow(`Hint: Run task-master init or task-master parse-prd to create tasks.json first`)),process.exit(1)),!e&&!t.fromBranch&&(console.error(z.red(`Error: Either tagName argument or --from-branch option is required.`)),console.log(z.yellow(`Usage examples:`)),console.log(z.cyan(` task-master add-tag my-tag`)),console.log(z.cyan(` task-master add-tag --from-branch`)),process.exit(1));let i={projectRoot:n.getProjectRoot(),commandName:`add-tag`,outputType:`cli`};if(t.fromBranch){let{createTagFromBranch:e}=await import(`./tag-management-
|
|
309
|
+
`));try{let n=q({tasksPath:t.file||!0}),r=n.getTasksPath();B.existsSync(r)||(console.error(z.red(`Error: Tasks file not found at path: ${r}`)),console.log(z.yellow(`Hint: Run task-master init or task-master parse-prd to create tasks.json first`)),process.exit(1)),!e&&!t.fromBranch&&(console.error(z.red(`Error: Either tagName argument or --from-branch option is required.`)),console.log(z.yellow(`Usage examples:`)),console.log(z.cyan(` task-master add-tag my-tag`)),console.log(z.cyan(` task-master add-tag --from-branch`)),process.exit(1));let i={projectRoot:n.getProjectRoot(),commandName:`add-tag`,outputType:`cli`};if(t.fromBranch){let{createTagFromBranch:e}=await import(`./tag-management-ByKA_1s5.js`),r=await import(`./git-utils-PBP1PRVP.js`);await r.isGitRepository(i.projectRoot)||(console.error(z.red(`Error: Not in a git repository. Cannot use --from-branch option.`)),process.exit(1));let a=await r.getCurrentBranch(i.projectRoot);a||(console.error(z.red(`Error: Could not determine current git branch.`)),process.exit(1));let o={copyFromCurrent:t.copyFromCurrent||!1,copyFromTag:t.copyFrom,description:t.description||`Tag created from git branch "${a}"`};await e(n.getTasksPath(),a,o,i,`text`)}else{let r={copyFromCurrent:t.copyFromCurrent||!1,copyFromTag:t.copyFrom,description:t.description};await be(n.getTasksPath(),e,r,i,`text`)}if(t.autoSwitch){let{useTag:r}=await import(`./tag-management-ByKA_1s5.js`),a=t.fromBranch?(await import(`./git-utils-PBP1PRVP.js`)).sanitizeBranchNameForTag(await(await import(`./git-utils-PBP1PRVP.js`)).getCurrentBranch(projectRoot)):e;await r(n.getTasksPath(),a,{},i,`text`)}}catch(e){console.error(z.red(`Error creating tag: ${e.message}`)),u(),process.exit(1)}}).on(`error`,function(e){console.error(z.red(`Error: ${e.message}`)),u(),process.exit(1)}),n.command(`delete-tag`).description(`[DEPRECATED] Delete an existing tag and all its tasks (use "tm tags remove" instead)`).argument(`<tagName>`,`Name of the tag to delete`).option(`-f, --file <file>`,`Path to the tasks file`,a).option(`-y, --yes`,`Skip confirmation prompts`).action(async(e,t)=>{console.warn(z.yellow(`⚠ Warning: "tm delete-tag" is deprecated. Use "tm tags remove" instead.`)),console.log(z.gray(` This command will be removed in a future version.
|
|
310
310
|
`));try{let n=q({tasksPath:t.file||!0}),r=n.getTasksPath();B.existsSync(r)||(console.error(z.red(`Error: Tasks file not found at path: ${r}`)),process.exit(1));let i={yes:t.yes||!1},a={projectRoot:n.getProjectRoot(),commandName:`delete-tag`,outputType:`cli`};await Ue(n.getTasksPath(),e,i,a,`text`)}catch(e){console.error(z.red(`Error deleting tag: ${e.message}`)),f(),process.exit(1)}}).on(`error`,function(e){console.error(z.red(`Error: ${e.message}`)),f(),process.exit(1)}),n.command(`use-tag`).description(`[DEPRECATED] Switch to a different tag context (use "tm tags use" instead)`).argument(`<tagName>`,`Name of the tag to switch to`).option(`-f, --file <file>`,`Path to the tasks file`,a).action(async(e,t)=>{console.warn(z.yellow(`⚠ Warning: "tm use-tag" is deprecated. Use "tm tags use" instead.`)),console.log(z.gray(` This command will be removed in a future version.
|
|
311
311
|
`));try{let n=q({tasksPath:t.file||!0}),r=n.getTasksPath();B.existsSync(r)||(console.error(z.red(`Error: Tasks file not found at path: ${r}`)),process.exit(1));let i={projectRoot:n.getProjectRoot(),commandName:`use-tag`,outputType:`cli`};await Ee(n.getTasksPath(),e,{},i,`text`)}catch(e){console.error(z.red(`Error switching tag: ${e.message}`)),p(),process.exit(1)}}).on(`error`,function(e){console.error(z.red(`Error: ${e.message}`)),p(),process.exit(1)}),n.command(`rename-tag`).description(`[DEPRECATED] Rename an existing tag (use "tm tags rename" instead)`).argument(`<oldName>`,`Current name of the tag`).argument(`<newName>`,`New name for the tag`).option(`-f, --file <file>`,`Path to the tasks file`,a).action(async(e,t,n)=>{console.warn(z.yellow(`⚠ Warning: "tm rename-tag" is deprecated. Use "tm tags rename" instead.`)),console.log(z.gray(` This command will be removed in a future version.
|
|
312
312
|
`));try{let r=q({tasksPath:n.file||!0}),i=r.getTasksPath();B.existsSync(i)||(console.error(z.red(`Error: Tasks file not found at path: ${i}`)),process.exit(1));let a={projectRoot:r.getProjectRoot(),commandName:`rename-tag`,outputType:`cli`};await xe(r.getTasksPath(),e,t,{},a,`text`)}catch(e){console.error(z.red(`Error renaming tag: ${e.message}`)),process.exit(1)}}).on(`error`,function(e){console.error(z.red(`Error: ${e.message}`)),process.exit(1)}),n.command(`copy-tag`).description(`[DEPRECATED] Copy an existing tag to create a new tag with the same tasks (use "tm tags copy" instead)`).argument(`<sourceName>`,`Name of the source tag to copy from`).argument(`<targetName>`,`Name of the new tag to create`).option(`-f, --file <file>`,`Path to the tasks file`,a).option(`-d, --description <text>`,`Optional description for the new tag`).action(async(e,t,n)=>{console.warn(z.yellow(`⚠ Warning: "tm copy-tag" is deprecated. Use "tm tags copy" instead.`)),console.log(z.gray(` This command will be removed in a future version.
|
|
313
313
|
`));try{let r=q({tasksPath:n.file||!0}),i=r.getTasksPath();B.existsSync(i)||(console.error(z.red(`Error: Tasks file not found at path: ${i}`)),process.exit(1)),await ze(i,e,t,{description:n.description},{projectRoot:r.getProjectRoot(),commandName:`copy-tag`,outputType:`cli`},`text`)}catch(e){console.error(z.red(`Error copying tag: ${e.message}`)),process.exit(1)}}).on(`error`,function(e){console.error(z.red(`Error: ${e.message}`)),process.exit(1)}),n.command(`tui`).alias(`repl`).description(`Launch the interactive TUI/REPL mode`).action(async()=>{await Q()}),n}async function bt(){return null}async function Q(){let e=await import(`react`),t=await bt();if(!t){console.log(z.yellow(`TUI mode coming soon!`)),console.log(z.dim(`Showing help instead...
|
|
314
314
|
`)),J()?X():j();return}let{render:n,Shell:r}=t,i=`master`,a=`local`,o,s={isAuthenticated:!1},c=process.cwd();try{let e=q({});i=e.getCurrentTag(),c=e.getProjectRoot()||process.cwd();let t=_.getInstance(),n=t.getContext(),r=t.getStoredContext();r&&r.email&&(s={isAuthenticated:!0,email:r.email,userId:r.userId}),n&&n.briefId&&(a=`api`,o={id:n.briefId,name:n.briefName||i})}catch{}let l=process.stdin.isTTY&&typeof process.stdin.setRawMode==`function`;console.clear();let u={showBanner:!0,showSplash:l,initialTag:i,storageType:a,brief:o,authState:s,isInteractive:l,projectRoot:c,onExit:()=>{console.log(z.dim(`
|
|
315
315
|
Goodbye! 👋`)),process.exit(0)}},d=n(e.createElement(r,u));l||setTimeout(()=>{d.unmount(),console.log(z.dim(`
|
|
316
|
-
💡 Run in an interactive terminal for full REPL mode.`)),process.exit(0)},200)}function $(){let e=new lt().name(`task-master`).description(`AI-driven development task management`).version(`0.43.
|
|
316
|
+
💡 Run in an interactive terminal for full REPL mode.`)),process.exit(0)},200)}function $(){let e=new lt().name(`task-master`).description(`AI-driven development task management`).version(`0.43.8`).helpOption(`-h, --help`,`Display help`).addHelpCommand(!1),t=e.helpInformation.bind(e);return e.helpInformation=function(){return this.parent&&this.parent!==e?t():(J()?X():j(),``)},Z(e),e}async function xt(e=process.argv){try{if(e.length<=2){await Q();return}let t=e.includes(`init`),n=e.includes(`tui`)||e.includes(`repl`),r=e.includes(`--no-banner`);process.stdout.isTTY&&!t&&!n&&!r&&Re();let i=process.env.TASKMASTER_SKIP_AUTO_UPDATE===`1`||process.env.CI||process.env.NODE_ENV===`test`,a=Se(),o=i?{currentVersion:a,latestVersion:a,needsUpdate:!1}:await ve(a);if(o.needsUpdate&&(Ye(o.currentVersion,o.latestVersion,o.highlights),await We(o.latestVersion))){he(e);return}let s=$(),c=e.filter(e=>e!==`--no-banner`);await s.parseAsync(c);try{let e=q({}),t=e.getTasksPath(),n=e.getStatePath();if(t&&B.existsSync(t)){let e=B.readFileSync(t,`utf8`),r=JSON.parse(e);if(r&&r.master){let e={migrationNoticeShown:!1};if(n&&B.existsSync(n)){let t=B.readFileSync(n,`utf8`);e=JSON.parse(t)||e}e.migrationNoticeShown||(me({_migrationHappened:!0}),e.migrationNoticeShown=!0,n&&B.writeFileSync(n,JSON.stringify(e,null,2)))}}}catch{}}catch(e){e instanceof b?console.error(H(z.red.bold(`Configuration Update Required!`)+`
|
|
317
317
|
|
|
318
318
|
`+z.white(`Taskmaster now uses a `)+z.yellow.bold(`configuration file`)+z.white(` in your project for AI model choices and settings.
|
|
319
319
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as e,B as t,C as n,Cn as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,R as _,S as v,T as y,U as b,V as x,W as S,_ as C,a as w,b as T,bn as E,c as D,d as O,f as k,g as A,h as j,i as M,j as N,k as P,l as F,m as I,n as L,o as R,p as z,q as B,r as V,s as H,t as U,u as W,v as G,w as K,x as q,xn as J,y as Y,z as X}from"./config-manager-
|
|
1
|
+
import{A as e,B as t,C as n,Cn as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,R as _,S as v,T as y,U as b,V as x,W as S,_ as C,a as w,b as T,bn as E,c as D,d as O,f as k,g as A,h as j,i as M,j as N,k as P,l as F,m as I,n as L,o as R,p as z,q as B,r as V,s as H,t as U,u as W,v as G,w as K,x as q,xn as J,y as Y,z as X}from"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";export{E as ALL_PROVIDERS,J as CUSTOM_PROVIDERS,U as ConfigurationError,u as MODEL_MAP,r as VALIDATED_PROVIDERS,L as getAllProviders,V as getAnonymousTelemetryEnabled,M as getAvailableModels,w as getAzureBaseURL,R as getBaseUrlForRole,H as getBedrockBaseURL,D as getClaudeCodeSettings,F as getClaudeCodeSettingsForCommand,W as getCodexCliSettings,O as getCodexCliSettingsForCommand,k as getConfig,z as getDebugFlag,I as getDefaultNumTasks,j as getDefaultPriority,A as getDefaultSubtasks,C as getFallbackModelId,G as getFallbackProvider,Y as getGrokCliSettings,T as getGrokCliSettingsForCommand,q as getLogLevel,v as getMainModelId,n as getMainProvider,K as getMcpApiKeyStatus,y as getOllamaBaseURL,a as getOperatingMode,i as getParametersForRole,h as getProjectName,P as getProxyEnabled,e as getResearchModelId,N as getResearchProvider,p as getResponseLanguage,m as getSupportedModelsForProvider,g as getUserId,o as getVertexLocation,l as getVertexProjectId,f as hasCodebaseAnalysis,_ as isApiKeySet,X as isCodebaseAnalysisEnabled,t as isConfigFilePresent,x as isConfigWarningSuppressed,c as isProxyEnabled,b as setSuppressConfigWarnings,S as validateClaudeCodeSettings,s as validateCodexCliSettings,d as validateProvider,B as writeConfig};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{t as e}from"./git-utils-DllbRE35.js";import t,{join as n,resolve as r}from"node:path";import i from"chalk";import{createClient as a,isAuthError as o}from"@supabase/supabase-js";import s from"fs";import c,{join as l}from"path";import u from"fs/promises";import{Writer as d}from"steno";import f from"crypto";import p from"os";import m,{appendFile as h,mkdir as ee,readFile as te}from"node:fs/promises";import ne from"fs-extra";import{simpleGit as re}from"simple-git";import ie,{constants as ae,existsSync as g,readFileSync as oe,readdirSync as se,realpathSync as ce}from"node:fs";import le from"proper-lockfile";import{spawn as ue,spawnSync as de}from"node:child_process";import fe from"node:os";import{z as _}from"zod";import{exec as pe,execSync as me}from"child_process";import{promisify as he}from"util";import"node:crypto";import{format as ge,formatDistanceToNow as _e}from"date-fns";import{fileURLToPath as ve}from"url";import ye from"dotenv";const be=600*1e3,xe=3,Se=[`add-dependency`,`remove-dependency`,`validate-dependencies`,`fix-dependencies`,`clear-subtasks`,`models`,`generate`];function Ce(e){return Se.includes(e)}function we(e){let{hasValidSession:t,briefName:n,storageType:r,commandName:i}=e;return!Ce(i)||!t||r!==`api`?{isBlocked:!1,commandName:i}:{isBlocked:!0,briefName:n||`remote brief`,commandName:i}}const v={FILE_NOT_FOUND:`FILE_NOT_FOUND`,FILE_READ_ERROR:`FILE_READ_ERROR`,FILE_WRITE_ERROR:`FILE_WRITE_ERROR`,PARSE_ERROR:`PARSE_ERROR`,JSON_PARSE_ERROR:`JSON_PARSE_ERROR`,YAML_PARSE_ERROR:`YAML_PARSE_ERROR`,VALIDATION_ERROR:`VALIDATION_ERROR`,SCHEMA_VALIDATION_ERROR:`SCHEMA_VALIDATION_ERROR`,TYPE_VALIDATION_ERROR:`TYPE_VALIDATION_ERROR`,API_ERROR:`API_ERROR`,NETWORK_ERROR:`NETWORK_ERROR`,AUTHENTICATION_ERROR:`AUTHENTICATION_ERROR`,AUTHORIZATION_ERROR:`AUTHORIZATION_ERROR`,TASK_NOT_FOUND:`TASK_NOT_FOUND`,TASK_DEPENDENCY_ERROR:`TASK_DEPENDENCY_ERROR`,TASK_STATUS_ERROR:`TASK_STATUS_ERROR`,STORAGE_ERROR:`STORAGE_ERROR`,DATABASE_ERROR:`DATABASE_ERROR`,CONFIG_ERROR:`CONFIG_ERROR`,MISSING_CONFIGURATION:`MISSING_CONFIGURATION`,INVALID_CONFIGURATION:`INVALID_CONFIGURATION`,PROVIDER_ERROR:`PROVIDER_ERROR`,PROVIDER_NOT_FOUND:`PROVIDER_NOT_FOUND`,PROVIDER_INITIALIZATION_ERROR:`PROVIDER_INITIALIZATION_ERROR`,INTERNAL_ERROR:`INTERNAL_ERROR`,INVALID_INPUT:`INVALID_INPUT`,NOT_IMPLEMENTED:`NOT_IMPLEMENTED`,UNKNOWN_ERROR:`UNKNOWN_ERROR`,NOT_FOUND:`NOT_FOUND`,NO_BRIEF_SELECTED:`NO_BRIEF_SELECTED`};var y=class e extends Error{code;context;cause;timestamp;constructor(t,n=v.UNKNOWN_ERROR,r={},i){super(t),this.name=`TaskMasterError`,this.code=n,this.cause=i,this.timestamp=new Date,this.context={timestamp:this.timestamp,...r},Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e),i?.stack&&(this.stack=`${this.stack}\nCaused by: ${i.stack}`)}getUserMessage(){return this.context.userMessage||this.message}getSanitizedDetails(){let{details:e,resource:t,operation:n}=this.context;return{code:this.code,message:this.getUserMessage(),...t&&{resource:t},...n&&{operation:n},...e&&typeof e==`object`&&!this.containsSensitiveInfo(e)&&{details:e}}}containsSensitiveInfo(e){if(typeof e!=`object`||!e)return!1;let t=[`password`,`token`,`key`,`secret`,`auth`,`credential`],n=JSON.stringify(e).toLowerCase();return t.some(e=>n.includes(e))}toJSON(){let t={name:this.name,message:this.message,code:this.code,context:this.context,stack:this.stack};return this.cause&&(this.cause instanceof e?t.cause=this.cause.toJSON():t.cause={name:this.cause.name,message:this.cause.message,code:v.UNKNOWN_ERROR,context:{},stack:this.cause.stack}),t}toString(){let e=`${this.name}[${this.code}]: ${this.message}`;return this.context.operation&&(e+=` (operation: ${this.context.operation})`),this.context.resource&&(e+=` (resource: ${this.context.resource})`),this.cause&&(e+=`\nCaused by: ${this.cause.toString()}`),e}is(e){return this.code===e}hasCode(t){return this.is(t)?!0:this.cause instanceof e?this.cause.hasCode(t):!1}withContext(t){return new e(this.message,this.code,{...this.context,...t},this.cause)}wrap(t,n=v.INTERNAL_ERROR,r={}){return new e(t,n,r,this)}};let b=function(e){return e[e.SILENT=0]=`SILENT`,e[e.ERROR=1]=`ERROR`,e[e.WARN=2]=`WARN`,e[e.INFO=3]=`INFO`,e[e.DEBUG=4]=`DEBUG`,e}({});var Te=class e{config;static DEFAULT_CONFIG={level:b.SILENT,silent:!1,prefix:``,timestamp:!1,colors:!0,mcpMode:!1,logCallback:void 0};constructor(t={}){let n={};if((process.env.MCP_MODE===`true`||process.env.TASK_MASTER_MCP===`true`)&&(n.mcpMode=!0),(process.env.TASK_MASTER_SILENT===`true`||process.env.TM_SILENT===`true`)&&(n.silent=!0),process.env.TASK_MASTER_LOG_LEVEL||process.env.TM_LOG_LEVEL){let e=(process.env.TASK_MASTER_LOG_LEVEL||process.env.TM_LOG_LEVEL||``).toUpperCase();e in b&&(n.level=b[e])}(process.env.NO_COLOR===`true`||process.env.TASK_MASTER_NO_COLOR===`true`)&&(n.colors=!1),this.config={...e.DEFAULT_CONFIG,...t,...n},this.config.mcpMode&&!this.config.logCallback&&(this.config.silent=!0)}shouldLog(e){return this.config.logCallback?e<=this.config.level:this.config.silent||this.config.mcpMode?!1:e<=this.config.level}formatMessage(e,t,...n){let r=``;if(this.config.timestamp){let e=new Date().toISOString();r+=this.config.colors?i.gray(`[${e}] `):`[${e}] `}if(this.config.prefix&&(r+=this.config.colors?i.cyan(`[${this.config.prefix}] `):`[${this.config.prefix}] `),this.config.colors)switch(e){case b.ERROR:t=i.red(t);break;case b.WARN:t=i.yellow(t);break;case b.INFO:break;case b.DEBUG:t=i.gray(t);break}return r+=t,n.length>0&&(r+=` `+n.map(e=>typeof e==`object`?JSON.stringify(e,null,2):String(e)).join(` `)),r}isLogObject(e){return typeof e==`object`&&!!e&&`info`in e&&`warn`in e&&`error`in e&&`debug`in e}output(e,t,n,...r){let i=this.formatMessage(e,n,...r);if(this.config.logCallback){if(this.isLogObject(this.config.logCallback)){let e=t.toLowerCase();e in this.config.logCallback&&this.config.logCallback[e](i)}else this.config.logCallback(t.toLowerCase(),i);return}switch(e){case b.ERROR:console.error(i);break;case b.WARN:console.warn(i);break;default:console.log(i);break}}error(e,...t){this.shouldLog(b.ERROR)&&this.output(b.ERROR,`ERROR`,e,...t)}warn(e,...t){this.shouldLog(b.WARN)&&this.output(b.WARN,`WARN`,e,...t)}info(e,...t){this.shouldLog(b.INFO)&&this.output(b.INFO,`INFO`,e,...t)}debug(e,...t){this.shouldLog(b.DEBUG)&&this.output(b.DEBUG,`DEBUG`,e,...t)}log(e,...t){if(this.config.logCallback){let n=t.length>0?[e,...t].join(` `):e;this.isLogObject(this.config.logCallback)?this.config.logCallback.info(n):this.config.logCallback(`log`,n);return}this.config.silent||this.config.mcpMode||(t.length>0?console.log(e,...t):console.log(e))}setConfig(e){this.config={...this.config,...e},this.config.mcpMode&&!this.config.logCallback&&(this.config.silent=!0)}getConfig(){return{...this.config}}child(t,n){let r=this.config.prefix?`${this.config.prefix}:${t}`:t;return new e({...this.config,...n,prefix:r})}};let Ee=null;const De=new Map;function Oe(e){return new Te(e)}function x(e,t){return e?(De.has(e)||De.set(e,Oe({prefix:e,...t})),De.get(e)):(Ee||=Oe(t),Ee)}const ke=c.join(process.env.HOME||process.env.USERPROFILE||`~`,`.taskmaster`,`session.json`);var Ae=class{storage=new Map;persistPath;logger=x(`SupabaseSessionStorage`);writer;initPromise;constructor(e=ke){this.persistPath=e,this.writer=new d(e),this.initPromise=this.load()}async load(){try{let e=c.dirname(this.persistPath);if(await u.mkdir(e,{recursive:!0,mode:448}),s.existsSync(this.persistPath)){let e=JSON.parse(await u.readFile(this.persistPath,`utf8`));Object.entries(e).forEach(([e,t])=>this.storage.set(e,t)),this.logger.debug(`Loaded session from disk`,{keys:Array.from(this.storage.keys())})}}catch(e){this.logger.error(`Failed to load session:`,e)}}async persist(){try{let e=Object.fromEntries(this.storage),t=JSON.stringify(e,null,2);await this.writer.write(t+`
|
|
2
|
-
`),this.logger.debug(`Persisted session to disk (steno)`)}catch(e){this.logger.error(`Failed to persist session:`,e)}}async getItem(e){await this.initPromise;let t=this.storage.get(e)??null;return this.logger.debug(`getItem called`,{key:e,hasValue:!!t}),t}async setItem(e,t){await this.initPromise,this.logger.debug(`setItem called`,{key:e}),this.storage.set(e,t),await this.persist()}async removeItem(e){await this.initPromise,this.logger.debug(`removeItem called`,{key:e}),this.storage.delete(e),await this.persist()}async clear(){await this.initPromise,this.logger.debug(`clear called`),this.storage.clear(),await this.persist()}},S=class extends Error{mfaChallenge;constructor(e,t,n,r){super(e),this.code=t,this.cause=n,this.name=`AuthenticationError`,this.mfaChallenge=r,n&&n instanceof Error&&(this.stack=`${this.stack}\nCaused by: ${n.stack}`)}};function C(e){return o(e)}const je={refresh_token_not_found:`Your session has expired. Please log in again with: task-master login`,refresh_token_already_used:`Your session has expired (token was already used). Please log in again with: task-master login`,invalid_refresh_token:`Your session has expired (invalid token). Please log in again with: task-master login`,session_expired:`Your session has expired. Please log in again with: task-master login`,user_not_found:`User account not found. Please log in again with: task-master login`,invalid_credentials:`Invalid credentials. Please log in again with: task-master login`},Me=[`refresh_token_not_found`,`refresh_token_already_used`];function w(e){return C(e)?Me.includes(e.code||``):!1}function Ne(e,t){let n=e.code,r=n&&je[n]||`${t}: ${e.message}`,i=`REFRESH_FAILED`;return n===`refresh_token_not_found`||n===`refresh_token_already_used`||n===`invalid_refresh_token`||n===`session_expired`||n===`user_not_found`?i=`NOT_AUTHENTICATED`:n===`invalid_credentials`&&(i=`INVALID_CREDENTIALS`),new S(r,i,e)}function Pe(){let{publicKey:e,privateKey:t}=f.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`}});return{publicKey:e,privateKey:t}}function Fe(e,t){try{let n=Buffer.from(e.encrypted_key,`base64`),r=Buffer.from(e.encrypted_data,`base64`),i=Buffer.from(e.iv,`base64`),a=Buffer.from(e.auth_tag,`base64`),o=f.privateDecrypt({key:t,padding:f.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},n),s=f.createDecipheriv(`aes-256-gcm`,o,i);s.setAuthTag(a);let c=Buffer.concat([s.update(r),s.final()]);return JSON.parse(c.toString(`utf8`))}catch(e){throw new S(`Token decryption failed: ${e instanceof Error?e.message:`Unknown error`}`,`DECRYPTION_FAILED`,e)}}var Ie=class e{static instance=null;client=null;sessionStorage;logger=x(`SupabaseAuthClient`);constructor(){this.sessionStorage=new Ae}static getInstance(){return e.instance||=new e,e.instance}static resetInstance(){e.instance&&(e.instance.client=null),e.instance=null}getClient(){if(!this.client){let e=process.env.TM_SUPABASE_URL||process.env.TM_PUBLIC_SUPABASE_URL||`https://tryhamster.com`,t=process.env.TM_SUPABASE_ANON_KEY||process.env.TM_PUBLIC_SUPABASE_ANON_KEY||`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5zdHhhdGRwbnNmYWxja3hhd3R6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDg3MzU3NTYsImV4cCI6MjA2NDMxMTc1Nn0.GF897_2zXRxl4pkeQ89-7xF4TkJfJuYPWKhv1bTbv9k`;if(!e||!t)throw new S(`Supabase configuration missing. Please set TM_SUPABASE_URL and TM_SUPABASE_ANON_KEY (runtime) or TM_PUBLIC_SUPABASE_URL and TM_PUBLIC_SUPABASE_ANON_KEY (build-time) environment variables.`,`CONFIG_MISSING`);this.client=a(e,t,{auth:{storage:this.sessionStorage,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!1}})}return this.client}async initialize(){let e=this.getClient();try{let{data:{session:t},error:n}=await e.auth.getSession();return n?(w(n)||this.logger.warn(`Failed to restore session:`,n),null):(t&&this.logger.info(`Session restored successfully`),t)}catch(e){return w(e)?this.logger.debug(`Session not available (expected during MFA flow)`):C(e)?this.logger.warn(`Session expired or invalid`):this.logger.error(`Error initializing session:`,e),null}}async signInWithPKCE(){let e=this.getClient();try{let{data:t,error:n}=await e.auth.signInWithOAuth({provider:`github`,options:{redirectTo:process.env.TM_AUTH_CALLBACK_URL||`http://localhost:3421/auth/callback`,scopes:`email`}});if(n)throw new S(`Failed to initiate PKCE flow: ${n.message}`,`PKCE_INIT_FAILED`);if(!t?.url)throw new S(`No authorization URL returned`,`INVALID_RESPONSE`);return{url:t.url,codeVerifier:``}}catch(e){throw e instanceof S?e:new S(`Failed to start PKCE flow: ${e.message}`,`PKCE_FAILED`)}}async exchangeCodeForSession(e){let t=this.getClient();try{let{data:n,error:r}=await t.auth.exchangeCodeForSession(e);if(r)throw new S(`Failed to exchange code: ${r.message}`,`CODE_EXCHANGE_FAILED`);if(!n?.session)throw new S(`No session returned from code exchange`,`INVALID_RESPONSE`);return this.logger.info(`Successfully exchanged code for session`),n.session}catch(e){throw e instanceof S?e:new S(`Code exchange failed: ${e.message}`,`CODE_EXCHANGE_FAILED`)}}async getSession(){let e=this.getClient();try{let{data:{session:t},error:n}=await e.auth.getSession();return n?(w(n)||this.logger.warn(`Failed to get session:`,n),null):t}catch(e){return w(e)?this.logger.debug(`Session not available (expected during MFA flow)`):C(e)?this.logger.warn(`Session expired or invalid`):this.logger.error(`Error getting session:`,e),null}}async refreshSession(){let e=this.getClient();try{this.logger.info(`Refreshing session...`);let{data:{session:t},error:n}=await e.auth.refreshSession();if(n)throw this.logger.error(`Failed to refresh session:`,n),Ne(n,`Failed to refresh session`);return t&&this.logger.info(`Successfully refreshed session`),t}catch(e){throw e instanceof S?e:C(e)?Ne(e,`Session refresh failed`):new S(`Failed to refresh session: ${e.message}`,`REFRESH_FAILED`)}}async getUser(){let e=this.getClient();try{let{data:{user:t},error:n}=await e.auth.getUser();return n?(this.logger.warn(`Failed to get user:`,n),null):t}catch(e){return this.logger.error(`Error getting user:`,e),null}}async signOut(){let e=this.getClient();try{let{error:t}=await e.auth.signOut({scope:`local`});t&&this.logger.warn(`Failed to sign out:`,t),this.sessionStorage.clear()}catch(e){this.logger.error(`Error during sign out:`,e)}}async setSession(e){let t=this.getClient();try{let{error:n}=await t.auth.setSession({access_token:e.access_token,refresh_token:e.refresh_token});if(n)throw new S(`Failed to set session: ${n.message}`,`SESSION_SET_FAILED`);this.logger.info(`Session set successfully`)}catch(e){throw e instanceof S?e:new S(`Failed to set session: ${e.message}`,`SESSION_SET_FAILED`)}}async handleRecoverableError(e,t,n){return!t&&w(e)?(this.logger.debug(`MFA-expected error during token verification, clearing stale session and retrying`),await this.sessionStorage.clear(),n()):null}async verifyOneTimeCode(e,t=!1){let n=this.getClient(),r=()=>this.verifyOneTimeCode(e,!0);try{this.logger.info(`Verifying authentication token...`);let{data:i,error:a}=await n.auth.verifyOtp({token_hash:e,type:`magiclink`});if(a){let e=await this.handleRecoverableError(a,t,r);if(e)return e;throw this.logger.error(`Failed to verify token:`,a),Ne(a,`Failed to verify token`)}if(!i?.session)throw new S(`No session returned from token verification`,`INVALID_RESPONSE`);return this.logger.info(`Successfully verified authentication token`),i.session}catch(e){if(e instanceof S)throw e;if(C(e)){let n=await this.handleRecoverableError(e,t,r);if(n)return n;throw Ne(e,`Token verification failed`)}throw new S(`Token verification failed: ${e.message}`,`CODE_AUTH_FAILED`)}}async checkMFARequired(){let e=this.getClient();try{let{data:{session:t},error:n}=await e.auth.getSession();if(n||!t)return this.logger.warn(`No session available to check MFA`),{required:!1};let{data:r,error:i}=await e.auth.mfa.getAuthenticatorAssuranceLevel();if(i)return this.logger.warn(`Failed to get AAL:`,i),{required:!1};if(r?.currentLevel===`aal2`)return this.logger.info(`Session already at AAL2, MFA not required`),{required:!1};let{data:a,error:o}=await e.auth.mfa.listFactors();if(o)return this.logger.warn(`Failed to list MFA factors:`,o),{required:!1};let s=a?.totp?.filter(e=>e.status===`verified`);if(!s||s.length===0)return this.logger.info(`No verified MFA factors found`),{required:!1};let c=s[0];return this.logger.info(`MFA verification required`,{factorId:c.id,factorType:c.factor_type}),{required:!0,factorId:c.id,factorType:c.factor_type}}catch(e){return this.logger.error(`Error checking MFA requirement:`,e),{required:!1}}}async verifyMFA(e,t){let n=this.getClient();try{this.logger.info(`Verifying MFA code...`);let{data:r,error:i}=await n.auth.mfa.challenge({factorId:e});if(i||!r)throw new S(`Failed to create MFA challenge: ${i?.message||`Unknown error`}`,`MFA_VERIFICATION_FAILED`);let{data:a,error:o}=await n.auth.mfa.verify({factorId:e,challengeId:r.id,code:t});if(o)throw this.logger.error(`MFA verification failed:`,o),new S(`Invalid MFA code: ${o.message}`,`INVALID_MFA_CODE`);if(!a)throw new S(`No data returned from MFA verification`,`INVALID_RESPONSE`);let{data:{session:s},error:c}=await n.auth.refreshSession();if(c||!s)throw new S(`Failed to refresh session after MFA: ${c?.message||`No session returned`}`,`REFRESH_FAILED`);return this.logger.info(`Successfully verified MFA, session upgraded to AAL2`),s}catch(e){throw e instanceof S?e:new S(`MFA verification failed: ${e.message}`,`MFA_VERIFICATION_FAILED`)}}};const Le=c.join(process.env.HOME||process.env.USERPROFILE||`~`,`.taskmaster`,`context.json`);var Re=class e{static instance=null;logger=x(`ContextStore`);contextPath;constructor(e=Le){this.contextPath=e}static getInstance(t){return e.instance||=new e(t),e.instance}static resetInstance(){e.instance=null}getContext(){try{if(!s.existsSync(this.contextPath))return null;let e=JSON.parse(s.readFileSync(this.contextPath,`utf8`));return this.logger.debug(`Loaded context from disk`),e}catch(e){return this.logger.error(`Failed to read context:`,e),null}}saveContext(e){try{let t={...this.getContext()||{},...e,lastUpdated:new Date().toISOString()},n=c.dirname(this.contextPath);s.existsSync(n)||s.mkdirSync(n,{recursive:!0,mode:448});let r=`${this.contextPath}.tmp`;s.writeFileSync(r,JSON.stringify(t,null,2),{mode:384}),s.renameSync(r,this.contextPath),this.logger.debug(`Saved context to disk`)}catch(e){throw new S(`Failed to save context: ${e.message}`,`SAVE_FAILED`,e)}}updateUserContext(e){let t=this.getContext(),n={...t?.selectedContext||{},...e,updatedAt:new Date().toISOString()};this.saveContext({...t,selectedContext:n})}getUserContext(){return this.getContext()?.selectedContext||null}clearUserContext(){let e=this.getContext();if(e){let{selectedContext:t,...n}=e;this.saveContext(n)}}clearContext(){try{s.existsSync(this.contextPath)&&(s.unlinkSync(this.contextPath),this.logger.debug(`Cleared context from disk`))}catch(e){throw new S(`Failed to clear context: ${e.message}`,`CLEAR_FAILED`,e)}}hasContext(){return this.getContext()!==null}getContextPath(){return this.contextPath}},ze=`@hhsw2015/task-master-ai`,Be=`0.43.7`;const Ve=[`anthropic`,`openai`,`google`,`zai`,`zai-coding`,`perplexity`,`xai`,`groq`,`mistral`,`azure`,`openrouter`,`bedrock`,`ollama`],T={AZURE:`azure`,VERTEX:`vertex`,BEDROCK:`bedrock`,OPENROUTER:`openrouter`,OLLAMA:`ollama`,LMSTUDIO:`lmstudio`,OPENAI_COMPATIBLE:`openai-compatible`,CLAUDE_CODE:`claude-code`,MCP:`mcp`,GEMINI_CLI:`gemini-cli`,GROK_CLI:`grok-cli`,CODEX_CLI:`codex-cli`},He=Object.values(T),Ue=[...new Set([...Ve,...He])],We=`.taskmaster/tasks/tasks.json`,Ge=[`.taskmaster`,`.taskmaster/config.json`,We,`.taskmasterconfig`],Ke=`.git,.svn,.hg,.fossil,.github,.gitlab,.circleci,.travis.yml,.jenkins,.buildkite,.vscode,.idea,.project,.devcontainer,package-lock.json,yarn.lock,pnpm-lock.yaml,bun.lockb,bun.lock,deno.lock,deno.json,deno.jsonc,package.json,lerna.json,nx.json,turbo.json,rush.json,pnpm-workspace.yaml,Cargo.toml,Cargo.lock,go.mod,go.sum,go.work,pyproject.toml,setup.py,setup.cfg,poetry.lock,Pipfile,Pipfile.lock,uv.lock,Gemfile,Gemfile.lock,composer.json,composer.lock,build.gradle,build.gradle.kts,settings.gradle,settings.gradle.kts,pom.xml,build.sbt,project.clj,deps.edn,mix.exs,rebar.config,pubspec.yaml,Package.swift,CMakeLists.txt,Makefile,meson.build,BUILD.bazel,WORKSPACE,flake.nix,shell.nix,default.nix,Dockerfile,docker-compose.yml,docker-compose.yaml,Containerfile,kubernetes.yml,kubernetes.yaml,helm/Chart.yaml`.split(`,`),qe=[`tasks/tasks.json`,`tasks.json`,...Ke,`requirements.txt`];[...Ge,...qe];const Je=Be||`unknown`,Ye=[`pending`,`in-progress`,`done`,`deferred`,`cancelled`,`blocked`,`review`],Xe=[`done`,`completed`,`cancelled`];function Ze(e){return Xe.includes(e)}const Qe=[`text`,`json`,`compact`],$e={done:`✓`,completed:`✓`,"in-progress":`►`,blocked:`⭕`,pending:`○`,deferred:`⏸`,cancelled:`✗`,review:`👁`};function et(){return process.env.TM_BASE_DOMAIN||process.env.TM_PUBLIC_BASE_DOMAIN||`https://tryhamster.com`}function tt(){return{baseUrl:et(),configDir:c.join(p.homedir(),`.taskmaster`),configFile:c.join(p.homedir(),`.taskmaster`,`auth.json`)}}function nt(e){return{...tt(),...e}}new Proxy({},{get(e,t){return tt()[t]}});var rt=class{logger=x(`OAuthService`);contextStore;supabaseClient;configOverrides;authorizationUrl=null;keyPair=null;get baseUrl(){return nt(this.configOverrides).baseUrl}constructor(e,t,n={}){this.contextStore=e,this.supabaseClient=t,this.configOverrides=n}async authenticate(e={}){let{openBrowser:t,timeout:n=3e5,onAuthUrl:r,onWaitingForAuth:i,onSuccess:a,onError:o}=e;try{return await this.authenticateWithBackendPKCE({openBrowser:t,timeout:n,onAuthUrl:r,onWaitingForAuth:i,onSuccess:a})}catch(e){let t=e instanceof S?e:new S(`OAuth authentication failed: ${e.message}`,`OAUTH_FAILED`,e);throw o&&t.code!==`MFA_REQUIRED`&&o(t),t}}async authenticateWithBackendPKCE(e){let{openBrowser:t,timeout:n=3e5,onAuthUrl:r,onWaitingForAuth:i,onSuccess:a}=e;this.keyPair=Pe(),this.logger.debug(`Generated RSA keypair for E2E encryption`);let o=await this.startBackendFlow();if(!o.success||!o.flow_id)throw new S(o.message||`Failed to start authentication flow`,`START_FLOW_FAILED`);let{flow_id:s,verification_url:c,poll_interval:l=2}=o;if(this.authorizationUrl=c||null,r&&c&&r(c),t&&c)try{await t(c),this.logger.debug(`Browser opened successfully with URL:`,c)}catch(e){this.logger.warn(`Failed to open browser automatically:`,e)}i&&i();let u=await this.pollForCompletion(s,l*1e3,n);u.refreshToken||this.logger.warn(`No refresh token received from server - session refresh will not work`);let d={access_token:u.token,refresh_token:u.refreshToken??``,expires_in:u.expiresAt?Math.floor((new Date(u.expiresAt).getTime()-Date.now())/1e3):3600,token_type:`bearer`,user:{id:u.userId,email:u.email,app_metadata:{},user_metadata:{},aud:`authenticated`,created_at:``}};return await this.supabaseClient.setSession(d),this.contextStore.saveContext({userId:u.userId,email:u.email}),await this.checkAndThrowIfMFARequired(),a&&a(u),u}async startBackendFlow(){let e=`${this.baseUrl}/api/auth/cli/start`;if(!this.keyPair)throw new S(`Keypair not generated before starting flow`,`INTERNAL_ERROR`);try{let t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`,"User-Agent":`TaskMasterCLI/${this.getCliVersion()}`},body:JSON.stringify({name:`Task Master CLI`,version:this.getCliVersion(),device:p.hostname(),user:p.userInfo().username,platform:p.platform(),public_key:this.keyPair.publicKey})});if(!t.ok)throw new S((await t.json().catch(()=>({}))).message||`HTTP ${t.status}`,`START_FLOW_FAILED`);return await t.json()}catch(e){throw e instanceof S?e:(this.logger.warn(`Failed to reach backend for PKCE flow:`,e),new S(`Unable to reach authentication server`,`BACKEND_UNREACHABLE`,e))}}async pollForCompletion(e,t,n){let r=`${this.baseUrl}/api/auth/cli/status?flow_id=${e}`,i=Date.now();if(!this.keyPair)throw new S(`Keypair not available for decryption`,`INTERNAL_ERROR`);for(;Date.now()-i<n;){try{let e=await fetch(r,{method:`GET`,headers:{"User-Agent":`TaskMasterCLI/${this.getCliVersion()}`}});if(!e.ok){let t=await e.json().catch(()=>({}));throw e.status===404?new S(`Authentication flow expired or not found`,`FLOW_NOT_FOUND`):new S(t.message||`HTTP ${e.status}`,`POLL_FAILED`)}let t=await e.json();if(!t.success)throw new S(t.message||`Failed to check status`,`POLL_FAILED`);switch(t.status){case`complete`:{if(!t.encrypted_tokens)throw new S(`Server returned no encrypted tokens`,`MISSING_TOKENS`);let e=Fe(t.encrypted_tokens,this.keyPair.privateKey);return this.logger.debug(`Successfully decrypted authentication tokens`),{token:e.access_token,refreshToken:e.refresh_token,userId:e.user_id,email:e.email,expiresAt:e.expires_in?new Date(Date.now()+e.expires_in*1e3).toISOString():void 0,tokenType:`standard`,savedAt:new Date().toISOString()}}case`failed`:throw new S(t.error_description||t.error||`Authentication failed`,`OAUTH_FAILED`);case`expired`:throw new S(`Authentication flow expired`,`AUTH_TIMEOUT`);case`pending`:case`authenticating`:this.logger.debug(`Flow status: ${t.status}, continuing to poll`);break;default:this.logger.warn(`Unknown flow status: ${t.status}`)}}catch(e){if(e instanceof S)throw e;this.logger.debug(`Poll request failed, will retry:`,e)}await new Promise(e=>setTimeout(e,t))}throw new S(`Authentication timeout`,`AUTH_TIMEOUT`)}getCliVersion(){return Je}getAuthorizationUrl(){return this.authorizationUrl}async checkAndThrowIfMFARequired(){let e=await this.supabaseClient.checkMFARequired();if(e.required)throw!e.factorId||!e.factorType?(this.logger.error(`MFA required but factor information is incomplete`,{mfaCheck:e}),new S(`MFA is required but the server returned incomplete factor configuration. Please contact support or try re-enrolling MFA.`,`MFA_REQUIRED_INCOMPLETE`)):(this.logger.info(`MFA verification required after OAuth login`,{factorId:e.factorId,factorType:e.factorType}),new S(`MFA verification required. Please provide your authentication code.`,`MFA_REQUIRED`,void 0,{factorId:e.factorId,factorType:e.factorType}))}},it=class{logger=x(`OrganizationService`);constructor(e){this.supabaseClient=e}async getOrganizations(){try{let{data:e,error:t}=await this.supabaseClient.from(`user_accounts`).select(`
|
|
2
|
+
`),this.logger.debug(`Persisted session to disk (steno)`)}catch(e){this.logger.error(`Failed to persist session:`,e)}}async getItem(e){await this.initPromise;let t=this.storage.get(e)??null;return this.logger.debug(`getItem called`,{key:e,hasValue:!!t}),t}async setItem(e,t){await this.initPromise,this.logger.debug(`setItem called`,{key:e}),this.storage.set(e,t),await this.persist()}async removeItem(e){await this.initPromise,this.logger.debug(`removeItem called`,{key:e}),this.storage.delete(e),await this.persist()}async clear(){await this.initPromise,this.logger.debug(`clear called`),this.storage.clear(),await this.persist()}},S=class extends Error{mfaChallenge;constructor(e,t,n,r){super(e),this.code=t,this.cause=n,this.name=`AuthenticationError`,this.mfaChallenge=r,n&&n instanceof Error&&(this.stack=`${this.stack}\nCaused by: ${n.stack}`)}};function C(e){return o(e)}const je={refresh_token_not_found:`Your session has expired. Please log in again with: task-master login`,refresh_token_already_used:`Your session has expired (token was already used). Please log in again with: task-master login`,invalid_refresh_token:`Your session has expired (invalid token). Please log in again with: task-master login`,session_expired:`Your session has expired. Please log in again with: task-master login`,user_not_found:`User account not found. Please log in again with: task-master login`,invalid_credentials:`Invalid credentials. Please log in again with: task-master login`},Me=[`refresh_token_not_found`,`refresh_token_already_used`];function w(e){return C(e)?Me.includes(e.code||``):!1}function Ne(e,t){let n=e.code,r=n&&je[n]||`${t}: ${e.message}`,i=`REFRESH_FAILED`;return n===`refresh_token_not_found`||n===`refresh_token_already_used`||n===`invalid_refresh_token`||n===`session_expired`||n===`user_not_found`?i=`NOT_AUTHENTICATED`:n===`invalid_credentials`&&(i=`INVALID_CREDENTIALS`),new S(r,i,e)}function Pe(){let{publicKey:e,privateKey:t}=f.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`}});return{publicKey:e,privateKey:t}}function Fe(e,t){try{let n=Buffer.from(e.encrypted_key,`base64`),r=Buffer.from(e.encrypted_data,`base64`),i=Buffer.from(e.iv,`base64`),a=Buffer.from(e.auth_tag,`base64`),o=f.privateDecrypt({key:t,padding:f.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},n),s=f.createDecipheriv(`aes-256-gcm`,o,i);s.setAuthTag(a);let c=Buffer.concat([s.update(r),s.final()]);return JSON.parse(c.toString(`utf8`))}catch(e){throw new S(`Token decryption failed: ${e instanceof Error?e.message:`Unknown error`}`,`DECRYPTION_FAILED`,e)}}var Ie=class e{static instance=null;client=null;sessionStorage;logger=x(`SupabaseAuthClient`);constructor(){this.sessionStorage=new Ae}static getInstance(){return e.instance||=new e,e.instance}static resetInstance(){e.instance&&(e.instance.client=null),e.instance=null}getClient(){if(!this.client){let e=process.env.TM_SUPABASE_URL||process.env.TM_PUBLIC_SUPABASE_URL||`https://tryhamster.com`,t=process.env.TM_SUPABASE_ANON_KEY||process.env.TM_PUBLIC_SUPABASE_ANON_KEY||`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5zdHhhdGRwbnNmYWxja3hhd3R6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDg3MzU3NTYsImV4cCI6MjA2NDMxMTc1Nn0.GF897_2zXRxl4pkeQ89-7xF4TkJfJuYPWKhv1bTbv9k`;if(!e||!t)throw new S(`Supabase configuration missing. Please set TM_SUPABASE_URL and TM_SUPABASE_ANON_KEY (runtime) or TM_PUBLIC_SUPABASE_URL and TM_PUBLIC_SUPABASE_ANON_KEY (build-time) environment variables.`,`CONFIG_MISSING`);this.client=a(e,t,{auth:{storage:this.sessionStorage,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!1}})}return this.client}async initialize(){let e=this.getClient();try{let{data:{session:t},error:n}=await e.auth.getSession();return n?(w(n)||this.logger.warn(`Failed to restore session:`,n),null):(t&&this.logger.info(`Session restored successfully`),t)}catch(e){return w(e)?this.logger.debug(`Session not available (expected during MFA flow)`):C(e)?this.logger.warn(`Session expired or invalid`):this.logger.error(`Error initializing session:`,e),null}}async signInWithPKCE(){let e=this.getClient();try{let{data:t,error:n}=await e.auth.signInWithOAuth({provider:`github`,options:{redirectTo:process.env.TM_AUTH_CALLBACK_URL||`http://localhost:3421/auth/callback`,scopes:`email`}});if(n)throw new S(`Failed to initiate PKCE flow: ${n.message}`,`PKCE_INIT_FAILED`);if(!t?.url)throw new S(`No authorization URL returned`,`INVALID_RESPONSE`);return{url:t.url,codeVerifier:``}}catch(e){throw e instanceof S?e:new S(`Failed to start PKCE flow: ${e.message}`,`PKCE_FAILED`)}}async exchangeCodeForSession(e){let t=this.getClient();try{let{data:n,error:r}=await t.auth.exchangeCodeForSession(e);if(r)throw new S(`Failed to exchange code: ${r.message}`,`CODE_EXCHANGE_FAILED`);if(!n?.session)throw new S(`No session returned from code exchange`,`INVALID_RESPONSE`);return this.logger.info(`Successfully exchanged code for session`),n.session}catch(e){throw e instanceof S?e:new S(`Code exchange failed: ${e.message}`,`CODE_EXCHANGE_FAILED`)}}async getSession(){let e=this.getClient();try{let{data:{session:t},error:n}=await e.auth.getSession();return n?(w(n)||this.logger.warn(`Failed to get session:`,n),null):t}catch(e){return w(e)?this.logger.debug(`Session not available (expected during MFA flow)`):C(e)?this.logger.warn(`Session expired or invalid`):this.logger.error(`Error getting session:`,e),null}}async refreshSession(){let e=this.getClient();try{this.logger.info(`Refreshing session...`);let{data:{session:t},error:n}=await e.auth.refreshSession();if(n)throw this.logger.error(`Failed to refresh session:`,n),Ne(n,`Failed to refresh session`);return t&&this.logger.info(`Successfully refreshed session`),t}catch(e){throw e instanceof S?e:C(e)?Ne(e,`Session refresh failed`):new S(`Failed to refresh session: ${e.message}`,`REFRESH_FAILED`)}}async getUser(){let e=this.getClient();try{let{data:{user:t},error:n}=await e.auth.getUser();return n?(this.logger.warn(`Failed to get user:`,n),null):t}catch(e){return this.logger.error(`Error getting user:`,e),null}}async signOut(){let e=this.getClient();try{let{error:t}=await e.auth.signOut({scope:`local`});t&&this.logger.warn(`Failed to sign out:`,t),this.sessionStorage.clear()}catch(e){this.logger.error(`Error during sign out:`,e)}}async setSession(e){let t=this.getClient();try{let{error:n}=await t.auth.setSession({access_token:e.access_token,refresh_token:e.refresh_token});if(n)throw new S(`Failed to set session: ${n.message}`,`SESSION_SET_FAILED`);this.logger.info(`Session set successfully`)}catch(e){throw e instanceof S?e:new S(`Failed to set session: ${e.message}`,`SESSION_SET_FAILED`)}}async handleRecoverableError(e,t,n){return!t&&w(e)?(this.logger.debug(`MFA-expected error during token verification, clearing stale session and retrying`),await this.sessionStorage.clear(),n()):null}async verifyOneTimeCode(e,t=!1){let n=this.getClient(),r=()=>this.verifyOneTimeCode(e,!0);try{this.logger.info(`Verifying authentication token...`);let{data:i,error:a}=await n.auth.verifyOtp({token_hash:e,type:`magiclink`});if(a){let e=await this.handleRecoverableError(a,t,r);if(e)return e;throw this.logger.error(`Failed to verify token:`,a),Ne(a,`Failed to verify token`)}if(!i?.session)throw new S(`No session returned from token verification`,`INVALID_RESPONSE`);return this.logger.info(`Successfully verified authentication token`),i.session}catch(e){if(e instanceof S)throw e;if(C(e)){let n=await this.handleRecoverableError(e,t,r);if(n)return n;throw Ne(e,`Token verification failed`)}throw new S(`Token verification failed: ${e.message}`,`CODE_AUTH_FAILED`)}}async checkMFARequired(){let e=this.getClient();try{let{data:{session:t},error:n}=await e.auth.getSession();if(n||!t)return this.logger.warn(`No session available to check MFA`),{required:!1};let{data:r,error:i}=await e.auth.mfa.getAuthenticatorAssuranceLevel();if(i)return this.logger.warn(`Failed to get AAL:`,i),{required:!1};if(r?.currentLevel===`aal2`)return this.logger.info(`Session already at AAL2, MFA not required`),{required:!1};let{data:a,error:o}=await e.auth.mfa.listFactors();if(o)return this.logger.warn(`Failed to list MFA factors:`,o),{required:!1};let s=a?.totp?.filter(e=>e.status===`verified`);if(!s||s.length===0)return this.logger.info(`No verified MFA factors found`),{required:!1};let c=s[0];return this.logger.info(`MFA verification required`,{factorId:c.id,factorType:c.factor_type}),{required:!0,factorId:c.id,factorType:c.factor_type}}catch(e){return this.logger.error(`Error checking MFA requirement:`,e),{required:!1}}}async verifyMFA(e,t){let n=this.getClient();try{this.logger.info(`Verifying MFA code...`);let{data:r,error:i}=await n.auth.mfa.challenge({factorId:e});if(i||!r)throw new S(`Failed to create MFA challenge: ${i?.message||`Unknown error`}`,`MFA_VERIFICATION_FAILED`);let{data:a,error:o}=await n.auth.mfa.verify({factorId:e,challengeId:r.id,code:t});if(o)throw this.logger.error(`MFA verification failed:`,o),new S(`Invalid MFA code: ${o.message}`,`INVALID_MFA_CODE`);if(!a)throw new S(`No data returned from MFA verification`,`INVALID_RESPONSE`);let{data:{session:s},error:c}=await n.auth.refreshSession();if(c||!s)throw new S(`Failed to refresh session after MFA: ${c?.message||`No session returned`}`,`REFRESH_FAILED`);return this.logger.info(`Successfully verified MFA, session upgraded to AAL2`),s}catch(e){throw e instanceof S?e:new S(`MFA verification failed: ${e.message}`,`MFA_VERIFICATION_FAILED`)}}};const Le=c.join(process.env.HOME||process.env.USERPROFILE||`~`,`.taskmaster`,`context.json`);var Re=class e{static instance=null;logger=x(`ContextStore`);contextPath;constructor(e=Le){this.contextPath=e}static getInstance(t){return e.instance||=new e(t),e.instance}static resetInstance(){e.instance=null}getContext(){try{if(!s.existsSync(this.contextPath))return null;let e=JSON.parse(s.readFileSync(this.contextPath,`utf8`));return this.logger.debug(`Loaded context from disk`),e}catch(e){return this.logger.error(`Failed to read context:`,e),null}}saveContext(e){try{let t={...this.getContext()||{},...e,lastUpdated:new Date().toISOString()},n=c.dirname(this.contextPath);s.existsSync(n)||s.mkdirSync(n,{recursive:!0,mode:448});let r=`${this.contextPath}.tmp`;s.writeFileSync(r,JSON.stringify(t,null,2),{mode:384}),s.renameSync(r,this.contextPath),this.logger.debug(`Saved context to disk`)}catch(e){throw new S(`Failed to save context: ${e.message}`,`SAVE_FAILED`,e)}}updateUserContext(e){let t=this.getContext(),n={...t?.selectedContext||{},...e,updatedAt:new Date().toISOString()};this.saveContext({...t,selectedContext:n})}getUserContext(){return this.getContext()?.selectedContext||null}clearUserContext(){let e=this.getContext();if(e){let{selectedContext:t,...n}=e;this.saveContext(n)}}clearContext(){try{s.existsSync(this.contextPath)&&(s.unlinkSync(this.contextPath),this.logger.debug(`Cleared context from disk`))}catch(e){throw new S(`Failed to clear context: ${e.message}`,`CLEAR_FAILED`,e)}}hasContext(){return this.getContext()!==null}getContextPath(){return this.contextPath}},ze=`@hhsw2015/task-master-ai`,Be=`0.43.8`;const Ve=[`anthropic`,`openai`,`google`,`zai`,`zai-coding`,`perplexity`,`xai`,`groq`,`mistral`,`azure`,`openrouter`,`bedrock`,`ollama`],T={AZURE:`azure`,VERTEX:`vertex`,BEDROCK:`bedrock`,OPENROUTER:`openrouter`,OLLAMA:`ollama`,LMSTUDIO:`lmstudio`,OPENAI_COMPATIBLE:`openai-compatible`,CLAUDE_CODE:`claude-code`,MCP:`mcp`,GEMINI_CLI:`gemini-cli`,GROK_CLI:`grok-cli`,CODEX_CLI:`codex-cli`},He=Object.values(T),Ue=[...new Set([...Ve,...He])],We=`.taskmaster/tasks/tasks.json`,Ge=[`.taskmaster`,`.taskmaster/config.json`,We,`.taskmasterconfig`],Ke=`.git,.svn,.hg,.fossil,.github,.gitlab,.circleci,.travis.yml,.jenkins,.buildkite,.vscode,.idea,.project,.devcontainer,package-lock.json,yarn.lock,pnpm-lock.yaml,bun.lockb,bun.lock,deno.lock,deno.json,deno.jsonc,package.json,lerna.json,nx.json,turbo.json,rush.json,pnpm-workspace.yaml,Cargo.toml,Cargo.lock,go.mod,go.sum,go.work,pyproject.toml,setup.py,setup.cfg,poetry.lock,Pipfile,Pipfile.lock,uv.lock,Gemfile,Gemfile.lock,composer.json,composer.lock,build.gradle,build.gradle.kts,settings.gradle,settings.gradle.kts,pom.xml,build.sbt,project.clj,deps.edn,mix.exs,rebar.config,pubspec.yaml,Package.swift,CMakeLists.txt,Makefile,meson.build,BUILD.bazel,WORKSPACE,flake.nix,shell.nix,default.nix,Dockerfile,docker-compose.yml,docker-compose.yaml,Containerfile,kubernetes.yml,kubernetes.yaml,helm/Chart.yaml`.split(`,`),qe=[`tasks/tasks.json`,`tasks.json`,...Ke,`requirements.txt`];[...Ge,...qe];const Je=Be||`unknown`,Ye=[`pending`,`in-progress`,`done`,`deferred`,`cancelled`,`blocked`,`review`],Xe=[`done`,`completed`,`cancelled`];function Ze(e){return Xe.includes(e)}const Qe=[`text`,`json`,`compact`],$e={done:`✓`,completed:`✓`,"in-progress":`►`,blocked:`⭕`,pending:`○`,deferred:`⏸`,cancelled:`✗`,review:`👁`};function et(){return process.env.TM_BASE_DOMAIN||process.env.TM_PUBLIC_BASE_DOMAIN||`https://tryhamster.com`}function tt(){return{baseUrl:et(),configDir:c.join(p.homedir(),`.taskmaster`),configFile:c.join(p.homedir(),`.taskmaster`,`auth.json`)}}function nt(e){return{...tt(),...e}}new Proxy({},{get(e,t){return tt()[t]}});var rt=class{logger=x(`OAuthService`);contextStore;supabaseClient;configOverrides;authorizationUrl=null;keyPair=null;get baseUrl(){return nt(this.configOverrides).baseUrl}constructor(e,t,n={}){this.contextStore=e,this.supabaseClient=t,this.configOverrides=n}async authenticate(e={}){let{openBrowser:t,timeout:n=3e5,onAuthUrl:r,onWaitingForAuth:i,onSuccess:a,onError:o}=e;try{return await this.authenticateWithBackendPKCE({openBrowser:t,timeout:n,onAuthUrl:r,onWaitingForAuth:i,onSuccess:a})}catch(e){let t=e instanceof S?e:new S(`OAuth authentication failed: ${e.message}`,`OAUTH_FAILED`,e);throw o&&t.code!==`MFA_REQUIRED`&&o(t),t}}async authenticateWithBackendPKCE(e){let{openBrowser:t,timeout:n=3e5,onAuthUrl:r,onWaitingForAuth:i,onSuccess:a}=e;this.keyPair=Pe(),this.logger.debug(`Generated RSA keypair for E2E encryption`);let o=await this.startBackendFlow();if(!o.success||!o.flow_id)throw new S(o.message||`Failed to start authentication flow`,`START_FLOW_FAILED`);let{flow_id:s,verification_url:c,poll_interval:l=2}=o;if(this.authorizationUrl=c||null,r&&c&&r(c),t&&c)try{await t(c),this.logger.debug(`Browser opened successfully with URL:`,c)}catch(e){this.logger.warn(`Failed to open browser automatically:`,e)}i&&i();let u=await this.pollForCompletion(s,l*1e3,n);u.refreshToken||this.logger.warn(`No refresh token received from server - session refresh will not work`);let d={access_token:u.token,refresh_token:u.refreshToken??``,expires_in:u.expiresAt?Math.floor((new Date(u.expiresAt).getTime()-Date.now())/1e3):3600,token_type:`bearer`,user:{id:u.userId,email:u.email,app_metadata:{},user_metadata:{},aud:`authenticated`,created_at:``}};return await this.supabaseClient.setSession(d),this.contextStore.saveContext({userId:u.userId,email:u.email}),await this.checkAndThrowIfMFARequired(),a&&a(u),u}async startBackendFlow(){let e=`${this.baseUrl}/api/auth/cli/start`;if(!this.keyPair)throw new S(`Keypair not generated before starting flow`,`INTERNAL_ERROR`);try{let t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`,"User-Agent":`TaskMasterCLI/${this.getCliVersion()}`},body:JSON.stringify({name:`Task Master CLI`,version:this.getCliVersion(),device:p.hostname(),user:p.userInfo().username,platform:p.platform(),public_key:this.keyPair.publicKey})});if(!t.ok)throw new S((await t.json().catch(()=>({}))).message||`HTTP ${t.status}`,`START_FLOW_FAILED`);return await t.json()}catch(e){throw e instanceof S?e:(this.logger.warn(`Failed to reach backend for PKCE flow:`,e),new S(`Unable to reach authentication server`,`BACKEND_UNREACHABLE`,e))}}async pollForCompletion(e,t,n){let r=`${this.baseUrl}/api/auth/cli/status?flow_id=${e}`,i=Date.now();if(!this.keyPair)throw new S(`Keypair not available for decryption`,`INTERNAL_ERROR`);for(;Date.now()-i<n;){try{let e=await fetch(r,{method:`GET`,headers:{"User-Agent":`TaskMasterCLI/${this.getCliVersion()}`}});if(!e.ok){let t=await e.json().catch(()=>({}));throw e.status===404?new S(`Authentication flow expired or not found`,`FLOW_NOT_FOUND`):new S(t.message||`HTTP ${e.status}`,`POLL_FAILED`)}let t=await e.json();if(!t.success)throw new S(t.message||`Failed to check status`,`POLL_FAILED`);switch(t.status){case`complete`:{if(!t.encrypted_tokens)throw new S(`Server returned no encrypted tokens`,`MISSING_TOKENS`);let e=Fe(t.encrypted_tokens,this.keyPair.privateKey);return this.logger.debug(`Successfully decrypted authentication tokens`),{token:e.access_token,refreshToken:e.refresh_token,userId:e.user_id,email:e.email,expiresAt:e.expires_in?new Date(Date.now()+e.expires_in*1e3).toISOString():void 0,tokenType:`standard`,savedAt:new Date().toISOString()}}case`failed`:throw new S(t.error_description||t.error||`Authentication failed`,`OAUTH_FAILED`);case`expired`:throw new S(`Authentication flow expired`,`AUTH_TIMEOUT`);case`pending`:case`authenticating`:this.logger.debug(`Flow status: ${t.status}, continuing to poll`);break;default:this.logger.warn(`Unknown flow status: ${t.status}`)}}catch(e){if(e instanceof S)throw e;this.logger.debug(`Poll request failed, will retry:`,e)}await new Promise(e=>setTimeout(e,t))}throw new S(`Authentication timeout`,`AUTH_TIMEOUT`)}getCliVersion(){return Je}getAuthorizationUrl(){return this.authorizationUrl}async checkAndThrowIfMFARequired(){let e=await this.supabaseClient.checkMFARequired();if(e.required)throw!e.factorId||!e.factorType?(this.logger.error(`MFA required but factor information is incomplete`,{mfaCheck:e}),new S(`MFA is required but the server returned incomplete factor configuration. Please contact support or try re-enrolling MFA.`,`MFA_REQUIRED_INCOMPLETE`)):(this.logger.info(`MFA verification required after OAuth login`,{factorId:e.factorId,factorType:e.factorType}),new S(`MFA verification required. Please provide your authentication code.`,`MFA_REQUIRED`,void 0,{factorId:e.factorId,factorType:e.factorType}))}},it=class{logger=x(`OrganizationService`);constructor(e){this.supabaseClient=e}async getOrganizations(){try{let{data:e,error:t}=await this.supabaseClient.from(`user_accounts`).select(`
|
|
3
3
|
id,
|
|
4
4
|
name,
|
|
5
5
|
slug
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,i as t,l as n,n as r,t as i}from"./ai-services-unified-
|
|
1
|
+
import{a as e,i as t,l as n,n as r,t as i}from"./ai-services-unified-D0SWrwB5.js";import{$ as a,A as o,At as s,B as c,Bt as l,C as u,Ct as d,D as f,Dn as p,En as m,Jt as h,Kt as g,L as _,Lt as v,Mt as y,O as b,On as x,Ot as S,R as C,Rt as w,S as T,Tn as E,Tt as D,X as O,Xt as k,Y as A,Yt as j,Z as M,Zt as N,_ as P,_n as ee,a as te,an as ne,bt as re,cn as ie,ct as ae,dn as F,dt as oe,en as se,et as ce,f as le,fn as ue,ft as de,g as fe,gn as pe,gt as me,h as he,hn as ge,ht as _e,i as ve,it as ye,j as be,jn as xe,kn as Se,kt as Ce,ln as I,lt as we,mn as Te,mt as Ee,n as De,nn as Oe,o as ke,on as Ae,p as je,pn as Me,pt as Ne,q as Pe,rt as Fe,sn as Ie,tt as Le,un as Re,ut as ze,v as Be,vn as Ve,vt as L,w as He,wt as Ue,xn as R,yn as We,yt as z}from"./config-manager-Dn_JApjY.js";import Ge,{resolve as Ke}from"node:path";import B from"chalk";import*as qe from"fs";import V from"fs";import H from"path";import Je from"os";import Ye from"node:fs/promises";import Xe from"node:fs";import Ze from"node:os";import{z as U}from"zod";import{spawn as Qe}from"child_process";import{fileURLToPath as $e}from"url";import{FastMCP as et}from"fastmcp";import{smoothStream as tt}from"ai";import W from"boxen";import nt from"readline";import{Command as G}from"commander";import rt from"figlet";import it from"gradient-string";import at from"terminal-link";import{marked as ot}from"marked";import{markedTerminal as st}from"marked-terminal";import ct from"turndown";import K from"cli-table3";import q from"inquirer";import J from"ora";import lt from"open";import ut,{Separator as dt}from"@inquirer/search";import ft from"process";import pt from"https";import mt from"cli-progress";import ht from"http";import gt from"fuse.js";import _t from"ajv";import vt from"ajv-formats";import yt from"gpt-tokens";import{LRUCache as bt}from"lru-cache";import"@streamparser/json";function xt(e,t,n){return(n?.color?B[n.color]:B.cyan)(at(e,t,{fallback:(e,t)=>`${e} (${t})`}))}function St(e,t){return xt(e,e,t)}const Ct=it([`#00b4d8`,`#0077b6`,`#03045e`]);function wt(){return process.env.TM_HIDE_BANNER===`true`}function Tt(){return process.stdout.columns||80}function Et(e={}){if(wt())return;let{version:t}=e;try{let e=rt.textSync(`Task Master`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(Ct(e))}catch{console.log(Ct(`=== Task Master ===`))}let n=xt(`x.com/eyaltoledano`,`https://x.com/eyaltoledano`),r=B.dim(`by `)+B.cyan(n),i=t?t.replace(/^v/,``):``,a=`https://github.com/eyaltoledano/claude-task-master/releases/tag/task-master-ai%40${i}`,o=t?xt(`v${i}`,a,{color:`gray`}):``;if(o){let e=i.length+1,t=Tt(),n=Math.max(2,t-22-e-2);console.log(r+` `.repeat(n)+o)}else console.log(r);let s=xt(`tryhamster.com`,`https://tryhamster.com`);console.log(B.dim(`Taskmaster for teams: `)+B.magenta(s)),console.log(``)}function Dt(){if(wt())return;try{let e=rt.textSync(`Task Master`,{font:`Standard`,horizontalLayout:`default`,verticalLayout:`default`});console.log(Ct(e))}catch{console.log(Ct(`=== Task Master ===`))}let e=xt(`x.com/eyaltoledano`,`https://x.com/eyaltoledano`);console.log(B.dim(`by `)+B.cyan(e));let t=xt(`tryhamster.com`,`https://tryhamster.com`);console.log(B.dim(`Taskmaster for teams: `)+B.magenta(t)),console.log(``)}function Ot(e){let{header:t,body:n,callToAction:r,footer:i,level:a=`warn`}=e,o=a===`info`?B.blue.bold:B.yellow.bold,s=a===`info`?`blue`:`yellow`,c=[o(t),...n.map(e=>B.white(e))];return r&&r.label&&r.action&&c.push(B.cyan(r.label)+`
|
|
2
2
|
`+B.blue.underline(r.action)),i&&c.push(B.gray(i)),W(c.join(`
|
|
3
3
|
|
|
4
4
|
`),{padding:1,borderColor:s,borderStyle:`round`,margin:{top:1,bottom:1}})}function kt(e,t=30,n){if(!n){let n=Math.round(e/100*t),r=t-n;return B.green(`█`).repeat(n)+B.gray(`░`).repeat(r)}let r=``,i=0;if(n.done&&n.done>0){let e=Math.round(n.done/100*t);e>0&&(r+=B.green(`█`).repeat(e),i+=e)}if(n.cancelled&&i<t){let e=Math.round(n.cancelled/100*t),a=Math.min(e,t-i);a>0&&(r+=B.gray(`█`).repeat(a),i+=a)}if(n.deferred&&i<t){let e=Math.round(n.deferred/100*t),a=Math.min(e,t-i);a>0&&(r+=B.gray(`█`).repeat(a),i+=a)}if(n[`in-progress`]&&i<t){let e=Math.round(n[`in-progress`]/100*t),a=Math.min(e,t-i);a>0&&(r+=B.blue(`█`).repeat(a),i+=a)}if(n.review&&i<t){let e=Math.round(n.review/100*t),a=Math.min(e,t-i);a>0&&(r+=B.magenta(`░`).repeat(a),i+=a)}if(n.pending&&i<t){let e=Math.round(n.pending/100*t),a=Math.min(e,t-i);a>0&&(r+=B.yellow(`░`).repeat(a),i+=a)}if(n.blocked&&i<t){let e=Math.round(n.blocked/100*t),a=Math.min(e,t-i);a>0&&(r+=B.red(`░`).repeat(a),i+=a)}return i<t&&(r+=B.yellow(`░`).repeat(t-i)),r}function At(e){let t={total:e.length,done:0,inProgress:0,pending:0,blocked:0,deferred:0,cancelled:0,review:0,completionPercentage:0,completedCount:0};return e.forEach(e=>{switch(e.status){case`done`:t.done++;break;case`in-progress`:t.inProgress++;break;case`pending`:t.pending++;break;case`blocked`:t.blocked++;break;case`deferred`:t.deferred++;break;case`cancelled`:t.cancelled++;break;case`review`:t.review=(t.review||0)+1;break}}),t.completedCount=e.filter(e=>We(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function jt(e){let t={total:0,done:0,inProgress:0,pending:0,blocked:0,deferred:0,cancelled:0,review:0,completionPercentage:0,completedCount:0},n=[];return e.forEach(e=>{e.subtasks&&e.subtasks.length>0&&e.subtasks.forEach(e=>{switch(t.total++,n.push(e),e.status){case`done`:t.done++;break;case`in-progress`:t.inProgress++;break;case`pending`:t.pending++;break;case`blocked`:t.blocked++;break;case`deferred`:t.deferred++;break;case`cancelled`:t.cancelled++;break;case`review`:t.review=(t.review||0)+1;break}})}),t.completedCount=n.filter(e=>We(e.status)).length,t.completionPercentage=t.total>0?Math.round(t.completedCount/t.total*100):0,t}function Mt(e){let t=new Set(e.filter(e=>We(e.status)).map(e=>e.id)),n=e.filter(e=>!We(e.status)&&(!e.dependencies||e.dependencies.length===0)).length,r=e.filter(e=>!We(e.status)&&e.dependencies&&e.dependencies.length>0&&e.dependencies.every(e=>t.has(e))).length,i=e.filter(e=>!We(e.status)&&e.dependencies&&e.dependencies.length>0&&!e.dependencies.every(e=>t.has(e))).length,a={};e.forEach(e=>{e.dependencies&&e.dependencies.length>0&&e.dependencies.forEach(e=>{let t=String(e);a[t]=(a[t]||0)+1})});let o,s=0;for(let[e,t]of Object.entries(a))t>s&&(s=t,o=parseInt(e));let c=e.reduce((e,t)=>e+(t.dependencies?t.dependencies.length:0),0),l=e.length>0?c/e.length:0;return{tasksWithNoDeps:n,tasksReadyToWork:n+r,tasksBlockedByDeps:i,mostDependedOnTaskId:o,mostDependedOnCount:s,avgDependenciesPerTask:l}}function Nt(e){let t={critical:0,high:0,medium:0,low:0};return e.forEach(e=>{let n=e.priority||`medium`;t[n]++}),t}function Pt(e){return e.total===0?{}:{done:e.done/e.total*100,"in-progress":e.inProgress/e.total*100,pending:e.pending/e.total*100,blocked:e.blocked/e.total*100,deferred:e.deferred/e.total*100,cancelled:e.cancelled/e.total*100,review:(e.review||0)/e.total*100}}function Ft(e,t=!1){let n=[];t?n.push(`Completed: ${B.green(`${e.completedCount}/${e.total}`)}`):n.push(`Done: ${B.green(e.done)}`),n.push(`Cancelled: ${B.gray(e.cancelled)}`),n.push(`Deferred: ${B.gray(e.deferred)}`);let r=n.join(` `);n.length=0,n.push(`In Progress: ${B.blue(e.inProgress)}`),n.push(`Review: ${B.magenta(e.review||0)}`),n.push(`Pending: ${B.yellow(e.pending)}`),n.push(`Blocked: ${B.red(e.blocked)}`);let i=n.join(` `);return r+`
|
|
@@ -867,7 +867,7 @@ ${B.cyan(`1.`)} Run ${B.yellow(`task-master next`)} to see what to work on next\
|
|
|
867
867
|
${B.cyan(`1.`)} Run ${B.yellow(`task-master list`)} to view all tasks\n${B.cyan(`2.`)} Run ${B.yellow(`task-master expand --id=<id>`)} to break down a task into subtasks\n${B.cyan(`3.`)} Run ${B.yellow(`task-master analyze-complexity`)} to analyze task complexity`;console.log(W(e,Yo.nextSteps))}function cs(e){return Math.ceil(e.length/4)}function ls(e){let t=V.readFileSync(e,`utf8`);if(!t)throw Error(`Input file ${e} is empty or could not be read.`);return t}function us(e,t){let n=[],r=1;if(!V.existsSync(e))return{existingTasks:n,nextId:r};try{let i=V.readFileSync(e,`utf8`),a=JSON.parse(i);a[t]?.tasks&&Array.isArray(a[t].tasks)&&(n=a[t].tasks,n.length>0&&(r=Math.max(...n.map(e=>e.id||0))+1))}catch{return{existingTasks:[],nextId:1}}return{existingTasks:n,nextId:r}}function ds({existingTasks:e,targetTag:t,append:n,force:r,isMCP:i,logger:a}){if(!(e.length>0)){a.report(`Tag '${t}' is empty or doesn't exist. Creating/updating tag with new tasks.`,`info`);return}if(n){a.report(`Append mode enabled. Found ${e.length} existing tasks in tag '${t}'.`,`info`);return}if(!r){let n=`Tag '${t}' already contains ${e.length} tasks. Use --force to overwrite or --append to add to existing tasks.`;if(a.report(n,`error`),i)throw Error(n);console.error(B.red(n)),process.exit(1)}a.report(`Force flag enabled. Overwriting existing tasks in tag '${t}'.`,`debug`)}function fs(e,t,n,r){ps(e,t);let i=t,a=new Map,o=e.map(e=>{let t=i++;return a.set(e.id,t),{...e,id:t,status:e.status||`pending`,priority:e.priority||r,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],subtasks:e.subtasks||[],title:e.title||``,description:e.description||``,details:e.details||``,testStrategy:e.testStrategy||``}});return o.forEach(e=>{e.dependencies=e.dependencies.map(e=>a.get(e)).filter(t=>t!=null&&t<e.id&&(oe(n,t)||o.some(e=>e.id===t)))}),o}function ps(e,t=1){if(!Array.isArray(e)||e.length===0)return;let n=e.map(e=>e.id);if(n.some(e=>!Number.isInteger(e)||e<1))throw Error(`PRD tasks must use sequential positive integer IDs starting at 1.`);let r=new Set(n);if(r.size!==n.length)throw Error(`PRD task IDs must be unique and sequential starting at 1.`);let i=[...r].sort((e,t)=>e-t),a=i[0];if(a!==1&&a!==t)throw Error(`PRD task IDs must start at 1 or ${t} and be sequential.`);for(let e=0;e<i.length;e+=1)if(i[e]!==a+e)throw Error(`PRD task IDs must be a contiguous sequence starting at ${a}.`)}function ms(e,t,n,r){let i=H.dirname(e);V.existsSync(i)||V.mkdirSync(i,{recursive:!0});let a={};if(V.existsSync(e))try{let t=V.readFileSync(e,`utf8`);a=JSON.parse(t)}catch{a={}}a[n]={tasks:t,metadata:{created:a[n]?.metadata?.created||new Date().toISOString(),updated:new Date().toISOString(),description:`Tasks for ${n} context`}},ae(a[n],{description:`Tasks for ${n} context`}),V.writeFileSync(e,JSON.stringify(a,null,2)),r.report(`Successfully saved ${t.length} tasks to ${e}`,`debug`)}async function hs(e,t,n){let r=Da(),i=he(e.projectRoot)||`medium`;return r.loadPrompt(`parse-prd`,{research:e.research,numTasks:e.numTasks,nextId:n,prdContent:t,prdPath:e.prdPath,defaultTaskPriority:i,hasCodebaseAnalysis:e.hasCodebaseAnalysis(),projectRoot:e.projectRoot||``})}async function gs({task:e,currentCount:t,totalTasks:n,estimatedTokens:r,progressTracker:i,reportProgress:a,priorityMap:o,defaultPriority:s,estimatedInputTokens:c}){let l=e.priority||s,u=o[l]||o.medium;if(i&&(i.addTaskLine(t,e.title,l),r&&i.updateTokens(c,r)),a)try{let i=r?Math.floor(r/n):0;await a({progress:t,total:n,message:`${u} Task ${t}/${n} - ${e.title} | ~Output: ${i} tokens`})}catch{}}async function _s({processedTasks:e,nextId:t,summary:n,prdPath:r,tasksPath:i,usedFallback:a,aiServiceResponse:o}){let s=(()=>{if(!Array.isArray(e)||e.length===0)return`task_${String(t).padStart(3,`0`)}.txt`;let n=e[0].id,r=e[e.length-1].id;return e.length===1?`task_${String(n).padStart(3,`0`)}.txt`:`task_${String(n).padStart(3,`0`)}.txt -> task_${String(r).padStart(3,`0`)}.txt`})();as({totalTasks:e.length,taskPriorities:n.taskPriorities,prdFilePath:r,outputPath:i,elapsedTime:n.elapsedTime,usedFallback:a,taskFilesGenerated:s,actionVerb:n.actionVerb}),o?.telemetryData&&(o.mainResult?.usage&&await Bo.withSoftTimeout(o.mainResult.usage,1e3,void 0),Sl(o.telemetryData,`cli`))}function vs({processedTasks:e,research:t,finalTasks:n,tasksPath:r,aiServiceResponse:i}){console.log(W(B.green(`Successfully generated ${e.length} new tasks${t?` with research-backed analysis`:``}. Total tasks in ${r}: ${n.length}`),{padding:1,borderColor:`green`,borderStyle:`round`})),console.log(W(B.white.bold(`Next Steps:`)+`
|
|
868
868
|
|
|
869
869
|
${B.cyan(`1.`)} Run ${B.yellow(`task-master list`)} to view all tasks\n${B.cyan(`2.`)} Run ${B.yellow(`task-master expand --id=<id>`)} to break down a task into subtasks`,{padding:1,borderColor:`cyan`,borderStyle:`round`,margin:{top:1}})),i?.telemetryData&&Sl(i.telemetryData,`cli`)}async function ys(e,t){let n=new Go(e.mcpLog,e.reportProgress),{systemPrompt:r,userPrompt:a}=t,o=cs(r+a),s=null;e.outputFormat===`text`&&!e.isMCP&&(s=J(`Parsing PRD and generating tasks...
|
|
870
|
-
`).start());try{n.report(`Calling AI service to generate tasks from PRD${e.research?` with research-backed analysis`:``}...`,`info`);let t=await i({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:Uo,objectName:`tasks_data`,systemPrompt:r,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),c=null;if(t?.mainResult&&(typeof t.mainResult==`object`&&t.mainResult!==null&&`tasks`in t.mainResult?c=t.mainResult:typeof t.mainResult.object==`object`&&t.mainResult.object!==null&&`tasks`in t.mainResult.object&&(c=t.mainResult.object)),!c||!Array.isArray(c.tasks))throw Error(`AI service returned unexpected data structure after validation.`);return s&&s.succeed(`Tasks generated successfully!`),{parsedTasks:c.tasks,aiServiceResponse:t,estimatedInputTokens:o}}catch(e){throw s&&s.fail(`Error parsing PRD: ${e.message}`),e}}const[bs,xs,Ss]=Qi,Cs=new Map;var ws=class{constructor(e,t,n,r=null){this.name=e,this.levels=t,this.colors=n,this.thresholds=r}getColor(e){return this.colors[e]||B.gray}getLevelFromScore(e){if(!this.thresholds)throw Error(`${this.name} does not support score-based levels`);return e>=7?this.levels[0]:e<=3?this.levels[2]:this.levels[1]}};const Ts={cli:{filled:`●`,empty:`○`},statusBar:{high:`⋮`,medium:`:`,low:`.`},mcp:{high:`🔴`,medium:`🟠`,low:`🟢`}},Es=new ws(`priority`,[bs,xs,Ss],{[bs]:B.hex(`#CC0000`),[xs]:B.hex(`#FF8800`),[Ss]:B.yellow});function Ds(e,t){let n=Ts.cli.filled,r=Ts.cli.empty,i=``;for(let a=0;a<3;a++)a<e?i+=t(n):i+=B.white(r);return i}function Os(e,t){return 3-t.indexOf(e)}function ks(e,t){if(Cs.has(e))return Cs.get(e);let n=t();return Cs.set(e,n),n}function As(){return ks(`mcp-priority-all`,()=>({[bs]:Ts.mcp.high,[xs]:Ts.mcp.medium,[Ss]:Ts.mcp.low}))}function js(){return ks(`cli-priority-all`,()=>{let e={};return Es.levels.forEach(t=>{e[t]=Ds(Os(t,Es.levels),Es.getColor(t))}),e})}function Ms(){return ks(`statusbar-priority-all`,()=>{let e={};return Es.levels.forEach((t,n)=>{let r=n===0?Ts.statusBar.high:n===1?Ts.statusBar.medium:Ts.statusBar.low;e[t]=Es.getColor(t)(r)}),e})}function Ns(){return{[bs]:Es.colors[bs],[xs]:Es.colors[xs],[Ss]:Es.colors[Ss]}}function Ps(e=!1){return e?As():js()}function Fs(e,t=!1){let n=Ps(t);return n[e]||n[xs]}new ws(`complexity`,[`high`,`medium`,`low`],{high:B.hex(`#CC0000`),medium:B.hex(`#FF8800`),low:B.green},{high:e=>e>=7,medium:e=>e>=4&&e<=6,low:e=>e<=3});const Is={clearOnComplete:!1,stopOnComplete:!0,hideCursor:!0,barsize:40},Ls={shades_classic:mt.Presets.shades_classic,shades_grey:mt.Presets.shades_grey,rect:mt.Presets.rect,legacy:mt.Presets.legacy},Rs=new class{constructor(e={},t=Ls.shades_classic){this.defaultOptions={...Is,...e},this.defaultPreset=t}createSingleBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new mt.SingleBar(n,r)}createMultiBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new mt.MultiBar(n,r)}_mergeConfig(e){return{...this.defaultOptions,...e}}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}setDefaultPreset(e){this.defaultPreset=e}};function zs(e={}){return Rs.createMultiBar(e)}var Bs=class{constructor(e={}){this.numUnits=e.numUnits||1,this.unitName=e.unitName||`unit`,this.startTime=null,this.completedUnits=0,this.tokensIn=0,this.tokensOut=0,this.isEstimate=!0,this.bestAvgTimePerUnit=null,this.lastEstimateTime=null,this.lastEstimateSeconds=0,this.multibar=null,this.timeTokensBar=null,this.progressBar=null,this._timerInterval=null,this.isStarted=!1,this.isFinished=!1,this._initializeCustomProperties(e)}_initializeCustomProperties(e){}get unitNamePlural(){return`${this.unitName}s`}start(){this.isStarted||this.isFinished||(this.isStarted=!0,this.startTime=Date.now(),this.multibar=zs(),this.timeTokensBar=this.multibar.create(1,0,{},{format:this._getTimeTokensBarFormat(),barsize:1,hideCursor:!0,clearOnComplete:!1}),this.progressBar=this.multibar.create(this.numUnits,0,{},{format:this._getProgressBarFormat(),barCompleteChar:`█`,barIncompleteChar:`░`}),this._updateTimeTokensBar(),this.progressBar.update(0,{[this.unitNamePlural]:`0/${this.numUnits}`}),this._timerInterval=setInterval(()=>this._updateTimeTokensBar(),1e3),this._setupCustomUI())}_setupCustomUI(){}_getTimeTokensBarFormat(){return`{clock} {elapsed} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`${this.unitName.charAt(0).toUpperCase()+this.unitName.slice(1)}s {${this.unitNamePlural}} |{bar}| {percentage}%`}updateTokens(e,t,n=!1){this.tokensIn=e||0,this.tokensOut=t||0,this.isEstimate=n,this._updateTimeTokensBar()}_updateTimeTokensBar(){if(!this.timeTokensBar||this.isFinished)return;let e=this._formatElapsedTime(),t=this._estimateRemainingTime(),n=this.isEstimate?`~ Tokens (I/O)`:`Tokens (I/O)`;this.timeTokensBar.update(1,{clock:`⏱️`,elapsed:e,in:this.tokensIn,out:this.tokensOut,remaining:t,tokensLabel:n,...this._getCustomTimeTokensPayload()})}_getCustomTimeTokensPayload(){return{}}_formatElapsedTime(){if(!this.startTime)return`0m 00s`;let e=Math.floor((Date.now()-this.startTime)/1e3);return`${Math.floor(e/60)}m ${(e%60).toString().padStart(2,`0`)}s`}_estimateRemainingTime(){let e=this._getProgressFraction();if(e>=1)return`~0s`;let t=Date.now(),n=(t-this.startTime)/1e3;if(e===0)return`~calculating...`;let r=n/e;(this.bestAvgTimePerUnit===null||r<this.bestAvgTimePerUnit)&&(this.bestAvgTimePerUnit=r);let i=this.numUnits*(1-e),a=Math.ceil(i*this.bestAvgTimePerUnit);if(this.lastEstimateTime){let e=Math.floor((t-this.lastEstimateTime)/1e3),n=Math.max(0,this.lastEstimateSeconds-e);if(n===0)return`~0s`;a=Math.min(a,n)}return this.lastEstimateTime=t,this.lastEstimateSeconds=a,`~${this._formatDuration(a)}`}_getProgressFraction(){return this.completedUnits/this.numUnits}_formatDuration(e){if(e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;return t<60?n>0?`${t}m ${n}s`:`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}getElapsedTime(){return this.startTime?Date.now()-this.startTime:0}stop(){this.isFinished||(this.isFinished=!0,this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar&&(this._updateTimeTokensBar(),this.multibar.stop()),this.cleanup())}getSummary(){return{completedUnits:this.completedUnits,elapsedTime:this.getElapsedTime()}}cleanup(){if(this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar){try{this.multibar.stop()}catch{}this.multibar=null}this.timeTokensBar=null,this.progressBar=null,this.isStarted=!1,this.isFinished=!0,this._performCustomCleanup()}_performCustomCleanup(){}},Vs=class{constructor(e){if(!e)throw Error(`Multibar instance is required`);this.multibar=e}createBar(e,t={}){if(typeof e!=`string`)throw Error(`Format must be a string`);let n=this.multibar.create(1,1,{},{format:e,barsize:1,hideCursor:!0,clearOnComplete:!1});return n.update(1,t),n}createHeader(e,t){this.createBar(t),this.createBar(e),this.createBar(t)}createRow(e,t){if(!t||typeof t!=`object`)throw Error(`Payload must be an object`);return this.createBar(e,t)}createBorder(e){return this.createBar(e)}};function Hs(e,t,n){new Vs(e).createHeader(t,n)}function Us(e,t,n){new Vs(e).createRow(t,n)}function Ws(e,t){new Vs(e).createBorder(t)}js();const Gs=Ms();Ns();const Ks={DEBOUNCE_DELAY:100,MAX_TITLE_LENGTH:57,TRUNCATED_LENGTH:54,TASK_ID_PAD_START:3,TASK_ID_PAD_END:4,PRIORITY_PAD_END:3,VALID_PRIORITIES:[`high`,`medium`,`low`],DEFAULT_PRIORITY:`medium`};var qs=class{constructor(e=Ks.DEBOUNCE_DELAY){this.delay=e,this.pendingTimeout=null}debounce(e){this.clear(),this.pendingTimeout=setTimeout(()=>{e(),this.pendingTimeout=null},this.delay)}clear(){this.pendingTimeout&&=(clearTimeout(this.pendingTimeout),null)}hasPending(){return this.pendingTimeout!==null}},Js=class{constructor(){this.priorities={high:0,medium:0,low:0}}increment(e){let t=this.normalize(e);return this.priorities[t]++,t}normalize(e){let t=e?e.toLowerCase():Ks.DEFAULT_PRIORITY;return Ks.VALID_PRIORITIES.includes(t)?t:Ks.DEFAULT_PRIORITY}getCounts(){return{...this.priorities}}},Ys=class{static formatTitle(e,t){return e?e.length>Ks.MAX_TITLE_LENGTH?e.substring(0,Ks.TRUNCATED_LENGTH)+`...`:e:`Task ${t}`}static formatPriority(e){return Fs(e,!1).padEnd(Ks.PRIORITY_PAD_END,` `)}static formatTaskId(e){return e.toString().padStart(Ks.TASK_ID_PAD_START,` `).padEnd(Ks.TASK_ID_PAD_END,` `)}},Xs=class extends Bs{_initializeCustomProperties(e){this.append=e.append,this.priorityManager=new Js,this.debouncer=new qs,this.headerShown=!1}_getTimeTokensBarFormat(){return`{clock} {elapsed} | ${Gs.high} {high} ${Gs.medium} {medium} ${Gs.low} {low} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`Tasks {tasks} |{bar}| {percentage}%`}_getCustomTimeTokensPayload(){return this.priorityManager.getCounts()}addTaskLine(e,t,n=`medium`){if(!this.multibar||this.isFinished)return;this._ensureHeaderShown();let r=this._updateTaskCounters(e,n);this._updateTimeTokensBar(),this.debouncer.debounce(()=>{this._updateProgressDisplay(e,t,r)})}_ensureHeaderShown(){this.headerShown||(this.headerShown=!0,Hs(this.multibar,` TASK | PRI | TITLE`,`------+-----+----------------------------------------------------------------`))}_updateTaskCounters(e,t){let n=this.priorityManager.increment(t);return this.completedUnits=e,n}_updateProgressDisplay(e,t,n){this.progressBar.update(this.completedUnits,{tasks:`${this.completedUnits}/${this.numUnits}`});let r=Ys.formatTitle(t,e),i=Ys.formatPriority(n),a=Ys.formatTaskId(e);Us(this.multibar,` ${a} | ${i} | {title}`,{title:r}),Ws(this.multibar,`------+-----+----------------------------------------------------------------`),this._updateTimeTokensBar()}finish(){this.debouncer.hasPending()&&(this.debouncer.clear(),this._updateTimeTokensBar()),this.cleanup(),super.finish()}_performCustomCleanup(){this.debouncer.clear()}getSummary(){return{...super.getSummary(),taskPriorities:this.priorityManager.getCounts(),actionVerb:this.append?`appended`:`generated`}}};function Zs(e={}){return new Xs(e)}async function Qs(e,t,n){let r=$s(e,t,n);await tc(e,n,r.estimatedInputTokens);let i=await nc(e,t,e.streamingTimeout),{progressTracker:a,priorityMap:o}=await rc(e,n),s=await ic(i.mainResult,e,t,n,a,o,r.defaultPriority,r.estimatedInputTokens,r.logger);if(ec(s),s.usage&&e.projectRoot){let{logAiUsage:t}=await import(`./ai-services-unified-BxDYeox6.js`),{getUserId:n}=await import(`./config-manager-Bqyvl0WP.js`),a=n(e.projectRoot);if(a&&i.providerName&&i.modelId)try{let n=await t({userId:a,commandName:`parse-prd`,providerName:i.providerName,modelId:i.modelId,inputTokens:s.usage.promptTokens||0,outputTokens:s.usage.completionTokens||0,outputType:e.isMCP?`mcp`:`cli`});n&&(i.telemetryData=n)}catch(e){r.logger.report(`Failed to log telemetry: ${e.message}`,`debug`)}}return mc(s,i,r.estimatedInputTokens,a)}function $s(e,t,n){let{systemPrompt:r,userPrompt:i}=t;return{logger:new Go(e.mcpLog,e.reportProgress),estimatedInputTokens:cs(r+i),defaultPriority:he(e.projectRoot)||`medium`}}function ec(e){if(e.parsedTasks.length===0)throw Error(`No tasks were generated from the PRD`)}async function tc(e,t,n){e.reportProgress&&await e.reportProgress({progress:0,total:t,message:`Starting PRD analysis (Input: ${n} tokens)${e.research?` with research`:``}...`})}async function nc(e,n,r){let{systemPrompt:i,userPrompt:a}=n;return await Bo.withTimeout(t({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:Uo,systemPrompt:i,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),r,`Streaming operation`)}async function rc(e,t){let n=Ps(e.isMCP),r=null;if(e.outputFormat===`text`&&!e.isMCP){r=Zs({numUnits:t,unitName:`task`,append:e.append});let n=e.research?o():T(),i=f(e.research?`research`:`main`);es({prdFilePath:e.prdPath,outputPath:e.tasksPath,numTasks:t,append:e.append,research:e.research,force:e.force,existingTasks:[],nextId:1,model:n||`Default`,temperature:i?.temperature||.7}),r.start()}return{progressTracker:r,priorityMap:n}}async function ic(e,t,n,r,i,a,o,s,c){let{systemPrompt:l,userPrompt:u}=n,d={config:{...t,schema:Uo},numTasks:r,progressTracker:i,priorityMap:a,defaultPriority:o,estimatedInputTokens:s,prompt:u,systemPrompt:l};try{let t={lastPartialObject:null,taskCount:0,estimatedOutputTokens:0,usage:null};if(await ac(e.partialObjectStream,t,d),e.usage)try{t.usage=await e.usage}catch(e){c.report(`Failed to get usage data: ${e.message}`,`debug`)}return lc(t,d)}catch(e){return c.report(`StreamObject processing failed: ${e.message}. Falling back to generateObject.`,`debug`),await pc(d,c)}}async function ac(e,t,n){for await(let r of e)t.lastPartialObject=r,r&&(t.estimatedOutputTokens=cs(JSON.stringify(r))),await oc(r,t,n)}async function oc(e,t,n){if(!e?.tasks||!Array.isArray(e.tasks))return;let r=e.tasks.length;r>t.taskCount?(await sc(e.tasks,t.taskCount,r,t.estimatedOutputTokens,n),t.taskCount=r):n.progressTracker&&t.estimatedOutputTokens>0&&n.progressTracker.updateTokens(n.estimatedInputTokens,t.estimatedOutputTokens,!0)}async function sc(e,t,n,r,i){for(let a=t;a<n;a++){let t=e[a]||{};t.title?await gs({task:t,currentCount:a+1,totalTasks:i.numTasks,estimatedTokens:r,progressTracker:i.progressTracker,reportProgress:i.config.reportProgress,priorityMap:i.priorityMap,defaultPriority:i.defaultPriority,estimatedInputTokens:i.estimatedInputTokens}):await cc(a+1,r,i)}}async function cc(e,t,n){let{progressTracker:r,config:i,numTasks:a,defaultPriority:o,estimatedInputTokens:s}=n;r&&(r.addTaskLine(e,`Generating task ${e}...`,o),r.updateTokens(s,t,!0)),i.reportProgress&&!r&&await i.reportProgress({progress:e,total:a,message:`Generating task ${e}/${a}...`})}async function lc(e,t){let{lastPartialObject:n,estimatedOutputTokens:r,taskCount:i,usage:a}=e;if(!n?.tasks||!Array.isArray(n.tasks))throw Error(`No tasks generated from streamObject`);let o=a?.completionTokens||r,s=a?.promptTokens||t.estimatedInputTokens;return t.progressTracker&&await uc(n.tasks,i,a?o:r,t,a?s:null),{parsedTasks:n.tasks,estimatedOutputTokens:o,actualInputTokens:s,usage:a,usedFallback:!1}}async function uc(e,t,n,r,i=null){let{progressTracker:a,defaultPriority:o,estimatedInputTokens:s}=r;t>0?dc(e,a,o):await fc(e,n,r),a.updateTokens(i||s,n,!1),a.stop()}function dc(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&t.addTaskLine(r+1,i.title,i.priority||n)}}async function fc(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&await gs({task:i,currentCount:r+1,totalTasks:n.numTasks,estimatedTokens:t,progressTracker:n.progressTracker,reportProgress:n.config.reportProgress,priorityMap:n.priorityMap,defaultPriority:n.defaultPriority,estimatedInputTokens:n.estimatedInputTokens})}}async function pc(e,t){if(t.report(`Using generateObject fallback for PRD parsing`,`info`),e.progressTracker)for(let t=0;t<e.numTasks;t++)e.progressTracker.addTaskLine(t+1,`Generating task ${t+1}...`,e.defaultPriority),e.progressTracker.updateTokens(e.estimatedInputTokens,0,!0);let n=await i({role:e.config.research?`research`:`main`,commandName:`parse-prd`,prompt:e.prompt,systemPrompt:e.systemPrompt,schema:e.config.schema,outputFormat:e.config.outputFormat||`text`,projectRoot:e.config.projectRoot,session:e.config.session}),r=n?.mainResult||n;if(r&&Array.isArray(r.tasks)&&(r.tasks=r.tasks.map(e=>({...e,dependencies:e.dependencies??[],priority:e.priority??null,details:e.details??null,testStrategy:e.testStrategy??null}))),r&&Array.isArray(r.tasks)){if(e.progressTracker){for(let t=0;t<r.tasks.length;t++){let n=r.tasks[t];n&&n.title&&e.progressTracker.addTaskLine(t+1,n.title,n.priority||e.defaultPriority)}let t=n.telemetryData?.outputTokens||cs(JSON.stringify(r)),i=n.telemetryData?.inputTokens||e.estimatedInputTokens;e.progressTracker.updateTokens(i,t,!1)}return{parsedTasks:r.tasks,estimatedOutputTokens:n.telemetryData?.outputTokens||cs(JSON.stringify(r)),actualInputTokens:n.telemetryData?.inputTokens,telemetryData:n.telemetryData,usedFallback:!0}}throw Error(`Failed to generate tasks using generateObject fallback`)}function mc(e,t,n,r){let i=null;if(r&&(i=r.getSummary(),r.cleanup()),e.usage&&t){let n=e.usage;t.usage||={promptTokens:n.promptTokens||0,completionTokens:n.completionTokens||0,totalTokens:n.totalTokens||0}}return{parsedTasks:e.parsedTasks,aiServiceResponse:t,estimatedInputTokens:e.actualInputTokens||n,estimatedOutputTokens:e.estimatedOutputTokens,usedFallback:e.usedFallback,progressTracker:r,summary:i}}async function hc(e,t,n){let r=new Go(e.mcpLog,e.reportProgress);r.report(`Parsing PRD file: ${e.prdPath}, Force: ${e.force}, Append: ${e.append}, Research: ${e.research}`,`debug`);try{let{existingTasks:i,nextId:a}=us(e.tasksPath,e.targetTag);ds({existingTasks:i,targetTag:e.targetTag,append:e.append,force:e.force,isMCP:e.isMCP,logger:r});let o=await t(e,await hs(e,ls(e.prdPath),a),e.numTasks),s=he(e.projectRoot)||`medium`,c=fs(o.parsedTasks,a,i,s),l=e.append?[...i,...c]:c;return ms(e.tasksPath,l,e.targetTag,r),await gc(e,o,c,l,a,n),{success:!0,tasksPath:e.tasksPath,telemetryData:o.aiServiceResponse?.telemetryData,tagInfo:o.aiServiceResponse?.tagInfo}}catch(t){throw r.report(`Error parsing PRD: ${t.message}`,`error`),e.isMCP||(console.error(B.red(`Error: ${t.message}`)),je(e.projectRoot)&&console.error(t)),t}}async function gc(e,t,n,r,i,a){let{aiServiceResponse:o,estimatedInputTokens:s,estimatedOutputTokens:c}=t;if(e.reportProgress){let t=o?.telemetryData&&(o.telemetryData.inputTokens>0||o.telemetryData.outputTokens>0),n;if(t){let e=o.telemetryData.totalCost||0,t=o.telemetryData.currency||`USD`;n=`✅ Task Generation Completed | Tokens (I/O): ${o.telemetryData.inputTokens}/${o.telemetryData.outputTokens} | Cost: ${t===`USD`?`$`:t}${e.toFixed(4)}`}else n=`✅ Task Generation Completed | ~Tokens (I/O): ${s}/${a?c:`unknown`} | Cost: ~$0.00`;await e.reportProgress({progress:e.numTasks,total:e.numTasks,message:n})}e.outputFormat===`text`&&!e.isMCP&&(a&&t.summary?await _s({processedTasks:n,nextId:i,summary:t.summary,prdPath:e.prdPath,tasksPath:e.tasksPath,usedFallback:t.usedFallback,aiServiceResponse:o}):a||vs({processedTasks:n,research:e.research,finalTasks:r,tasksPath:e.tasksPath,aiServiceResponse:o}))}async function _c(e,t,n,r={}){return hc(new Wo(e,t,n,r),Qs,!0)}async function vc(e,t,n,r={}){return hc(new Wo(e,t,n,r),ys,!1)}async function yc(e,t,n,r={}){let i=new Wo(e,t,n,r);if(i.useStreaming)try{return await _c(e,t,n,r)}catch(a){if(a instanceof Ro||a.code===zo.NOT_ASYNC_ITERABLE||a.code===zo.STREAM_PROCESSING_FAILED||a.code===zo.STREAM_NOT_ITERABLE||Bo.isTimeoutError(a)){let o=new Go(i.mcpLog,i.reportProgress);return i.outputFormat===`text`&&!i.isMCP?console.log(B.yellow(`⚠️ Streaming operation ${a.message.includes(`timed out`)?`timed out`:`failed`}. Falling back to non-streaming mode...`)):o.report(`Streaming failed (${a.message}), falling back to non-streaming mode...`,`warn`),await vc(e,t,n,r)}else throw a}else return await vc(e,t,n,r)}var bc=yc;async function xc(e,t,n=!1,r=!1,i={}){let{projectRoot:a,tag:o}=i;try{z(`info`,`Removing subtask ${t}...`);let r=D(e,a,o);if(!r||!r.tasks)throw Error(`Invalid or missing tasks file at ${e}`);if(!t.includes(`.`))throw Error(`Invalid subtask ID format: ${t}. Expected format: "parentId.subtaskId"`);let[i,s]=t.split(`.`),c=parseInt(i,10),l=parseInt(s,10),u=r.tasks.find(e=>e.id===c);if(!u)throw Error(`Parent task with ID ${c} not found`);if(!u.subtasks||u.subtasks.length===0)throw Error(`Parent task ${c} has no subtasks`);let d=u.subtasks.findIndex(e=>e.id===l);if(d===-1)throw Error(`Subtask ${t} not found`);let f={...u.subtasks[d]};u.subtasks.splice(d,1),u.subtasks.length===0&&(u.subtasks=void 0);let p=null;if(n){z(`info`,`Converting subtask ${t} to a standalone task...`);let e=Math.max(...r.tasks.map(e=>e.id))+1;p={id:e,title:f.title,description:f.description||``,details:f.details||``,status:f.status||`pending`,dependencies:f.dependencies||[],priority:u.priority||`medium`},p.dependencies.includes(c)||p.dependencies.push(c),r.tasks.push(p),z(`info`,`Created new task ${e} from subtask ${t}`)}else z(`info`,`Subtask ${t} deleted`);return y(e,r,a,o),p}catch(e){throw z(`error`,`Error removing subtask: ${e.message}`),e}}var Sc=xc;function Cc(e,t){if(typeof t==`string`&&t.includes(`.`)){let n=t.split(`.`);if(n.length!==2||!n[0]||!n[1]){let n=parseInt(t,10);return e.some(e=>e.id===n)}let[r,i]=n,a=parseInt(r,10),o=parseInt(i,10),s=e.find(e=>e.id===a);return s&&s.subtasks&&s.subtasks.some(e=>e.id===o)}let n=parseInt(t,10);return e.some(e=>e.id===n)}var wc=Cc;async function Tc(e,t,n={}){let{projectRoot:r,tag:i}=n,a={success:!0,messages:[],errors:[],removedTasks:[]},o=t.split(`,`).map(e=>e.trim()).filter(Boolean);if(o.length===0)return a.success=!1,a.errors.push(`No valid task IDs provided.`),a;try{let t=D(e,r,i);if(!t)throw Error(`Could not read tasks file at ${e}`);let n=t._rawTaggedData||t;if(!n[i]||!n[i].tasks)throw Error(`Tag '${i}' not found or has no tasks.`);let s=n[i].tasks,c=[];for(let e of o){if(!wc(s,e)){let t=`Task with ID ${e} in tag '${i}' not found or already removed.`;a.errors.push(t),a.success=!1;continue}try{if(typeof e==`string`&&e.includes(`.`)){let[t,n]=e.split(`.`).map(e=>parseInt(e,10)),r=s.find(e=>e.id===t);if(!r||!r.subtasks)throw Error(`Parent task ${t} or its subtasks not found for subtask ${e}`);let o=r.subtasks.findIndex(e=>e.id===n);if(o===-1)throw Error(`Subtask ${n} not found in parent task ${t}`);let c={...r.subtasks[o],parentTaskId:t};a.removedTasks.push(c),r.subtasks.splice(o,1),a.messages.push(`Successfully removed subtask ${e} from tag '${i}'`)}else{let t=parseInt(e,10),n=s.findIndex(e=>e.id===t);if(n===-1)throw Error(`Task with ID ${e} not found in tag '${i}'`);let r=s[n];a.removedTasks.push(r),c.push(t),s.splice(n,1),a.messages.push(`Successfully removed task ${e} from tag '${i}'`)}}catch(t){let n=`Error processing ID ${e}: ${t.message}`;a.errors.push(n),a.success=!1,z(`warn`,n)}}if(a.removedTasks.length>0){let t=new Set(o.map(e=>typeof e==`string`&&e.includes(`.`)?e:parseInt(e,10)));for(let e in n[i].tasks=s,n)Object.prototype.hasOwnProperty.call(n,e)&&n[e]&&n[e].tasks&&n[e].tasks.forEach(e=>{e.dependencies&&=e.dependencies.filter(e=>!t.has(e)),e.subtasks&&e.subtasks.forEach(n=>{n.dependencies&&=n.dependencies.filter(n=>!t.has(`${e.id}.${n}`)&&!t.has(n))})});y(e,n,r,i);for(let t of c){let n=H.join(H.dirname(e),`task_${t.toString().padStart(3,`0`)}.txt`);if(qe.existsSync(n))try{qe.unlinkSync(n),a.messages.push(`Deleted task file: ${n}`)}catch(e){let t=`Failed to delete task file ${n}: ${e.message}`;a.errors.push(t),a.success=!1,z(`warn`,t)}}}else a.errors.length===0&&a.messages.push(`No tasks found matching the provided IDs.`);let l=a.messages.join(`
|
|
870
|
+
`).start());try{n.report(`Calling AI service to generate tasks from PRD${e.research?` with research-backed analysis`:``}...`,`info`);let t=await i({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:Uo,objectName:`tasks_data`,systemPrompt:r,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),c=null;if(t?.mainResult&&(typeof t.mainResult==`object`&&t.mainResult!==null&&`tasks`in t.mainResult?c=t.mainResult:typeof t.mainResult.object==`object`&&t.mainResult.object!==null&&`tasks`in t.mainResult.object&&(c=t.mainResult.object)),!c||!Array.isArray(c.tasks))throw Error(`AI service returned unexpected data structure after validation.`);return s&&s.succeed(`Tasks generated successfully!`),{parsedTasks:c.tasks,aiServiceResponse:t,estimatedInputTokens:o}}catch(e){throw s&&s.fail(`Error parsing PRD: ${e.message}`),e}}const[bs,xs,Ss]=Qi,Cs=new Map;var ws=class{constructor(e,t,n,r=null){this.name=e,this.levels=t,this.colors=n,this.thresholds=r}getColor(e){return this.colors[e]||B.gray}getLevelFromScore(e){if(!this.thresholds)throw Error(`${this.name} does not support score-based levels`);return e>=7?this.levels[0]:e<=3?this.levels[2]:this.levels[1]}};const Ts={cli:{filled:`●`,empty:`○`},statusBar:{high:`⋮`,medium:`:`,low:`.`},mcp:{high:`🔴`,medium:`🟠`,low:`🟢`}},Es=new ws(`priority`,[bs,xs,Ss],{[bs]:B.hex(`#CC0000`),[xs]:B.hex(`#FF8800`),[Ss]:B.yellow});function Ds(e,t){let n=Ts.cli.filled,r=Ts.cli.empty,i=``;for(let a=0;a<3;a++)a<e?i+=t(n):i+=B.white(r);return i}function Os(e,t){return 3-t.indexOf(e)}function ks(e,t){if(Cs.has(e))return Cs.get(e);let n=t();return Cs.set(e,n),n}function As(){return ks(`mcp-priority-all`,()=>({[bs]:Ts.mcp.high,[xs]:Ts.mcp.medium,[Ss]:Ts.mcp.low}))}function js(){return ks(`cli-priority-all`,()=>{let e={};return Es.levels.forEach(t=>{e[t]=Ds(Os(t,Es.levels),Es.getColor(t))}),e})}function Ms(){return ks(`statusbar-priority-all`,()=>{let e={};return Es.levels.forEach((t,n)=>{let r=n===0?Ts.statusBar.high:n===1?Ts.statusBar.medium:Ts.statusBar.low;e[t]=Es.getColor(t)(r)}),e})}function Ns(){return{[bs]:Es.colors[bs],[xs]:Es.colors[xs],[Ss]:Es.colors[Ss]}}function Ps(e=!1){return e?As():js()}function Fs(e,t=!1){let n=Ps(t);return n[e]||n[xs]}new ws(`complexity`,[`high`,`medium`,`low`],{high:B.hex(`#CC0000`),medium:B.hex(`#FF8800`),low:B.green},{high:e=>e>=7,medium:e=>e>=4&&e<=6,low:e=>e<=3});const Is={clearOnComplete:!1,stopOnComplete:!0,hideCursor:!0,barsize:40},Ls={shades_classic:mt.Presets.shades_classic,shades_grey:mt.Presets.shades_grey,rect:mt.Presets.rect,legacy:mt.Presets.legacy},Rs=new class{constructor(e={},t=Ls.shades_classic){this.defaultOptions={...Is,...e},this.defaultPreset=t}createSingleBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new mt.SingleBar(n,r)}createMultiBar(e={},t=null){let n=this._mergeConfig(e),r=t||this.defaultPreset;return new mt.MultiBar(n,r)}_mergeConfig(e){return{...this.defaultOptions,...e}}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}setDefaultPreset(e){this.defaultPreset=e}};function zs(e={}){return Rs.createMultiBar(e)}var Bs=class{constructor(e={}){this.numUnits=e.numUnits||1,this.unitName=e.unitName||`unit`,this.startTime=null,this.completedUnits=0,this.tokensIn=0,this.tokensOut=0,this.isEstimate=!0,this.bestAvgTimePerUnit=null,this.lastEstimateTime=null,this.lastEstimateSeconds=0,this.multibar=null,this.timeTokensBar=null,this.progressBar=null,this._timerInterval=null,this.isStarted=!1,this.isFinished=!1,this._initializeCustomProperties(e)}_initializeCustomProperties(e){}get unitNamePlural(){return`${this.unitName}s`}start(){this.isStarted||this.isFinished||(this.isStarted=!0,this.startTime=Date.now(),this.multibar=zs(),this.timeTokensBar=this.multibar.create(1,0,{},{format:this._getTimeTokensBarFormat(),barsize:1,hideCursor:!0,clearOnComplete:!1}),this.progressBar=this.multibar.create(this.numUnits,0,{},{format:this._getProgressBarFormat(),barCompleteChar:`█`,barIncompleteChar:`░`}),this._updateTimeTokensBar(),this.progressBar.update(0,{[this.unitNamePlural]:`0/${this.numUnits}`}),this._timerInterval=setInterval(()=>this._updateTimeTokensBar(),1e3),this._setupCustomUI())}_setupCustomUI(){}_getTimeTokensBarFormat(){return`{clock} {elapsed} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`${this.unitName.charAt(0).toUpperCase()+this.unitName.slice(1)}s {${this.unitNamePlural}} |{bar}| {percentage}%`}updateTokens(e,t,n=!1){this.tokensIn=e||0,this.tokensOut=t||0,this.isEstimate=n,this._updateTimeTokensBar()}_updateTimeTokensBar(){if(!this.timeTokensBar||this.isFinished)return;let e=this._formatElapsedTime(),t=this._estimateRemainingTime(),n=this.isEstimate?`~ Tokens (I/O)`:`Tokens (I/O)`;this.timeTokensBar.update(1,{clock:`⏱️`,elapsed:e,in:this.tokensIn,out:this.tokensOut,remaining:t,tokensLabel:n,...this._getCustomTimeTokensPayload()})}_getCustomTimeTokensPayload(){return{}}_formatElapsedTime(){if(!this.startTime)return`0m 00s`;let e=Math.floor((Date.now()-this.startTime)/1e3);return`${Math.floor(e/60)}m ${(e%60).toString().padStart(2,`0`)}s`}_estimateRemainingTime(){let e=this._getProgressFraction();if(e>=1)return`~0s`;let t=Date.now(),n=(t-this.startTime)/1e3;if(e===0)return`~calculating...`;let r=n/e;(this.bestAvgTimePerUnit===null||r<this.bestAvgTimePerUnit)&&(this.bestAvgTimePerUnit=r);let i=this.numUnits*(1-e),a=Math.ceil(i*this.bestAvgTimePerUnit);if(this.lastEstimateTime){let e=Math.floor((t-this.lastEstimateTime)/1e3),n=Math.max(0,this.lastEstimateSeconds-e);if(n===0)return`~0s`;a=Math.min(a,n)}return this.lastEstimateTime=t,this.lastEstimateSeconds=a,`~${this._formatDuration(a)}`}_getProgressFraction(){return this.completedUnits/this.numUnits}_formatDuration(e){if(e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;return t<60?n>0?`${t}m ${n}s`:`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}getElapsedTime(){return this.startTime?Date.now()-this.startTime:0}stop(){this.isFinished||(this.isFinished=!0,this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar&&(this._updateTimeTokensBar(),this.multibar.stop()),this.cleanup())}getSummary(){return{completedUnits:this.completedUnits,elapsedTime:this.getElapsedTime()}}cleanup(){if(this._timerInterval&&=(clearInterval(this._timerInterval),null),this.multibar){try{this.multibar.stop()}catch{}this.multibar=null}this.timeTokensBar=null,this.progressBar=null,this.isStarted=!1,this.isFinished=!0,this._performCustomCleanup()}_performCustomCleanup(){}},Vs=class{constructor(e){if(!e)throw Error(`Multibar instance is required`);this.multibar=e}createBar(e,t={}){if(typeof e!=`string`)throw Error(`Format must be a string`);let n=this.multibar.create(1,1,{},{format:e,barsize:1,hideCursor:!0,clearOnComplete:!1});return n.update(1,t),n}createHeader(e,t){this.createBar(t),this.createBar(e),this.createBar(t)}createRow(e,t){if(!t||typeof t!=`object`)throw Error(`Payload must be an object`);return this.createBar(e,t)}createBorder(e){return this.createBar(e)}};function Hs(e,t,n){new Vs(e).createHeader(t,n)}function Us(e,t,n){new Vs(e).createRow(t,n)}function Ws(e,t){new Vs(e).createBorder(t)}js();const Gs=Ms();Ns();const Ks={DEBOUNCE_DELAY:100,MAX_TITLE_LENGTH:57,TRUNCATED_LENGTH:54,TASK_ID_PAD_START:3,TASK_ID_PAD_END:4,PRIORITY_PAD_END:3,VALID_PRIORITIES:[`high`,`medium`,`low`],DEFAULT_PRIORITY:`medium`};var qs=class{constructor(e=Ks.DEBOUNCE_DELAY){this.delay=e,this.pendingTimeout=null}debounce(e){this.clear(),this.pendingTimeout=setTimeout(()=>{e(),this.pendingTimeout=null},this.delay)}clear(){this.pendingTimeout&&=(clearTimeout(this.pendingTimeout),null)}hasPending(){return this.pendingTimeout!==null}},Js=class{constructor(){this.priorities={high:0,medium:0,low:0}}increment(e){let t=this.normalize(e);return this.priorities[t]++,t}normalize(e){let t=e?e.toLowerCase():Ks.DEFAULT_PRIORITY;return Ks.VALID_PRIORITIES.includes(t)?t:Ks.DEFAULT_PRIORITY}getCounts(){return{...this.priorities}}},Ys=class{static formatTitle(e,t){return e?e.length>Ks.MAX_TITLE_LENGTH?e.substring(0,Ks.TRUNCATED_LENGTH)+`...`:e:`Task ${t}`}static formatPriority(e){return Fs(e,!1).padEnd(Ks.PRIORITY_PAD_END,` `)}static formatTaskId(e){return e.toString().padStart(Ks.TASK_ID_PAD_START,` `).padEnd(Ks.TASK_ID_PAD_END,` `)}},Xs=class extends Bs{_initializeCustomProperties(e){this.append=e.append,this.priorityManager=new Js,this.debouncer=new qs,this.headerShown=!1}_getTimeTokensBarFormat(){return`{clock} {elapsed} | ${Gs.high} {high} ${Gs.medium} {medium} ${Gs.low} {low} | Tokens (I/O): {in}/{out} | Est: {remaining}`}_getProgressBarFormat(){return`Tasks {tasks} |{bar}| {percentage}%`}_getCustomTimeTokensPayload(){return this.priorityManager.getCounts()}addTaskLine(e,t,n=`medium`){if(!this.multibar||this.isFinished)return;this._ensureHeaderShown();let r=this._updateTaskCounters(e,n);this._updateTimeTokensBar(),this.debouncer.debounce(()=>{this._updateProgressDisplay(e,t,r)})}_ensureHeaderShown(){this.headerShown||(this.headerShown=!0,Hs(this.multibar,` TASK | PRI | TITLE`,`------+-----+----------------------------------------------------------------`))}_updateTaskCounters(e,t){let n=this.priorityManager.increment(t);return this.completedUnits=e,n}_updateProgressDisplay(e,t,n){this.progressBar.update(this.completedUnits,{tasks:`${this.completedUnits}/${this.numUnits}`});let r=Ys.formatTitle(t,e),i=Ys.formatPriority(n),a=Ys.formatTaskId(e);Us(this.multibar,` ${a} | ${i} | {title}`,{title:r}),Ws(this.multibar,`------+-----+----------------------------------------------------------------`),this._updateTimeTokensBar()}finish(){this.debouncer.hasPending()&&(this.debouncer.clear(),this._updateTimeTokensBar()),this.cleanup(),super.finish()}_performCustomCleanup(){this.debouncer.clear()}getSummary(){return{...super.getSummary(),taskPriorities:this.priorityManager.getCounts(),actionVerb:this.append?`appended`:`generated`}}};function Zs(e={}){return new Xs(e)}async function Qs(e,t,n){let r=$s(e,t,n);await tc(e,n,r.estimatedInputTokens);let i=await nc(e,t,e.streamingTimeout),{progressTracker:a,priorityMap:o}=await rc(e,n),s=await ic(i.mainResult,e,t,n,a,o,r.defaultPriority,r.estimatedInputTokens,r.logger);if(ec(s),s.usage&&e.projectRoot){let{logAiUsage:t}=await import(`./ai-services-unified--KinsHuW.js`),{getUserId:n}=await import(`./config-manager-BiA1Lh9-.js`),a=n(e.projectRoot);if(a&&i.providerName&&i.modelId)try{let n=await t({userId:a,commandName:`parse-prd`,providerName:i.providerName,modelId:i.modelId,inputTokens:s.usage.promptTokens||0,outputTokens:s.usage.completionTokens||0,outputType:e.isMCP?`mcp`:`cli`});n&&(i.telemetryData=n)}catch(e){r.logger.report(`Failed to log telemetry: ${e.message}`,`debug`)}}return mc(s,i,r.estimatedInputTokens,a)}function $s(e,t,n){let{systemPrompt:r,userPrompt:i}=t;return{logger:new Go(e.mcpLog,e.reportProgress),estimatedInputTokens:cs(r+i),defaultPriority:he(e.projectRoot)||`medium`}}function ec(e){if(e.parsedTasks.length===0)throw Error(`No tasks were generated from the PRD`)}async function tc(e,t,n){e.reportProgress&&await e.reportProgress({progress:0,total:t,message:`Starting PRD analysis (Input: ${n} tokens)${e.research?` with research`:``}...`})}async function nc(e,n,r){let{systemPrompt:i,userPrompt:a}=n;return await Bo.withTimeout(t({role:e.research?`research`:`main`,session:e.session,projectRoot:e.projectRoot,schema:Uo,systemPrompt:i,prompt:a,commandName:`parse-prd`,outputType:e.isMCP?`mcp`:`cli`}),r,`Streaming operation`)}async function rc(e,t){let n=Ps(e.isMCP),r=null;if(e.outputFormat===`text`&&!e.isMCP){r=Zs({numUnits:t,unitName:`task`,append:e.append});let n=e.research?o():T(),i=f(e.research?`research`:`main`);es({prdFilePath:e.prdPath,outputPath:e.tasksPath,numTasks:t,append:e.append,research:e.research,force:e.force,existingTasks:[],nextId:1,model:n||`Default`,temperature:i?.temperature||.7}),r.start()}return{progressTracker:r,priorityMap:n}}async function ic(e,t,n,r,i,a,o,s,c){let{systemPrompt:l,userPrompt:u}=n,d={config:{...t,schema:Uo},numTasks:r,progressTracker:i,priorityMap:a,defaultPriority:o,estimatedInputTokens:s,prompt:u,systemPrompt:l};try{let t={lastPartialObject:null,taskCount:0,estimatedOutputTokens:0,usage:null};if(await ac(e.partialObjectStream,t,d),e.usage)try{t.usage=await e.usage}catch(e){c.report(`Failed to get usage data: ${e.message}`,`debug`)}return lc(t,d)}catch(e){return c.report(`StreamObject processing failed: ${e.message}. Falling back to generateObject.`,`debug`),await pc(d,c)}}async function ac(e,t,n){for await(let r of e)t.lastPartialObject=r,r&&(t.estimatedOutputTokens=cs(JSON.stringify(r))),await oc(r,t,n)}async function oc(e,t,n){if(!e?.tasks||!Array.isArray(e.tasks))return;let r=e.tasks.length;r>t.taskCount?(await sc(e.tasks,t.taskCount,r,t.estimatedOutputTokens,n),t.taskCount=r):n.progressTracker&&t.estimatedOutputTokens>0&&n.progressTracker.updateTokens(n.estimatedInputTokens,t.estimatedOutputTokens,!0)}async function sc(e,t,n,r,i){for(let a=t;a<n;a++){let t=e[a]||{};t.title?await gs({task:t,currentCount:a+1,totalTasks:i.numTasks,estimatedTokens:r,progressTracker:i.progressTracker,reportProgress:i.config.reportProgress,priorityMap:i.priorityMap,defaultPriority:i.defaultPriority,estimatedInputTokens:i.estimatedInputTokens}):await cc(a+1,r,i)}}async function cc(e,t,n){let{progressTracker:r,config:i,numTasks:a,defaultPriority:o,estimatedInputTokens:s}=n;r&&(r.addTaskLine(e,`Generating task ${e}...`,o),r.updateTokens(s,t,!0)),i.reportProgress&&!r&&await i.reportProgress({progress:e,total:a,message:`Generating task ${e}/${a}...`})}async function lc(e,t){let{lastPartialObject:n,estimatedOutputTokens:r,taskCount:i,usage:a}=e;if(!n?.tasks||!Array.isArray(n.tasks))throw Error(`No tasks generated from streamObject`);let o=a?.completionTokens||r,s=a?.promptTokens||t.estimatedInputTokens;return t.progressTracker&&await uc(n.tasks,i,a?o:r,t,a?s:null),{parsedTasks:n.tasks,estimatedOutputTokens:o,actualInputTokens:s,usage:a,usedFallback:!1}}async function uc(e,t,n,r,i=null){let{progressTracker:a,defaultPriority:o,estimatedInputTokens:s}=r;t>0?dc(e,a,o):await fc(e,n,r),a.updateTokens(i||s,n,!1),a.stop()}function dc(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&t.addTaskLine(r+1,i.title,i.priority||n)}}async function fc(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];i?.title&&await gs({task:i,currentCount:r+1,totalTasks:n.numTasks,estimatedTokens:t,progressTracker:n.progressTracker,reportProgress:n.config.reportProgress,priorityMap:n.priorityMap,defaultPriority:n.defaultPriority,estimatedInputTokens:n.estimatedInputTokens})}}async function pc(e,t){if(t.report(`Using generateObject fallback for PRD parsing`,`info`),e.progressTracker)for(let t=0;t<e.numTasks;t++)e.progressTracker.addTaskLine(t+1,`Generating task ${t+1}...`,e.defaultPriority),e.progressTracker.updateTokens(e.estimatedInputTokens,0,!0);let n=await i({role:e.config.research?`research`:`main`,commandName:`parse-prd`,prompt:e.prompt,systemPrompt:e.systemPrompt,schema:e.config.schema,outputFormat:e.config.outputFormat||`text`,projectRoot:e.config.projectRoot,session:e.config.session}),r=n?.mainResult||n;if(r&&Array.isArray(r.tasks)&&(r.tasks=r.tasks.map(e=>({...e,dependencies:e.dependencies??[],priority:e.priority??null,details:e.details??null,testStrategy:e.testStrategy??null}))),r&&Array.isArray(r.tasks)){if(e.progressTracker){for(let t=0;t<r.tasks.length;t++){let n=r.tasks[t];n&&n.title&&e.progressTracker.addTaskLine(t+1,n.title,n.priority||e.defaultPriority)}let t=n.telemetryData?.outputTokens||cs(JSON.stringify(r)),i=n.telemetryData?.inputTokens||e.estimatedInputTokens;e.progressTracker.updateTokens(i,t,!1)}return{parsedTasks:r.tasks,estimatedOutputTokens:n.telemetryData?.outputTokens||cs(JSON.stringify(r)),actualInputTokens:n.telemetryData?.inputTokens,telemetryData:n.telemetryData,usedFallback:!0}}throw Error(`Failed to generate tasks using generateObject fallback`)}function mc(e,t,n,r){let i=null;if(r&&(i=r.getSummary(),r.cleanup()),e.usage&&t){let n=e.usage;t.usage||={promptTokens:n.promptTokens||0,completionTokens:n.completionTokens||0,totalTokens:n.totalTokens||0}}return{parsedTasks:e.parsedTasks,aiServiceResponse:t,estimatedInputTokens:e.actualInputTokens||n,estimatedOutputTokens:e.estimatedOutputTokens,usedFallback:e.usedFallback,progressTracker:r,summary:i}}async function hc(e,t,n){let r=new Go(e.mcpLog,e.reportProgress);r.report(`Parsing PRD file: ${e.prdPath}, Force: ${e.force}, Append: ${e.append}, Research: ${e.research}`,`debug`);try{let{existingTasks:i,nextId:a}=us(e.tasksPath,e.targetTag);ds({existingTasks:i,targetTag:e.targetTag,append:e.append,force:e.force,isMCP:e.isMCP,logger:r});let o=await t(e,await hs(e,ls(e.prdPath),a),e.numTasks),s=he(e.projectRoot)||`medium`,c=fs(o.parsedTasks,a,i,s),l=e.append?[...i,...c]:c;return ms(e.tasksPath,l,e.targetTag,r),await gc(e,o,c,l,a,n),{success:!0,tasksPath:e.tasksPath,telemetryData:o.aiServiceResponse?.telemetryData,tagInfo:o.aiServiceResponse?.tagInfo}}catch(t){throw r.report(`Error parsing PRD: ${t.message}`,`error`),e.isMCP||(console.error(B.red(`Error: ${t.message}`)),je(e.projectRoot)&&console.error(t)),t}}async function gc(e,t,n,r,i,a){let{aiServiceResponse:o,estimatedInputTokens:s,estimatedOutputTokens:c}=t;if(e.reportProgress){let t=o?.telemetryData&&(o.telemetryData.inputTokens>0||o.telemetryData.outputTokens>0),n;if(t){let e=o.telemetryData.totalCost||0,t=o.telemetryData.currency||`USD`;n=`✅ Task Generation Completed | Tokens (I/O): ${o.telemetryData.inputTokens}/${o.telemetryData.outputTokens} | Cost: ${t===`USD`?`$`:t}${e.toFixed(4)}`}else n=`✅ Task Generation Completed | ~Tokens (I/O): ${s}/${a?c:`unknown`} | Cost: ~$0.00`;await e.reportProgress({progress:e.numTasks,total:e.numTasks,message:n})}e.outputFormat===`text`&&!e.isMCP&&(a&&t.summary?await _s({processedTasks:n,nextId:i,summary:t.summary,prdPath:e.prdPath,tasksPath:e.tasksPath,usedFallback:t.usedFallback,aiServiceResponse:o}):a||vs({processedTasks:n,research:e.research,finalTasks:r,tasksPath:e.tasksPath,aiServiceResponse:o}))}async function _c(e,t,n,r={}){return hc(new Wo(e,t,n,r),Qs,!0)}async function vc(e,t,n,r={}){return hc(new Wo(e,t,n,r),ys,!1)}async function yc(e,t,n,r={}){let i=new Wo(e,t,n,r);if(i.useStreaming)try{return await _c(e,t,n,r)}catch(a){if(a instanceof Ro||a.code===zo.NOT_ASYNC_ITERABLE||a.code===zo.STREAM_PROCESSING_FAILED||a.code===zo.STREAM_NOT_ITERABLE||Bo.isTimeoutError(a)){let o=new Go(i.mcpLog,i.reportProgress);return i.outputFormat===`text`&&!i.isMCP?console.log(B.yellow(`⚠️ Streaming operation ${a.message.includes(`timed out`)?`timed out`:`failed`}. Falling back to non-streaming mode...`)):o.report(`Streaming failed (${a.message}), falling back to non-streaming mode...`,`warn`),await vc(e,t,n,r)}else throw a}else return await vc(e,t,n,r)}var bc=yc;async function xc(e,t,n=!1,r=!1,i={}){let{projectRoot:a,tag:o}=i;try{z(`info`,`Removing subtask ${t}...`);let r=D(e,a,o);if(!r||!r.tasks)throw Error(`Invalid or missing tasks file at ${e}`);if(!t.includes(`.`))throw Error(`Invalid subtask ID format: ${t}. Expected format: "parentId.subtaskId"`);let[i,s]=t.split(`.`),c=parseInt(i,10),l=parseInt(s,10),u=r.tasks.find(e=>e.id===c);if(!u)throw Error(`Parent task with ID ${c} not found`);if(!u.subtasks||u.subtasks.length===0)throw Error(`Parent task ${c} has no subtasks`);let d=u.subtasks.findIndex(e=>e.id===l);if(d===-1)throw Error(`Subtask ${t} not found`);let f={...u.subtasks[d]};u.subtasks.splice(d,1),u.subtasks.length===0&&(u.subtasks=void 0);let p=null;if(n){z(`info`,`Converting subtask ${t} to a standalone task...`);let e=Math.max(...r.tasks.map(e=>e.id))+1;p={id:e,title:f.title,description:f.description||``,details:f.details||``,status:f.status||`pending`,dependencies:f.dependencies||[],priority:u.priority||`medium`},p.dependencies.includes(c)||p.dependencies.push(c),r.tasks.push(p),z(`info`,`Created new task ${e} from subtask ${t}`)}else z(`info`,`Subtask ${t} deleted`);return y(e,r,a,o),p}catch(e){throw z(`error`,`Error removing subtask: ${e.message}`),e}}var Sc=xc;function Cc(e,t){if(typeof t==`string`&&t.includes(`.`)){let n=t.split(`.`);if(n.length!==2||!n[0]||!n[1]){let n=parseInt(t,10);return e.some(e=>e.id===n)}let[r,i]=n,a=parseInt(r,10),o=parseInt(i,10),s=e.find(e=>e.id===a);return s&&s.subtasks&&s.subtasks.some(e=>e.id===o)}let n=parseInt(t,10);return e.some(e=>e.id===n)}var wc=Cc;async function Tc(e,t,n={}){let{projectRoot:r,tag:i}=n,a={success:!0,messages:[],errors:[],removedTasks:[]},o=t.split(`,`).map(e=>e.trim()).filter(Boolean);if(o.length===0)return a.success=!1,a.errors.push(`No valid task IDs provided.`),a;try{let t=D(e,r,i);if(!t)throw Error(`Could not read tasks file at ${e}`);let n=t._rawTaggedData||t;if(!n[i]||!n[i].tasks)throw Error(`Tag '${i}' not found or has no tasks.`);let s=n[i].tasks,c=[];for(let e of o){if(!wc(s,e)){let t=`Task with ID ${e} in tag '${i}' not found or already removed.`;a.errors.push(t),a.success=!1;continue}try{if(typeof e==`string`&&e.includes(`.`)){let[t,n]=e.split(`.`).map(e=>parseInt(e,10)),r=s.find(e=>e.id===t);if(!r||!r.subtasks)throw Error(`Parent task ${t} or its subtasks not found for subtask ${e}`);let o=r.subtasks.findIndex(e=>e.id===n);if(o===-1)throw Error(`Subtask ${n} not found in parent task ${t}`);let c={...r.subtasks[o],parentTaskId:t};a.removedTasks.push(c),r.subtasks.splice(o,1),a.messages.push(`Successfully removed subtask ${e} from tag '${i}'`)}else{let t=parseInt(e,10),n=s.findIndex(e=>e.id===t);if(n===-1)throw Error(`Task with ID ${e} not found in tag '${i}'`);let r=s[n];a.removedTasks.push(r),c.push(t),s.splice(n,1),a.messages.push(`Successfully removed task ${e} from tag '${i}'`)}}catch(t){let n=`Error processing ID ${e}: ${t.message}`;a.errors.push(n),a.success=!1,z(`warn`,n)}}if(a.removedTasks.length>0){let t=new Set(o.map(e=>typeof e==`string`&&e.includes(`.`)?e:parseInt(e,10)));for(let e in n[i].tasks=s,n)Object.prototype.hasOwnProperty.call(n,e)&&n[e]&&n[e].tasks&&n[e].tasks.forEach(e=>{e.dependencies&&=e.dependencies.filter(e=>!t.has(e)),e.subtasks&&e.subtasks.forEach(n=>{n.dependencies&&=n.dependencies.filter(n=>!t.has(`${e.id}.${n}`)&&!t.has(n))})});y(e,n,r,i);for(let t of c){let n=H.join(H.dirname(e),`task_${t.toString().padStart(3,`0`)}.txt`);if(qe.existsSync(n))try{qe.unlinkSync(n),a.messages.push(`Deleted task file: ${n}`)}catch(e){let t=`Failed to delete task file ${n}: ${e.message}`;a.errors.push(t),a.success=!1,z(`warn`,t)}}}else a.errors.length===0&&a.messages.push(`No tasks found matching the provided IDs.`);let l=a.messages.join(`
|
|
871
871
|
`),u=a.errors.join(`
|
|
872
872
|
`);return{success:a.success,message:l||`No tasks were removed.`,error:u||null,removedTasks:a.removedTasks}}catch(e){return z(`error`,`Error removing tasks: ${e.message}`),{success:!1,message:``,error:`Operation failed: ${e.message}`,removedTasks:[]}}}var Ec=Tc;ot.use(st({code:e=>e.split(`
|
|
873
873
|
`).map(e=>` `+B.cyan(e)).join(`
|
|
@@ -885,9 +885,9 @@ ${B.cyan(`1.`)} Run ${B.yellow(`task-master list`)} to view all tasks\n${B.cyan(
|
|
|
885
885
|
`);if(r.push(B.cyan(`Prompts: `)+B.yellow(i.toLocaleString())+B.gray(` (generated)`)+`
|
|
886
886
|
`+a),r.length>0){let e=W(r.join(`
|
|
887
887
|
|
|
888
|
-
`),{title:B.blue.bold(`Context Analysis`),titleAlignment:`left`,padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:1},borderStyle:`single`,borderColor:`blue`});console.log(e)}}async function kc(e,t,n,r,i,a,o){let s=!1;try{let{readJSON:c}=await import(`./utils-
|
|
888
|
+
`),{title:B.blue.bold(`Context Analysis`),titleAlignment:`left`,padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:1},borderStyle:`single`,borderColor:`blue`});console.log(e)}}async function kc(e,t,n,r,i,a,o){let s=!1;try{let{readJSON:c}=await import(`./utils-CtCI5DEr.js`);(await import(`./update-task-by-id-rlGR5O_g.js`)).default;let{updateSubtaskById:l}=await import(`./update-subtask-by-id-D56bbaA6.js`),u=[{question:a,answer:o,type:`initial`,timestamp:new Date().toISOString()}];for(;;){let{action:a}=await q.prompt([{type:`list`,name:`action`,message:`What would you like to do next?`,choices:[{name:`Ask a follow-up question`,value:`followup`},{name:`Save to file`,value:`savefile`},{name:`Save to task/subtask`,value:`save`},{name:`Quit`,value:`quit`}],pageSize:4}]);if(a===`quit`)break;if(a===`savefile`){await jc(u,r,t,i);continue}if(a===`save`){await Ac(u,r,t,i)&&(s=!0);continue}if(a===`followup`){let{followUpQuery:r}=await q.prompt([{type:`input`,name:`followUpQuery`,message:`Enter your follow-up question:`,validate:e=>!e||e.trim().length===0?`Please enter a valid question.`:!0}]);if(!r||r.trim().length===0)continue;console.log(`
|
|
889
889
|
`+B.gray(`─`.repeat(60))+`
|
|
890
|
-
`);let i=Pc(u),a={...e,taskIds:[],customContext:i+(e.customContext?`\n\n--- Original Context ---\n${e.customContext}`:``)},o=await Dc(r.trim(),a,t,n,!1);u.push({question:r.trim(),answer:o.result,type:`followup`,timestamp:new Date().toISOString()})}}}catch(e){i.debug(`Follow-up questions not available: ${e.message}`)}return{interactiveSaveOccurred:s}}async function Ac(e,t,n,r){try{let{readJSON:r}=await import(`./utils-
|
|
890
|
+
`);let i=Pc(u),a={...e,taskIds:[],customContext:i+(e.customContext?`\n\n--- Original Context ---\n${e.customContext}`:``)},o=await Dc(r.trim(),a,t,n,!1);u.push({question:r.trim(),answer:o.result,type:`followup`,timestamp:new Date().toISOString()})}}}catch(e){i.debug(`Follow-up questions not available: ${e.message}`)}return{interactiveSaveOccurred:s}}async function Ac(e,t,n,r){try{let{readJSON:r}=await import(`./utils-CtCI5DEr.js`),i=(await import(`./update-task-by-id-rlGR5O_g.js`)).default,{updateSubtaskById:a}=await import(`./update-subtask-by-id-D56bbaA6.js`),{taskId:o}=await q.prompt([{type:`input`,name:`taskId`,message:`Enter task ID (e.g., "15" for task or "15.2" for subtask):`,validate:e=>{if(!e||e.trim().length===0)return`Please enter a task ID.`;let t=e.trim();return/^\d+(\.\d+)?$/.test(t)?!0:`Invalid format. Use "15" for task or "15.2" for subtask.`}}]),s=o.trim(),c=Nc(e),l=s.includes(`.`),u=H.join(t,`.taskmaster`,`tasks`,`tasks.json`);if(!V.existsSync(u)){console.log(B.red(`❌ Tasks file not found. Please run task-master init first.`));return}let d=r(u,t,n.tag);if(!d||!d.tasks){console.log(B.red(`❌ No valid tasks found.`));return}if(l){let[e,t]=s.split(`.`).map(e=>parseInt(e,10)),r=d.tasks.find(t=>t.id===e);if(!r){console.log(B.red(`❌ Parent task ${e} not found.`));return}if(!r.subtasks||!r.subtasks.find(e=>e.id===t)){console.log(B.red(`❌ Subtask ${s} not found.`));return}console.log(B.blue(`💾 Saving research conversation to subtask...`)),await a(u,s,c,!1,n,`text`),console.log(B.green(`✅ Research conversation saved to subtask ${s}`))}else{let e=parseInt(s,10);if(!d.tasks.find(t=>t.id===e)){console.log(B.red(`❌ Task ${s} not found.`));return}console.log(B.blue(`💾 Saving research conversation to task...`)),await i(u,e,c,!1,n,`text`,!0),console.log(B.green(`✅ Research conversation saved to task ${s}`))}return!0}catch(e){return console.log(B.red(`❌ Error saving conversation: ${e.message}`)),r.error(`Error saving conversation: ${e.message}`),!1}}async function jc(e,t,n,r){try{let n=H.join(t,`.taskmaster`,`docs`,`research`);V.existsSync(n)||V.mkdirSync(n,{recursive:!0});let i=e[0]?.question||`research-query`,a=`${new Date().toISOString().split(`T`)[0]}_${i.toLowerCase().replace(/[^a-z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).substring(0,50).replace(/^-+|-+$/g,``)}.md`,o=H.join(n,a),s=Mc(e,i);V.writeFileSync(o,s,`utf8`);let c=H.relative(t,o);return console.log(B.green(`✅ Research saved to: ${B.cyan(c)}`)),r.success(`Research conversation saved to ${c}`),o}catch(e){throw console.log(B.red(`❌ Error saving research file: ${e.message}`)),r.error(`Error saving research file: ${e.message}`),e}}function Mc(e,t){let n=new Date().toISOString(),r=`---
|
|
891
891
|
title: Research Session
|
|
892
892
|
query: "${t}"
|
|
893
893
|
date: ${new Date().toLocaleDateString()}
|
package/dist/mcp-server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{o as e,s as t}from"./ai-services-unified-
|
|
2
|
+
import{o as e,s as t}from"./ai-services-unified-D0SWrwB5.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-D_uegoOJ.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-BVhvTqG7.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-D56bbaA6.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-rlGR5O_g.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-
|
|
1
|
+
import{c as e}from"./ai-services-unified-D0SWrwB5.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-D_uegoOJ.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-
|
|
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-D0SWrwB5.js";import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{A as e}from"./dependency-manager-D_uegoOJ.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-
|
|
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-
|
|
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-D0SWrwB5.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-D_uegoOJ.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-
|
|
1
|
+
import"./ai-services-unified-D0SWrwB5.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-D_uegoOJ.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};
|
package/dist/task-master.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{U as e,cn as t,hn as n}from"./config-manager-
|
|
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-D_wCc0QR.js`);c(process.argv);export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./ai-services-unified-D0SWrwB5.js";import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{w as e}from"./dependency-manager-D_uegoOJ.js";import"./response-language-DeTA_0Bx.js";export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./ai-services-unified-D0SWrwB5.js";import"./config-manager-Dn_JApjY.js";import"./git-utils-DllbRE35.js";import"./sentry-Dbx7-h6F.js";import{C as e}from"./dependency-manager-D_uegoOJ.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-
|
|
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 +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 +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};
|
|
@@ -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{C as e}from"./dependency-manager-Di3zHzuM.js";import"./response-language-c-DJJiVH.js";export{e as default};
|